diff --git a/Gemfile b/Gemfile index ffcc4cab..11a34b3c 100644 --- a/Gemfile +++ b/Gemfile @@ -41,6 +41,9 @@ gem 'material_icons' gem 'font-awesome-rails', '~> 4.7', '>= 4.7.0.2' gem 'rack-cors' +# Multi-tenancy for shops +gem 'acts_as_tenant' + # image upload gem 'carrierwave', '~> 1.0' gem 'mini_magick' diff --git a/Gemfile.lock b/Gemfile.lock index 633b5965..bbcc1085 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -46,6 +46,9 @@ GEM i18n (>= 0.7, < 2) minitest (~> 5.1) tzinfo (~> 1.1) + acts_as_tenant (0.4.4) + rails (>= 4.0) + request_store (>= 1.0.5) aescrypt (1.0.0) airbrussh (1.4.0) sshkit (>= 1.6.1, != 1.7.0) @@ -219,6 +222,8 @@ GEM rb-inotify (0.10.0) ffi (~> 1.0) redis (3.3.5) + request_store (1.4.1) + rack (>= 1.4) roo (1.13.2) nokogiri rubyzip @@ -315,6 +320,7 @@ PLATFORMS ruby DEPENDENCIES + acts_as_tenant aescrypt axlsx (= 2.0.1) axlsx_rails @@ -374,10 +380,8 @@ DEPENDENCIES web-console (>= 3.3.0) whenever - RUBY VERSION ruby 2.4.1p111 - BUNDLED WITH 2.0.2 diff --git a/README.md b/README.md index 54474f5e..67fcc40b 100755 --- a/README.md +++ b/README.md @@ -288,6 +288,10 @@ For Number Formats => settings/lookups => { lookup_type: number_format, name: strip_insignificant_zeros, value: {true: => ['1', 't', 'true', 'on', 'y', 'yes'], false: => ['0', 'f', 'false', 'off', 'n', 'no', ...] } +For Booking checkin time limit + settings/lookups => + { lookup_type: checkin_time_limit, name: CheckinTimeLimit, value: total hours before checkout (e.g., '48')) } + /* Customer Types in lookups */ 1) settings/lookups => { type:customer_type, name: Dinein, value:Dinein } 2) settings/lookups => { type:customer_type, name: Takeaway, value: Takeaway } diff --git a/app/assets/javascripts/origami_bk.js b/app/assets/javascripts/origami_bk.js index d4071432..aaa05613 100755 --- a/app/assets/javascripts/origami_bk.js +++ b/app/assets/javascripts/origami_bk.js @@ -69,11 +69,11 @@ $(document).ready(function(){ type: "POST", url: "/origami/" + unique_id, data: { 'booking_id' : unique_id }, - success:function(result){ + success:function(result){ for (i = 0; i < result.length; i++) { var data = JSON.stringify(result[i]); var parse_data = JSON.parse(data); - var show_date = ""; + var show_date = ""; // Receipt Header receipt_no = result[i].receipt_no; @@ -81,14 +81,14 @@ $(document).ready(function(){ if(result[i].receipt_date != null){ receipt_date = new Date(result[i].receipt_date); show_date = receipt_date.getDate() + "-" + receipt_date.getMonth() + "-" + receipt_date.getFullYear() + ' ' + receipt_date.getHours()+ ':' + receipt_date.getMinutes() - } + } //Receipt Charges sub_total += parseFloat(parse_data.price); discount_amount = parse_data.discount_amount == null? '0.0' : parse_data.discount_amount; tax_amount = parse_data.tax_amount; - grand_total_amount = parse_data.grand_total_amount; + grand_total_amount = parse_data.grand_total_amount; // Ordered Items var order_items_rows = "" + @@ -135,7 +135,7 @@ $(document).ready(function(){ // Discount for Payment $('#discount').click(function() { var order_id=$(".selected-item").find(".orders-id").text().substr(0,16); - + if(order_id!=""){ window.location.href = '/origami/' + order_id + '/discount' } @@ -164,7 +164,7 @@ $(document).ready(function(){ } // For Percentage Discount - if(discount_type == 1){ + if(discount_type == 1){ discount_amount=(sub_total*discount_value)/100; } @@ -193,7 +193,7 @@ $(document).ready(function(){ $('#customer').click(function() { var sale = $(".selected-item").find(".orders-id").text().substr(0,16); - if (sale.substring(0, 3)=="SAL") { + if (sale.includes("SAL")) { var sale_id = sale }else{ var sale_id = $(".selected-item").find(".order-cid").text(); @@ -205,7 +205,7 @@ $(document).ready(function(){ $('#re-print').click(function() { var sale_id = $(".selected-item").find(".orders-id").text().substr(0,16); - + window.location.href = '/origami/'+ sale_id + "/reprint" return false; diff --git a/app/controllers/api/api_controller.rb b/app/controllers/api/api_controller.rb index 0e8ea909..8c6aaf65 100755 --- a/app/controllers/api/api_controller.rb +++ b/app/controllers/api/api_controller.rb @@ -1,11 +1,20 @@ class Api::ApiController < ActionController::API + include MultiTenancy include TokenVerification include ActionController::MimeResponds + include ActionView::Rendering + include Customers # before_action :lookup_domain helper_method :current_token, :current_login_employee, :get_cashier private + # ActionView::Rendering override render_to_body breaks render :json, + # resulting in an ActionView::MissingTemplate error. + def render_to_body(options) + _render_to_body_with_renderer(options) || super + end + #this is base api base controller to need to inherit. #all token authentication must be done here #response format must be set to JSON diff --git a/app/controllers/api/bill_controller.rb b/app/controllers/api/bill_controller.rb index 7a00666a..64597f02 100755 --- a/app/controllers/api/bill_controller.rb +++ b/app/controllers/api/bill_controller.rb @@ -9,7 +9,7 @@ class Api::BillController < Api::ApiController if !ShiftSale.current_shift.nil? #create Bill by Booking ID table = 0 - if (params[:booking_id]) + if params[:booking_id].present? booking = Booking.find(params[:booking_id]) if booking.booking_orders.count > 0 if booking.checkin_at.utc.strftime("%Y-%m-%d %H:%M") > Time.now.utc.strftime("%Y-%m-%d %H:%M") && booking.checkout_at.nil? @@ -51,13 +51,6 @@ class Api::BillController < Api::ApiController @status = false @error_message = "There is no order for '#{params[:booking_id]}'" end - # elsif (params[:order_id]) - # order = Order.find(params[:order_id]) - # @status, @sale_id = Sale.generate_invoice_from_order(params[:order_id], current_login_employee, get_cashier, order.source) - # - # # for Job - # booking = Booking.find_by_sale_id(@sale_id) - # table = DiningFacility.find(booking.dining_facility_id) end # Bind shift sale id to sale @@ -106,7 +99,7 @@ class Api::BillController < Api::ApiController # unique_code = "ReceiptBillPdf" # #shop detail - # shop_details = Shop.find(1) + # shop_details = Shop.current_shop # customer= Customer.find(@sale_data.customer_id) # # get member information @@ -147,7 +140,7 @@ class Api::BillController < Api::ApiController @order = Order.new @order.source = "cashier" @order.order_type = "Takeaway" - @order.customer_id = "CUS-000000000002" # for no customer id from mobile + @order.customer_id = takeaway.customer_id # for no customer id from mobile @order.items = params[:order_items] @order.guest = params[:guest_info] @order.table_id = params[:table_id] # this is dining facilities's id diff --git a/app/controllers/api/call_waiters_controller.rb b/app/controllers/api/call_waiters_controller.rb index 066fa30c..5beba9a6 100644 --- a/app/controllers/api/call_waiters_controller.rb +++ b/app/controllers/api/call_waiters_controller.rb @@ -23,7 +23,7 @@ class Api::CallWaitersController < ActionController::API end ActionCable.server.broadcast "call_waiter_channel",table: @table,time:@time,from: from, shift_ids: shift_ids # get printer info - @shop = Shop.first + @shop = Shop.current_shop unique_code = "CallWaiterPdf" print_settings = PrintSetting.find_by_unique_code(unique_code) printer = Printer::ReceiptPrinter.new(print_settings) diff --git a/app/controllers/api/check_in_process_controller.rb b/app/controllers/api/check_in_process_controller.rb index 602ef600..2a04ff6b 100644 --- a/app/controllers/api/check_in_process_controller.rb +++ b/app/controllers/api/check_in_process_controller.rb @@ -1,8 +1,8 @@ class Api::CheckInProcessController < Api::ApiController # before_action :authenticate def check_in_time - if params[:dining_id] - dining_facility = DiningFacility.find(params[:dining_id]) + if params[:dining_id] + dining_facility = DiningFacility.find(params[:dining_id]) if params[:booking_id] data = Booking.where("dining_facility_id = #{params[:dining_id]} AND booking_id = '#{params[:booking_id]}'") if data.count > 0 @@ -10,7 +10,7 @@ class Api::CheckInProcessController < Api::ApiController else booking = nil end - else + else booking = dining_facility.get_current_booking end if !booking.nil? @@ -21,7 +21,7 @@ class Api::CheckInProcessController < Api::ApiController #Send to background job for processing if ENV["SERVER_MODE"] == 'cloud' from = request.subdomain + "." + request.domain - else + else from = "" end ActionCable.server.broadcast "check_in_booking_channel",table: table,from:from @@ -37,7 +37,7 @@ class Api::CheckInProcessController < Api::ApiController end lookup_checkout_time = Lookup.collection_of("checkout_alert_time") - + if !lookup_checkout_time.empty? now = Time.now.utc lookup_checkout_time.each do |checkout_time| @@ -52,16 +52,18 @@ class Api::CheckInProcessController < Api::ApiController else render :json => { :status => true } end - - else + + else render :json => { :status => false, :error_message => "No current booking!" } end + else + render :json => { :status => false } end end def check_in_process if params[:dining_id] - dining_facility = DiningFacility.find(params[:dining_id]) + dining_facility = DiningFacility.find(params[:dining_id]) if dining_facility.is_active && dining_facility.status == "available" if params[:checkin_time] checkin_at = nil @@ -75,7 +77,7 @@ class Api::CheckInProcessController < Api::ApiController if dining_facility.check_time(checkin_at, "checkin") booking = dining_facility.get_current_booking if booking.nil? - + booking = Booking.create({:dining_facility_id => params[:dining_id],:type => "TableBooking", :checkin_by=>current_login_employee.name,:checkin_at => checkin_at,:checkout_at =>nil, :booking_status => "assign", :reserved_at => nil, :reserved_by => nil }) if booking.save! @@ -95,10 +97,10 @@ class Api::CheckInProcessController < Api::ApiController render :json => { :status => false, :error_message => "Operation failed!" } end else - booking = dining_facility.get_current_checkout_booking + booking = dining_facility.current_checkout_booking if booking.nil? lookup_checkout_time = Lookup.collection_of("checkout_time") - + if !lookup_checkout_time.empty? today = Time.now.utc.getlocal checkout_at = Time.now.utc.getlocal @@ -118,7 +120,7 @@ class Api::CheckInProcessController < Api::ApiController # else # type = "RoomBooking" # end - + booking = Booking.create({:dining_facility_id => params[:dining_id],:type => "TableBooking", :checkin_by=>current_login_employee.name,:checkin_at => Time.now.utc,:checkout_at =>checkout_at, :booking_status => "assign", :reserved_at => checkout_at, :reserved_by => current_login_employee.name }) if booking.save! @@ -133,13 +135,13 @@ class Api::CheckInProcessController < Api::ApiController unique_code = "CheckInOutPdf" printer = PrintSetting.find_by_unique_code(unique_code) - # print when complete click + # print when complete click order_queue_printer = Printer::OrderQueuePrinter.new(printer) if !printer.nil? order_queue_printer.print_check_in_out(printer, cashier_terminal, booking, dining_facility) end - end + end render :json => { :status => true, :booking_id => booking.booking_id, :checkout_at => booking.checkout_at.utc.getlocal.strftime("%Y-%m-%d %H:%M") } else render :json => { :status => true } @@ -176,7 +178,7 @@ class Api::CheckInProcessController < Api::ApiController booking.save! render :json => { :status => true, :checkout_at => booking.checkout_at.utc.getlocal.strftime("%Y-%m-%d %H:%M") } - elsif !params[:booking_id].nil? && params[:time].nil? + elsif !params[:booking_id].nil? && params[:time].nil? error_message = "time is required!" render :json => { :status => false, :error_message => error_message } elsif params[:booking_id].nil? && !params[:time].nil? diff --git a/app/controllers/api/order_reserve/order_reservation_controller.rb b/app/controllers/api/order_reserve/order_reservation_controller.rb index 32c2192e..cfec740d 100644 --- a/app/controllers/api/order_reserve/order_reservation_controller.rb +++ b/app/controllers/api/order_reserve/order_reservation_controller.rb @@ -70,7 +70,7 @@ class Api::OrderReserve::OrderReservationController < Api::ApiController order_reservation_id, flag = OrderReservation.addOrderReservationInfo(order_reservation) if !order_reservation_id.nil? && flag - shop = Shop.find_by_id(1) + shop = Shop.current_shop if !shop.nil? shop_code = shop.shop_code order_audio = DisplayImage.find_by_shop_id_and_name(shop.id, "order_audio") diff --git a/app/controllers/api/orders_controller.rb b/app/controllers/api/orders_controller.rb index bd2c3e18..0c79f303 100755 --- a/app/controllers/api/orders_controller.rb +++ b/app/controllers/api/orders_controller.rb @@ -46,7 +46,7 @@ class Api::OrdersController < Api::ApiController @tax_profile = TaxProfile.where("lower(group_type)='cashier'") # end - @shop = Shop.first + @shop = Shop.current_shop puts "Hello world" puts @shop.to_json return @shop.to_json @@ -67,15 +67,10 @@ class Api::OrdersController < Api::ApiController if checkin_checkout_time(params[:booking_id]) - if params[:booking_id].present? - booking = Booking.find(params[:booking_id]) - end - if params[:table_id].present? - if booking.nil? || booking.dining_facility_id.to_i != params[:table_id].to_i - table = DiningFacility.find(params[:table_id]) - booking = table.get_current_booking - end - end + table = DiningFacility.find(params[:table_id]) if params[:table_id].present? + + booking = table.current_checkin_booking if table + booking ||= Booking.find(params[:booking_id]) if params[:booking_id].present? #for extratime is_extra_time = false @@ -98,7 +93,7 @@ class Api::OrdersController < Api::ApiController @order = Order.new @order.source = params[:order_source] @order.order_type = params[:order_type] - @order.customer_id = params[:customer_id] == ""? "CUS-000000000001" : params[:customer_id] # for no customer id from mobile + @order.customer_id = params[:customer_id].present? ? params[:customer_id] : walkin.customer_id # for no customer id from mobile @order.items = params[:order_items] @order.guest = params[:guest_info] @order.table_id = params[:table_id] # this is dining facilities's id @@ -118,6 +113,7 @@ class Api::OrdersController < Api::ApiController end @status, @booking = @order.generate + if @status && @booking Order.process_order_queue(@order.order_id,@order.table_id,@order.source) end @@ -195,7 +191,7 @@ class Api::OrdersController < Api::ApiController #checked checkin and checkout time def checkin_checkout_time(booking_id) status = true - if !booking_id.nil? + if booking_id.present? if booking = Booking.find(booking_id) if booking.checkout_at.present? if booking.checkout_at.utc <= Time.now.utc diff --git a/app/controllers/api/payment/mobilepayment_controller.rb b/app/controllers/api/payment/mobilepayment_controller.rb index 220cbbeb..53daa790 100644 --- a/app/controllers/api/payment/mobilepayment_controller.rb +++ b/app/controllers/api/payment/mobilepayment_controller.rb @@ -14,7 +14,7 @@ class Api::Payment::MobilepaymentController < Api::ApiController saleObj = Sale.find(sale_id) sale_items = SaleItem.get_all_sale_items(sale_id) - shop_detail = Shop.first + shop_detail = Shop.current_shop # rounding adjustment if !path.include? ("credit_payment") diff --git a/app/controllers/api/restaurant/menu_controller.rb b/app/controllers/api/restaurant/menu_controller.rb index 7dfa0ec5..ae9f7b12 100755 --- a/app/controllers/api/restaurant/menu_controller.rb +++ b/app/controllers/api/restaurant/menu_controller.rb @@ -6,7 +6,8 @@ class Api::Restaurant::MenuController < Api::ApiController param_checksum = params[:checksum] # checksum = File.readlines("public/checksums/menu_json.txt").pop.chomp - all_menu = Menu.active.all + all_menu = Menu.includes(:menu_categories => [:children, :menu_items => [:menu_item_instances => :menu_instance_item_sets, :item_sets => :menu_item_instances]]).active.all + @request_url = '' if ENV["SERVER_MODE"] == "cloud" @request_url = request.base_url @@ -14,20 +15,21 @@ class Api::Restaurant::MenuController < Api::ApiController # to hash menu_array = [] all_menu.each do |m| - menu_array.push(m.to_json(:include => {:menu_categories => - { :include => { :menu_items => - { :include => [:menu_item_sets, :menu_item_instances => - { :include => :menu_instance_item_sets}]} } }})) - end - + menu_array.push(m.to_json(:include => { :menu_categories => { :include => { :menu_items => { :include => [ :item_sets, :menu_item_instances => { :include => :menu_instance_item_sets } ] } } } } )) + end + #export Checksum file generate by md5 menu_checksum = Digest::MD5.hexdigest(menu_array.to_json) if menu_checksum != param_checksum response.headers['CHECKSUM'] = menu_checksum - @menus = all_menu + @menus = all_menu + @item_attributes = MenuItemAttribute.all.load + @item_options = MenuItemOption.all.load + else + render :json => nil end - # @current_menu = Menu.current_menu + # @current_menu = Menu.current_menu end #Description diff --git a/app/controllers/api/restaurant/zones_controller.rb b/app/controllers/api/restaurant/zones_controller.rb index 3e2d34ab..d9b5149a 100755 --- a/app/controllers/api/restaurant/zones_controller.rb +++ b/app/controllers/api/restaurant/zones_controller.rb @@ -2,8 +2,8 @@ class Api::Restaurant::ZonesController < Api::ApiController def index if (params[:filter] && params[:filter] = "all" ) - @all_tables = Table.active - @all_rooms = Room.active + @all_tables = Table.includes(:zone, :current_checkin_booking, :current_checkout_booking, :current_reserved_booking).active + @all_rooms = Room.includes(:zone, :current_checkin_booking, :current_checkout_booking, :current_reserved_booking).active else @zones = Zone.includes([:tables, :rooms]).where("is_active = true") end diff --git a/app/controllers/api/sound_effect_controller.rb b/app/controllers/api/sound_effect_controller.rb index 97dc3db5..f3126ca2 100644 --- a/app/controllers/api/sound_effect_controller.rb +++ b/app/controllers/api/sound_effect_controller.rb @@ -2,7 +2,7 @@ class Api::SoundEffectController < Api::ApiController #sound effect / alarm api for doemal side calling def sound_effect - shop = Shop.find_by_id(1) + shop = Shop.current_shop if !shop.nil? shop_code = shop.shop_code order_audio = DisplayImage.find_by_shop_id_and_name(shop.id, "order_audio") diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 66f20c55..6d5a413e 100755 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -1,5 +1,7 @@ class ApplicationController < ActionController::Base + include MultiTenancy include LoginVerification + include Customers #before_action :check_installation protect_from_forgery with: :exception @@ -17,5 +19,4 @@ class ApplicationController < ActionController::Base flash[:warning] = exception.message redirect_to root_path end - end diff --git a/app/controllers/base_controller.rb b/app/controllers/base_controller.rb index 1bf5b4d4..1bb0421e 100755 --- a/app/controllers/base_controller.rb +++ b/app/controllers/base_controller.rb @@ -1,5 +1,6 @@ class BaseController < ActionController::Base + include MultiTenancy layout "installation" protect_from_forgery with: :exception - + end diff --git a/app/controllers/base_crm_controller.rb b/app/controllers/base_crm_controller.rb index 00b5cf98..273a3639 100755 --- a/app/controllers/base_crm_controller.rb +++ b/app/controllers/base_crm_controller.rb @@ -1,4 +1,5 @@ class BaseCrmController < ActionController::Base + include MultiTenancy include LoginVerification layout "CRM" diff --git a/app/controllers/base_inventory_controller.rb b/app/controllers/base_inventory_controller.rb index 8ee82777..64cdd2cd 100755 --- a/app/controllers/base_inventory_controller.rb +++ b/app/controllers/base_inventory_controller.rb @@ -1,4 +1,5 @@ class BaseInventoryController < ActionController::Base + include MultiTenancy include LoginVerification layout "inventory" diff --git a/app/controllers/base_oqs_controller.rb b/app/controllers/base_oqs_controller.rb index 9b337b69..6b01383d 100755 --- a/app/controllers/base_oqs_controller.rb +++ b/app/controllers/base_oqs_controller.rb @@ -1,5 +1,7 @@ class BaseOqsController < ActionController::Base + include MultiTenancy include LoginVerification + layout "OQS" before_action :check_user diff --git a/app/controllers/base_origami_controller.rb b/app/controllers/base_origami_controller.rb index 6940a129..468a2fab 100755 --- a/app/controllers/base_origami_controller.rb +++ b/app/controllers/base_origami_controller.rb @@ -1,5 +1,8 @@ class BaseOrigamiController < ActionController::Base + include MultiTenancy include LoginVerification + include Customers + layout "origami" before_action :check_user diff --git a/app/controllers/base_report_controller.rb b/app/controllers/base_report_controller.rb index 691ece34..9dfa7c18 100755 --- a/app/controllers/base_report_controller.rb +++ b/app/controllers/base_report_controller.rb @@ -1,4 +1,5 @@ class BaseReportController < ActionController::Base + include MultiTenancy include LoginVerification layout "application" @@ -69,7 +70,7 @@ class BaseReportController < ActionController::Base from = from.beginning_of_day to = to.end_of_day - + return from, to end diff --git a/app/controllers/base_waiter_controller.rb b/app/controllers/base_waiter_controller.rb index 580de0f9..f89a8f31 100755 --- a/app/controllers/base_waiter_controller.rb +++ b/app/controllers/base_waiter_controller.rb @@ -1,5 +1,6 @@ class BaseWaiterController < ActionController::Base - include LoginVerification + include MultiTenancy + include LoginVerification layout "waiter" before_action :check_user diff --git a/app/controllers/concerns/customers.rb b/app/controllers/concerns/customers.rb new file mode 100644 index 00000000..83df79c1 --- /dev/null +++ b/app/controllers/concerns/customers.rb @@ -0,0 +1,18 @@ +module Customers + extend ActiveSupport::Concern + + included do + helper_method :walkin, :takeaway if respond_to? :helper_method + end + + def walkin + return @walkin if defined? @walkin + @walkin = Customer.walkin + end + + def takeaway + return @takeaway if defined? @takeaway + @takeaway = Customer.takeaway + end + +end diff --git a/app/controllers/concerns/login_verification.rb b/app/controllers/concerns/login_verification.rb index 8eb719cb..b1102171 100755 --- a/app/controllers/concerns/login_verification.rb +++ b/app/controllers/concerns/login_verification.rb @@ -3,7 +3,7 @@ module LoginVerification included do before_action :authenticate_session_token - helper_method :current_company,:current_shop, :current_login_employee, :current_user, :get_cashier, :order_reservation, :bank_integration, :shop_detail + helper_method :current_company, :current_shop, :current_login_employee, :current_user, :get_cashier, :order_reservation, :bank_integration, :shop_detail end #this is base api base controller to need to inherit. @@ -19,7 +19,7 @@ module LoginVerification def current_shop begin - return Shop.first + return Shop.current_shop rescue return nil end @@ -41,7 +41,7 @@ module LoginVerification #Shop Name in Navbor def shop_detail - @shop = Shop.first + @shop = current_shop end #check order reservation used @@ -78,11 +78,11 @@ module LoginVerification protected # Authenticate the user with token based authentication - def authenticate - authenticate_session_token || render_unauthorized + def authenticate + authenticate_session_token || render_unauthorized end - def authenticate_session_token + def authenticate_session_token token = session[:session_token] if (token) #@current_user = User.find_by(api_key: token) diff --git a/app/controllers/concerns/multi_tenancy.rb b/app/controllers/concerns/multi_tenancy.rb new file mode 100644 index 00000000..cb7c8aae --- /dev/null +++ b/app/controllers/concerns/multi_tenancy.rb @@ -0,0 +1,19 @@ +module MultiTenancy + extend ActiveSupport::Concern + + included do + set_current_tenant_through_filter if respond_to? :set_current_tenant_through_filter + before_action :find_shop_by_subdomain_or_frist if respond_to? :before_action + end + + private + def find_shop_by_subdomain_or_frist + if request.subdomain.present? + shop_code = request.subdomain.partition('-').last + shop = Shop.find_by(shop_code: shop_code) + else + shop = Shop.first + end + set_current_tenant(shop) + end +end diff --git a/app/controllers/concerns/number_formattable.rb b/app/controllers/concerns/number_formattable.rb index bb022263..60f6c4c0 100644 --- a/app/controllers/concerns/number_formattable.rb +++ b/app/controllers/concerns/number_formattable.rb @@ -8,7 +8,7 @@ module NumberFormattable @precision = @number_formats.find? { |x| x.name.parameterize.underscore == 'precision'}.value.to_i rescue nil end if @precision.nil? - @print_settings = PrintSetting.get_precision_delimiter if !defined? @number_formats + @print_settings = PrintSetting.get_precision_delimiter if !defined? @print_settings if @print_settings @precision = @print_settings.precision.to_i else @@ -24,7 +24,7 @@ module NumberFormattable @delimiter = @number_formats.find { |f| f.name.parameterize.underscore == 'delimiter'}.value.gsub(/\\u(\h{4})/) { |m| [$1].pack("H*").unpack("n*").pack("U*") } rescue nil end if @delimiter.nil? - @print_settings = PrintSetting.get_precision_delimiter if !defined? @number_formats + @print_settings = PrintSetting.get_precision_delimiter if !defined? @print_settings if @print_settings && @print_settings.delimiter @delimiter = "," else @@ -42,10 +42,10 @@ module NumberFormattable end def number_format(number, options = {}) - options[:precision] = options[:precision] || precision + options[:precision] = options[:precision] || precision # options[:delimiter] = options[:delimiter] || delimiter options[:strip_insignificant_zeros] = options[:strip_insignificant_zeros] || strip_insignificant_zeros - + number = number.to_f.round(options[:precision]) if options[:precision] > 0 diff --git a/app/controllers/crm/customers_controller.rb b/app/controllers/crm/customers_controller.rb index 12837add..abf1a9fe 100644 --- a/app/controllers/crm/customers_controller.rb +++ b/app/controllers/crm/customers_controller.rb @@ -81,10 +81,10 @@ class Crm::CustomersController < BaseCrmController @membership_types = Lookup.collection_of("member_group_type") - # @taxes = TaxProfile.all - # @taxes =TaxProfile.unscoped.select("id,(SELECT name from lookups where lookup_type='tax_profiles') as name") - @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") + # @taxes = TaxProfile.where(:group_type => 'cashier') + @taxes = TaxProfile.unscope(:order).select("tax_profiles.id, CONCAT(tax_profiles.name, '(', lookups.name, ')') as name") + .joins(:lookup) + .order("group_type ASC, order_by ASC") @filter = filter @@ -171,15 +171,33 @@ class Crm::CustomersController < BaseCrmController nrc = @customer.nrc_no card_no = @customer.card_no paypar_account_no = @customer.paypar_account_no +<<<<<<< HEAD id = @customer.membership_id member_group_id = @customer.membership_type # if !id.present? && !member_group_id.nil? +======= + id = @crm_customer.membership_id + member_group_id = @customer.membership_type + if !id.present? && !member_group_id.nil? +>>>>>>> d87ffee65b491cc164fa8b6aba6a385da646f18f membership = MembershipSetting.find_by_membership_type("paypar_url") memberaction = MembershipAction.find_by_membership_type("create_membership_customer") merchant_uid = memberaction.merchant_account_id.to_s auth_token = memberaction.auth_token.to_s url = membership.gateway_url.to_s + memberaction.gateway_url.to_s +<<<<<<< HEAD +======= + member_params = { name: name,phone: phone,email: email, + dob: dob,address: address,nrc:nrc,card_no:card_no, + member_group_id: member_group_id, + id:id, + merchant_uid:merchant_uid,auth_token:auth_token}.to_json + + # Check for paypar account exists + # if paypar_account_no != nil || paypar_account_no != '' + if paypar_account_no.present? +>>>>>>> d87ffee65b491cc164fa8b6aba6a385da646f18f member_params = { name: name,phone: phone,email: email, dob: dob,address: address,nrc:nrc,card_no:card_no, paypar_account_no: paypar_account_no, diff --git a/app/controllers/home_controller.rb b/app/controllers/home_controller.rb index a82a6483..18928fc3 100755 --- a/app/controllers/home_controller.rb +++ b/app/controllers/home_controller.rb @@ -91,7 +91,7 @@ class HomeController < ApplicationController def dashboard @from, @to = get_date_range_from_params - @shop = Shop.first + @shop = Shop.current_shop @orders = Sale.receipt_date_between(@from, @to).where("payment_status = 'new' and sale_status = 'bill'") @sales = Sale.receipt_date_between(@from, @to).completed diff --git a/app/controllers/inventory/inventory_controller.rb b/app/controllers/inventory/inventory_controller.rb index a0324b15..d91e4176 100755 --- a/app/controllers/inventory/inventory_controller.rb +++ b/app/controllers/inventory/inventory_controller.rb @@ -26,6 +26,6 @@ class Inventory::InventoryController < BaseInventoryController #Shop Name in Navbor helper_method :shop_detail def shop_detail - @shop = Shop.first + @shop = Shop.current_shop end end diff --git a/app/controllers/inventory/inventory_definitions_controller.rb b/app/controllers/inventory/inventory_definitions_controller.rb index 01ca52b3..fca0bb07 100755 --- a/app/controllers/inventory/inventory_definitions_controller.rb +++ b/app/controllers/inventory/inventory_definitions_controller.rb @@ -106,7 +106,7 @@ class Inventory::InventoryDefinitionsController < BaseInventoryController #Shop Name in Navbor helper_method :shop_detail def shop_detail - @shop = Shop.first + @shop = Shop.current_shop end private diff --git a/app/controllers/inventory/stock_check_items_controller.rb b/app/controllers/inventory/stock_check_items_controller.rb index 7a37f789..98fb0116 100755 --- a/app/controllers/inventory/stock_check_items_controller.rb +++ b/app/controllers/inventory/stock_check_items_controller.rb @@ -64,7 +64,7 @@ class Inventory::StockCheckItemsController < BaseInventoryController #Shop Name in Navbor helper_method :shop_detail def shop_detail - @shop = Shop.first + @shop = Shop.current_shop end private diff --git a/app/controllers/inventory/stock_checks_controller.rb b/app/controllers/inventory/stock_checks_controller.rb index b7f7369d..05f7c70f 100755 --- a/app/controllers/inventory/stock_checks_controller.rb +++ b/app/controllers/inventory/stock_checks_controller.rb @@ -41,7 +41,7 @@ class Inventory::StockChecksController < BaseInventoryController member_info = nil unique_code = 'StockCheckPdf' - shop_details = current_shop + shop_details = Shop.current_shop checker = Employee.find(stockcheck.check_by) print_settings = PrintSetting.find_by_unique_code(unique_code) if !print_settings.nil? @@ -66,7 +66,7 @@ class Inventory::StockChecksController < BaseInventoryController #Shop Name in Navbor helper_method :shop_detail def shop_detail - @shop = current_shop + @shop = Shop.current_shop end # before_action :set_stock_check, only: [:show, :edit, :update, :destroy] diff --git a/app/controllers/inventory/stock_journals_controller.rb b/app/controllers/inventory/stock_journals_controller.rb index 11db2efd..9a737da0 100755 --- a/app/controllers/inventory/stock_journals_controller.rb +++ b/app/controllers/inventory/stock_journals_controller.rb @@ -64,7 +64,7 @@ class StockJournalsController < ApplicationController #Shop Name in Navbor helper_method :shop_detail def shop_detail - @shop = Shop.first + @shop = Shop.current_shop end private diff --git a/app/controllers/oqs/backhome_controller.rb b/app/controllers/oqs/backhome_controller.rb index 4ac5f0a2..a66751cf 100755 --- a/app/controllers/oqs/backhome_controller.rb +++ b/app/controllers/oqs/backhome_controller.rb @@ -21,7 +21,7 @@ class Oqs::HomeController < BaseOqsController zone_id = qid.zone_id i=i+1 end - end + end end @queue_stations_items.push({:zone_id => zone_id , :station_name => que.station_name, :is_active => que.is_active , :is_ap => que.auto_print, :item_count => i }) end @@ -57,14 +57,6 @@ class Oqs::HomeController < BaseOqsController end end - # booking_id = dining.get_new_booking - # BookingOrder.where("booking_id='#{ booking_id }'").find_each do |bo| - # order=Order.find(bo.order_id); - # order.order_items.each do |oi| - # items.push(oi) - # end - # end - render :json => items.to_json end @@ -88,7 +80,7 @@ class Oqs::HomeController < BaseOqsController end # Query for OQS with delivery status - def queue_items_query(status) + def queue_items_query(status) AssignedOrderItem.select("assigned_order_items.assigned_order_item_id, oqs.id as station_id, oqs.station_name, oqs.is_active, oqpz.zone_id, df.name as zone, df.type as type, odt.order_id, odt.item_code, odt.item_name, odt.price, odt.qty, odt.item_order_by, odt.options, cus.name as customer_name, odt.created_at") .joins(" left join order_queue_stations as oqs on oqs.id = assigned_order_items.order_queue_station_id left join order_queue_process_by_zones as oqpz on oqpz.order_queue_station_id = oqs.id diff --git a/app/controllers/oqs/edit_controller.rb b/app/controllers/oqs/edit_controller.rb index c6e130ec..e2499fbb 100644 --- a/app/controllers/oqs/edit_controller.rb +++ b/app/controllers/oqs/edit_controller.rb @@ -85,6 +85,6 @@ class Oqs::EditController < BaseOqsController #Shop Name in Navbor helper_method :shop_detail def shop_detail - @shop = Shop.first + @shop = Shop.current_shop end end diff --git a/app/controllers/origami/addorders_controller.rb b/app/controllers/origami/addorders_controller.rb index 597b5d28..2e36aaa1 100755 --- a/app/controllers/origami/addorders_controller.rb +++ b/app/controllers/origami/addorders_controller.rb @@ -7,10 +7,10 @@ class Origami::AddordersController < BaseOrigamiController @webview = true end - @tables = Table.all.active.order('zone_id asc').group("zone_id") - @rooms = Room.all.active.order('zone_id asc').group("zone_id") - @all_table = Table.all.active.order('status desc') - @all_room = Room.all.active.order('status desc') + @tables = Table.active.order('zone_id asc').group("zone_id") + @rooms = Room.active.order('zone_id asc').group("zone_id") + @all_table = Table.active.order('status desc') + @all_room = Room.active.order('status desc') end def detail @@ -38,10 +38,11 @@ class Origami::AddordersController < BaseOrigamiController @booking = @table.get_booking if @booking @booking_id = @booking.booking_id - @obj_order = @booking.orders.first - @customer = @obj_order.customer - @date = @obj_order.created_at - @order_items = @booking.order_items + if @obj_order = @booking.orders.first + @customer = @obj_order.customer + @date = @obj_order.created_at + @order_items = @booking.order_items + end end end @@ -108,87 +109,85 @@ class Origami::AddordersController < BaseOrigamiController items_arr = [] JSON.parse(params[:order_items]).each { |i| i["item_instance_code"] = i["item_instance_code"].downcase.to_s - if i["item_instance_code"].include? "ext" - is_extra_time = true - arr_exts = i["item_instance_code"].split("_") - if arr_exts[1].match(/^(\d)+$/) + if i["item_instance_code"].include? "ext" + is_extra_time = true + arr_exts = i["item_instance_code"].split("_") + if arr_exts[1].match(/^(\d)+$/) time = arr_exts[1].to_i*60*i["quantity"].to_i extra_time = Time.at(time) - end - end - if i["parent_order_item_id"]; - items = {"order_item_id": i["order_item_id"],"item_instance_code": i["item_instance_code"],"quantity": i["quantity"],"parent_order_item_id": i["parent_order_item_id"],"options": JSON.parse(i["options"])} - else + end + end + if i["parent_order_item_id"] + items = {"order_item_id": i["order_item_id"],"item_instance_code": i["item_instance_code"],"quantity": i["quantity"],"parent_order_item_id": i["parent_order_item_id"],"options": JSON.parse(i["options"])} + else items = {"order_item_id": i["order_item_id"],"item_instance_code": i["item_instance_code"],"quantity": i["quantity"],"options": JSON.parse(i["options"])} - end - items_arr.push(items) - } + end + items_arr.push(items) + } # begin if params[:order_source] == "quick_service" && params[:table_id].to_i == 0 - customer_id = "CUS-000000000002" # for no customer id from mobile + customer_id = takeaway.customer_id # for no customer id from mobile else - customer_id = params[:customer_id] == ""? "CUS-000000000001" : params[:customer_id] # for no customer id from mobile + customer_id = params[:customer_id].present? ? params[:customer_id] : walkin.customer_id # for no customer id from mobile end - @order = Order.new - @order.source = params[:order_source] - @order.order_type = params[:order_type] - @order.customer_id = customer_id - @order.items = items_arr - @order.guest = params[:guest_info] - @order.table_id = params[:table_id] # this is dining facilities's id - @order.new_booking = true - @order.waiters = current_login_employee.name - @order.employee_name = current_login_employee.name - - @order.is_extra_time = is_extra_time - @order.extra_time = extra_time - - if booking.nil? || booking.sale_id.present? || booking.booking_status == 'moved' + Order.transaction do + @order = Order.new + @order.source = params[:order_source] + @order.order_type = params[:order_type] + @order.customer_id = customer_id + @order.items = items_arr + @order.guest = params[:guest_info] + @order.table_id = params[:table_id] # this is dining facilities's id @order.new_booking = true - else - @order.new_booking = false - @order.booking_id = booking.booking_id - end + @order.waiters = current_login_employee.name + @order.employee_name = current_login_employee.name - @status, @booking = @order.generate - - if @status && @booking - #send order broadcast to order_channel - if @order.table_id.to_i > 0 - table = DiningFacility.find(@booking.dining_facility_id) - type = 'order' - from = getCloudDomain #get sub domain in cloud mode - ActionCable.server.broadcast "order_channel",table: table,type:type,from:from + @order.is_extra_time = is_extra_time + @order.extra_time = extra_time + if booking.nil? || booking.sale_id.present? || booking.booking_status == 'moved' + @order.new_booking = true + else + @order.new_booking = false + @order.booking_id = booking.booking_id end - if params[:order_source] != "quick_service" && params[:order_source] != "food_court" - process_order_queue(@order.order_id,@order.table_id,@order.source) - end - end + @status, @booking = @order.generate + if @status && @booking + #send order broadcast to order_channel + if @order.table_id.to_i > 0 + table = DiningFacility.find(@booking.dining_facility_id) + type = 'order' + from = getCloudDomain #get sub domain in cloud mode + ActionCable.server.broadcast "order_channel", table: table,type:type,from:from + end + if params[:order_source] != "quick_service" && params[:order_source] != "food_court" + process_order_queue(@order.order_id,@order.table_id,@order.source) + end + end # Order.send_customer_view(@booking) - if current_user.role != "waiter" && params[:create_type] == "create_pay" - if @status && @booking && (@order.source == 'quick_service') || (@order.source == 'food_court') + if current_user.role != "waiter" && params[:create_type] == "create_pay" + if @status && @booking && (@order.source == 'quick_service') || (@order.source == 'food_court') - @status, @sale = Sale.request_bill(@order,current_user,current_login_employee) + @status, @sale = Sale.request_bill(@order,current_user,current_login_employee) - # for second display - if @order.source == 'quick_service' - from = getCloudDomain #get sub domain in cloud mode - ActionCable.server.broadcast "second_display_channel",data: @sale,status:"sale",from:from + # for second display + if @order.source == 'quick_service' + from = getCloudDomain #get sub domain in cloud mode + ActionCable.server.broadcast "second_display_channel",data: @sale,status:"sale",from:from + end + #end + result = {:status=> @status, :data => @sale } + render :json => result.to_json end - #end - result = {:status=> @status, :data => @sale } + else + result = {:status=> @status, :data => 0 } render :json => result.to_json end - else - result = {:status=> @status, :data => 0 } - render :json => result.to_json end - end # render json for http status code @@ -232,66 +231,28 @@ class Origami::AddordersController < BaseOrigamiController end def process_order_queue(order_id,table_id,order_source) - print_status = nil - cup_status = nil + #Send to background job for processing + order = Order.find(order_id) + sidekiq = Lookup.find_by_lookup_type("sidekiq") - #Send to background job for processing - order = Order.find(order_id) - sidekiq = Lookup.find_by_lookup_type("sidekiq") - if ENV["SERVER_MODE"] != 'cloud' - cup_status = `#{"sudo service cups status"}` - print_status = check_cup_status(cup_status) + if ENV["SERVER_MODE"] != 'cloud' + if Printer::PrinterWorker.printers.blank? + msg = 'Print Error ! Please contact to service' + ActionCable.server.broadcast "call_waiter_channel", table: msg, time:'print_error', from: '' end + end - if print_status - if !sidekiq.nil? - OrderQueueProcessorJob.perform_later(order_id, table_id) - else - if order - oqs = OrderQueueStation.new - oqs.process_order(order, table_id, order_source) - end - # assign_order = AssignedOrderItem.assigned_order_item_by_job(order_id) - # ActionCable.server.broadcast "order_queue_station_channel",order: assign_order - end - else - if ENV["SERVER_MODE"] != 'cloud' - cup_start = `#{"sudo service cups start"}` - cup_status = `#{"sudo service cups status"}` - print_status = check_cup_status(cup_status) - end - - if print_status - if !sidekiq.nil? - OrderQueueProcessorJob.perform_later(order_id, table_id) - else - if order - oqs = OrderQueueStation.new - oqs.process_order(order, table_id, order_source) - end - # assign_order = AssignedOrderItem.assigned_order_item_by_job(order_id) - # ActionCable.server.broadcast "order_queue_station_channel",order: assign_order - end - else - if ENV["SERVER_MODE"] != 'cloud' - from = "" - msg = ' Print Error ! Please contact to service' - ActionCable.server.broadcast "call_waiter_channel",table: msg,time:'print_error',from:from - end - if !sidekiq.nil? - OrderQueueProcessorJob.perform_later(order_id, table_id) - else - if order - oqs = OrderQueueStation.new - oqs.process_order(order, table_id, order_source) - end - - from = getCloudDomain #get sub domain in cloud mode - assign_order = AssignedOrderItem.assigned_order_item_by_job(order_id) - ActionCable.server.broadcast "order_queue_station_channel",order: assign_order,from:from - end - end + if !sidekiq.nil? + OrderQueueProcessorJob.perform_later(order_id, table_id) + else + if order + oqs = OrderQueueStation.new + oqs.process_order(order, table_id, order_source) end + from = getCloudDomain #get sub domain in cloud mode + assign_order = AssignedOrderItem.assigned_order_item_by_job(order_id) + ActionCable.server.broadcast "order_queue_station_channel", order: assign_order, from: from + end end def check_cup_status(status) diff --git a/app/controllers/origami/alipay_controller.rb b/app/controllers/origami/alipay_controller.rb index 8c5f4884..3578724f 100644 --- a/app/controllers/origami/alipay_controller.rb +++ b/app/controllers/origami/alipay_controller.rb @@ -11,7 +11,7 @@ class Origami::AlipayController < BaseOrigamiController end total = 0 @alipaycount = 0 - @shop = Shop.first + @shop = Shop.current_shop @rounding_adj = 0 @can_alipay = 0 @member_discount = 0 @@ -64,7 +64,7 @@ class Origami::AlipayController < BaseOrigamiController ref_no = params[:ref_no] if(Sale.exists?(sale_id)) saleObj = Sale.find(sale_id) - shop_details = Shop.first + shop_details = Shop.current_shop # rounding adjustment # if shop_details.is_rounding_adj @@ -88,6 +88,6 @@ class Origami::AlipayController < BaseOrigamiController #Shop Name in Navbor helper_method :shop_detail def shop_detail - @shop = Shop.first + @shop = Shop.current_shop end end diff --git a/app/controllers/origami/credit_payments_controller.rb b/app/controllers/origami/credit_payments_controller.rb index 05faf4f7..3e9f2bd3 100755 --- a/app/controllers/origami/credit_payments_controller.rb +++ b/app/controllers/origami/credit_payments_controller.rb @@ -9,7 +9,7 @@ class Origami::CreditPaymentsController < BaseOrigamiController @creditcount = 0 others = 0 - @shop = Shop.first + @shop = Shop.current_shop if @shop.is_rounding_adj new_total = Sale.get_rounding_adjustment(sale_data.grand_total) else @@ -32,7 +32,7 @@ class Origami::CreditPaymentsController < BaseOrigamiController sale_id = params[:sale_id] if(Sale.exists?(sale_id)) saleObj = Sale.find(sale_id) - shop_details = Shop.first + shop_details = Shop.current_shop # rounding adjustment # if shop_details.is_rounding_adj diff --git a/app/controllers/origami/credit_sales_controller.rb b/app/controllers/origami/credit_sales_controller.rb index 8f43edda..587b22dd 100644 --- a/app/controllers/origami/credit_sales_controller.rb +++ b/app/controllers/origami/credit_sales_controller.rb @@ -3,11 +3,11 @@ class Origami::CreditSalesController < BaseOrigamiController @cashier_type = 'cashier' @webview = false if check_mobile - @webview = true + @webview = true end - - @tables = Table.unscoped.all.active.order('status desc') - @rooms = Room.unscoped.all.active.order('status desc') + + @tables = Table.unscope(:order).all.active.order('status desc') + @rooms = Room.unscope(:order).all.active.order('status desc') @complete = Sale.where("DATE_FORMAT(created_at,'%Y-%m-%d') = ? and sale_status != 'new'",DateTime.now.strftime('%Y-%m-%d')) @orders = Order.includes("sale_orders").where("DATE_FORMAT(date,'%Y-%m-%d') = ? and status != 'billed' and source != 'quick_service'",DateTime.now.strftime('%Y-%m-%d')).order('date desc') @customers = Customer.pluck("customer_id, name") @@ -15,7 +15,7 @@ class Origami::CreditSalesController < BaseOrigamiController @sale = Sale.find_by_sale_id(params[:sale_id]) @sale_payment = SalePayment.select("SUM(payment_amount) as payment_amount") .where("sale_id = ? and payment_method=?", @sale.sale_id, "creditnote") - + @sale_taxes = [] sale_taxes = SaleTax.where("sale_id = ?", @sale.sale_id) if !sale_taxes.empty? @@ -24,5 +24,5 @@ class Origami::CreditSalesController < BaseOrigamiController end end end - + end diff --git a/app/controllers/origami/customers_controller.rb b/app/controllers/origami/customers_controller.rb index 97f35339..746b8bdc 100644 --- a/app/controllers/origami/customers_controller.rb +++ b/app/controllers/origami/customers_controller.rb @@ -55,7 +55,7 @@ class Origami::CustomersController < BaseOrigamiController @cashier_type = params[:type] @page = params[:dir_page] - if(@sale_id[0,3] == "SAL") + if @sale_id.include? "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) @@ -87,7 +87,7 @@ class Origami::CustomersController < BaseOrigamiController @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") + @taxes = TaxProfile.unscope(:order).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") # if flash["errors"] # @crm_customer.valid? @@ -117,7 +117,7 @@ class Origami::CustomersController < BaseOrigamiController def update_sale_by_customer - id = params[:sale_id][0,3] + id = params[:sale_id] customer_id = params[:customer_id] customer = Customer.find(customer_id) order_source = params[:type] @@ -129,7 +129,7 @@ class Origami::CustomersController < BaseOrigamiController # end # end - if(id == "SAL") + if id.include? "SAL" sale = Sale.find(params[:sale_id]) status = sale.update_attributes(customer_id: customer_id) sale.sale_orders.each do |sale_order| @@ -153,7 +153,7 @@ class Origami::CustomersController < BaseOrigamiController if status == true render json: JSON.generate({:status => true}) - if(id == "SAL") + if id.include? "SAL" sale.compute_by_sale_items(sale.total_discount, nil, order_source) end else diff --git a/app/controllers/origami/dashboard_controller.rb b/app/controllers/origami/dashboard_controller.rb index 43c79179..52eb5cf4 100644 --- a/app/controllers/origami/dashboard_controller.rb +++ b/app/controllers/origami/dashboard_controller.rb @@ -1,7 +1,7 @@ class Origami::DashboardController < BaseOrigamiController def index - @shop = Shop.first + @shop = Shop.current_shop @display_type = Lookup.find_by_lookup_type("display_type") @sale_data = Array.new @@ -99,7 +99,7 @@ class Origami::DashboardController < BaseOrigamiController end def get_all_menu - @menus = Menu.includes(:menu_categories => :children).includes(:menu_categories => {:menu_items => :menu_item_instances}).includes(:menu_categories => {:menu_items => :item_sets }).includes(:menu_categories => {:menu_items => {:item_sets => :menu_item_instances}}).active.all + @menus = Menu.includes(:menu_categories => [:children, :menu_items => [:menu_item_instances => :menu_instance_item_sets, :item_sets => :menu_item_instances]]).active.all @item_attributes = MenuItemAttribute.all.load @item_options = MenuItemOption.all.load end diff --git a/app/controllers/origami/dinga_controller.rb b/app/controllers/origami/dinga_controller.rb index 01e35004..9754b81d 100644 --- a/app/controllers/origami/dinga_controller.rb +++ b/app/controllers/origami/dinga_controller.rb @@ -6,7 +6,7 @@ class Origami::DingaController < BaseOrigamiController @membership_rebate_balance=0 @sale_data = Sale.find_by_sale_id(@sale_id) @receipt_no = @sale_data.receipt_no - @shop = Shop.first + @shop = Shop.current_shop if @shop.is_rounding_adj new_total = Sale.get_rounding_adjustment(@sale_data.grand_total) else @@ -77,7 +77,7 @@ def create account_no = params[:account_no] if(Sale.exists?(sale_id)) saleObj = Sale.find(sale_id) - shop_details = Shop.first + shop_details = Shop.current_shop # rounding adjustment # if shop_details.is_rounding_adj # new_total = Sale.get_rounding_adjustment(saleObj.grand_total) diff --git a/app/controllers/origami/food_court_controller.rb b/app/controllers/origami/food_court_controller.rb index 1157bb44..e201566d 100644 --- a/app/controllers/origami/food_court_controller.rb +++ b/app/controllers/origami/food_court_controller.rb @@ -49,7 +49,7 @@ class Origami::FoodCourtController < ApplicationController # @menus = Menu.all # @menu = MenuCategory.active.where("menu_id =#{@menus[0].id}").order('order_by asc') # end - if(params[:id][0,3] == "BKI") + if params[:id].include? "BKI" @table_id = nil @table = nil @booking = Booking.find(params[:id]) @@ -106,7 +106,7 @@ class Origami::FoodCourtController < ApplicationController order = Order.new order.source = params[:order_source] order.order_type = params[:order_type] - order.customer_id = params[:customer_id] == ""? "CUS-000000000001" : params[:customer_id] # for no customer id from mobile + order.customer_id = params[:customer_id].present? ? params[:customer_id] : walkin.customer_id # for no customer id from mobile order.items = items_arr order.guest = params[:guest_info] order.table_id = params[:table_id] # this is dining facilities's id diff --git a/app/controllers/origami/gift_voucher_controller.rb b/app/controllers/origami/gift_voucher_controller.rb index 572e248e..7ad78065 100644 --- a/app/controllers/origami/gift_voucher_controller.rb +++ b/app/controllers/origami/gift_voucher_controller.rb @@ -6,7 +6,7 @@ class Origami::GiftVoucherController < BaseOrigamiController sale_data = Sale.find_by_sale_id(@sale_id) total = 0 @gift_vouchercount = 0 - @shop = Shop.first + @shop = Shop.current_shop @rounding_adj = 0 @can_gift_voucher = 0 @member_discount = 0 @@ -48,7 +48,7 @@ class Origami::GiftVoucherController < BaseOrigamiController ref_no = params[:reference_no] if(Sale.exists?(sale_id)) saleObj = Sale.find(sale_id) - shop_details = Shop.first + shop_details = Shop.current_shop # rounding adjustment # if shop_details.is_rounding_adj @@ -66,6 +66,6 @@ class Origami::GiftVoucherController < BaseOrigamiController #Shop Name in Navbor helper_method :shop_detail def shop_detail - @shop = Shop.first + @shop = Shop.current_shop end end diff --git a/app/controllers/origami/home_controller.rb b/app/controllers/origami/home_controller.rb index fe074210..ad135e03 100755 --- a/app/controllers/origami/home_controller.rb +++ b/app/controllers/origami/home_controller.rb @@ -4,8 +4,8 @@ class Origami::HomeController < BaseOrigamiController def index @webview = check_mobile - @tables = Table.unscoped.all.active.order('status desc') - @rooms = Room.unscoped.all.active.order('status desc') + @tables = Table.unscope(:order).includes(:zone, :current_checkin_booking, :current_checkout_booking, :current_reserved_booking).active.order('status desc') + @rooms = Room.unscope(:order).includes(:zone, :current_checkin_booking, :current_checkout_booking, :current_reserved_booking).active.order('status desc') @complete = Sale.completed_sale("cashier") @orders = Order.includes("sale_orders").where("DATE_FORMAT(date,'%Y-%m-%d') = ? and status != 'billed' and source != 'quick_service'",DateTime.now.strftime('%Y-%m-%d')).order('date desc') @@ -21,8 +21,8 @@ class Origami::HomeController < BaseOrigamiController @print_settings = PrintSetting.get_precision_delimiter() @webview = check_mobile - @tables = Table.unscoped.all.active.order('status desc') - @rooms = Room.unscoped.all.active.order('status desc') + @tables = Table.unscope(:order).includes(:zone, :current_checkin_booking, :current_checkout_booking, :current_reserved_booking).all.active.order('status desc') + @rooms = Room.unscope(:order).includes(:zone, :current_checkin_booking, :current_checkout_booking, :current_reserved_booking).all.active.order('status desc') @complete = Sale.completed_sale("cashier") @orders = Order.includes("sale_orders").where("DATE_FORMAT(date,'%Y-%m-%d') = ? and status != 'billed' and source != 'quick_service'",DateTime.now.strftime('%Y-%m-%d')).order('date desc') @customers = Customer.pluck("customer_id, name") @@ -35,75 +35,41 @@ class Origami::HomeController < BaseOrigamiController @shop = shop_detail @membership = MembershipSetting::MembershipSetting @payment_methods = PaymentMethodSetting.all - @dining_booking = @dining.bookings.active.where("DATE_FORMAT(created_at,'%Y-%m-%d') = '#{DateTime.now.strftime('%Y-%m-%d')}' OR DATE_FORMAT(created_at,'%Y-%m-%d') = '#{Date.today.prev_day}' ") - #@dining_booking = @dining.bookings.active.where("created_at between '#{DateTime.now.utc - 12.hours}' and '#{DateTime.now.utc}'") - @order_items = Array.new + @dining_booking = @dining.current_bookings + + @order_items = Array.new @dining_booking.each do |booking| - if booking.sale_id.nil? && booking.booking_status != 'moved' - @order_items = Array.new - # @assigned_order_items = Array.new - if booking.booking_orders.empty? - @booking = booking - else - booking.booking_orders.each do |booking_order| - order = Order.find(booking_order.order_id) - if (order.status == "new") - @obj_order = order - @customer = order.customer - @date = order.created_at - @booking= booking - order.order_items.each do |item| - @order_items.push(item) - # assigned_order_items = AssignedOrderItem.find_by_item_code_and_instance_code_and_order_id(item.item_code,item.item_instance_code,item.order_id) - # if !assigned_order_items.nil? - # @assigned_order_items.push({item.order_items_id => assigned_order_items.assigned_order_item_id}) - # end - end - @account_arr = Array.new - if @customer.tax_profiles - accounts = @customer.tax_profiles - @account_arr =[] - accounts.each do |acc| - account = TaxProfile.find_by_id(acc) - if !account.nil? - @account_arr.push(account) - end - end - end - end - end - end - @status_order = 'order' - else - sale = Sale.find(booking.sale_id) - if sale.sale_status != "completed" && sale.sale_status != 'void' && sale.sale_status != 'spoile' && sale.sale_status != 'waste' - @sale_array.push(sale) - if @status_order == 'order' - @status_order = 'sale' - end - @booking= booking - @date = sale.created_at - @status_sale = 'sale' - @obj_sale = sale - @customer = sale.customer - accounts = @customer.tax_profiles - @account_arr =[] - accounts.each do |acc| - account = TaxProfile.find_by_id(acc) - if !account.nil? - @account_arr.push(account) - end - end - end - @sale_taxes = [] - sale_taxes = SaleTax.where("sale_id = ?", sale.sale_id) - if !sale_taxes.empty? - sale_taxes.each do |sale_tax| - @sale_taxes.push(sale_tax) - end - end + if @obj_sale || @booking.blank? + @booking = booking + end + + if booking.sale_id + @obj_sale = booking.sale + @sale_array.push(@obj_sale) + @sale_taxes = @obj_sale.sale_taxes + @status_sale = 'sale' + else + @order_items += booking.order_items + @obj_order = booking.orders.first + end + + if @obj_sale || @customer.blank? + if obj = @obj_sale || @obj_order + @customer = obj.customer + @date = obj.created_at end - end + end + + if @obj_sale + @status_order = 'sale' + else + @status_order = 'order' + end + + if (@obj_sale || @account_arr.blank?) && @customer + @account_arr = TaxProfile.find_by(id: @customer.tax_profiles) + end + end #for bank integration @checkout_time = Lookup.collection_of('checkout_time') @@ -126,7 +92,7 @@ class Origami::HomeController < BaseOrigamiController lookup_edit_order = Lookup.collection_of('edit_order') if !lookup_edit_order.empty? lookup_edit_order.each do |edit_order| - if edit_order[0].downcase == "editorderorigami" + if edit_order[0].downcase == "editorderorigami" if edit_order[1] == '0' && (current_login_employee.role == 'cashier' || current_login_employee.role == 'waiter') @edit_order_origami = false end @@ -139,14 +105,14 @@ class Origami::HomeController < BaseOrigamiController lookup_changable_tax = Lookup.collection_of('changable_tax') if !lookup_changable_tax.empty? lookup_changable_tax.each do |changable_tax| - if changable_tax[0].downcase == "change" - if changable_tax[1] == '0' + if changable_tax[0].downcase == "change" + if changable_tax[1] == '0' @changable_tax = false end end end end - + end def check_emp_access_code diff --git a/app/controllers/origami/home_controller_bk.rb b/app/controllers/origami/home_controller_bk.rb index 4839f15c..2220f463 100755 --- a/app/controllers/origami/home_controller_bk.rb +++ b/app/controllers/origami/home_controller_bk.rb @@ -1,9 +1,8 @@ class Origami::HomeController < ApplicationController def index if params[:booking_id] != nil - type=params[:booking_id].split('-')[0]; # Sale - if type == "SAL" + if params[:booking_id].include? "SAL" @selected_item = Sale.find(params[:booking_id]) @selected_item_type="Sale" # Booking @@ -25,9 +24,8 @@ class Origami::HomeController < ApplicationController def selection(selected_id, is_ajax) str = [] - type=selected_id.split('-')[0]; # Sale - if type == "SAL" + if selected_id.include? "SAL" @order_details = SaleItem.get_order_items_details(params[:booking_id]) @order_details.each do |ord_detail| str.push(ord_detail) @@ -48,9 +46,7 @@ class Origami::HomeController < ApplicationController end def update_sale_by_customer - - id = params[:sale_id][0,3] - if(id == "SAL") + if id.inlude? "SAL" sale = Sale.find(params[:sale_id]) else sale = Order.find(params[:sale_id]) diff --git a/app/controllers/origami/jcb_controller.rb b/app/controllers/origami/jcb_controller.rb index 1f979adc..3a64b8a0 100644 --- a/app/controllers/origami/jcb_controller.rb +++ b/app/controllers/origami/jcb_controller.rb @@ -12,7 +12,7 @@ class Origami::JcbController < BaseOrigamiController end total = 0 @jcbcount = 0 - @shop = Shop.first + @shop = Shop.current_shop @rounding_adj = 0 @can_jcb = 0 @member_discount= 0 @@ -66,7 +66,7 @@ class Origami::JcbController < BaseOrigamiController ref_no = params[:ref_no] if(Sale.exists?(sale_id)) saleObj = Sale.find(sale_id) - shop_details = Shop.first + shop_details = Shop.current_shop # rounding adjustment # if shop_details.is_rounding_adj @@ -89,6 +89,6 @@ class Origami::JcbController < BaseOrigamiController #Shop Name in Navbor helper_method :shop_detail def shop_detail - @shop = Shop.first + @shop = Shop.current_shop end end diff --git a/app/controllers/origami/junction_pay_controller.rb b/app/controllers/origami/junction_pay_controller.rb index c77c2655..1b416c6a 100644 --- a/app/controllers/origami/junction_pay_controller.rb +++ b/app/controllers/origami/junction_pay_controller.rb @@ -11,7 +11,7 @@ class Origami::JunctionPayController < BaseOrigamiController @cashier_id = current_user.emp_id @payment_method_setting_nav = PaymentMethodSetting.all - @shop = Shop.first + @shop = Shop.current_shop if @shop.is_rounding_adj new_total = Sale.get_rounding_adjustment(sale_data.grand_total) else @@ -52,7 +52,7 @@ class Origami::JunctionPayController < BaseOrigamiController if(Sale.exists?(sale_id)) saleObj = Sale.find(sale_id) - shop_details = Shop.first + shop_details = Shop.current_shop # rounding adjustment # if shop_details.is_rounding_adj diff --git a/app/controllers/origami/master_controller.rb b/app/controllers/origami/master_controller.rb index 15edb703..f36b86f0 100644 --- a/app/controllers/origami/master_controller.rb +++ b/app/controllers/origami/master_controller.rb @@ -12,7 +12,7 @@ class Origami::MasterController < BaseOrigamiController end total = 0 @mastercount = 0 - @shop = Shop.first + @shop = Shop.current_shop @rounding_adj = 0 @can_master = 0 @member_discount = 0 @@ -63,7 +63,7 @@ class Origami::MasterController < BaseOrigamiController ref_no = params[:ref_no] if(Sale.exists?(sale_id)) saleObj = Sale.find(sale_id) - shop_details = Shop.first + shop_details = Shop.current_shop # rounding adjustment # if shop_details.is_rounding_adj @@ -87,6 +87,6 @@ class Origami::MasterController < BaseOrigamiController #Shop Name in Navbor helper_method :shop_detail def shop_detail - @shop = Shop.first + @shop = Shop.current_shop end end diff --git a/app/controllers/origami/movetable_controller.rb b/app/controllers/origami/movetable_controller.rb index 41c58941..86680c6e 100755 --- a/app/controllers/origami/movetable_controller.rb +++ b/app/controllers/origami/movetable_controller.rb @@ -105,7 +105,7 @@ class Origami::MovetableController < BaseOrigamiController # @type = (DiningFacility.find(change_to)).type # @moved_by = @current_user.name # @date = DateTime.now - # @shop = Shop.first + # @shop = Shop.current_shop # unique_code = "MoveTablePdf" # pdf_no = PrintSetting.where(:unique_code => unique_code).count # #print_settings = PrintSetting.find_by_unique_code(unique_code) diff --git a/app/controllers/origami/mpu_controller.rb b/app/controllers/origami/mpu_controller.rb index 220219c3..1a7743c1 100644 --- a/app/controllers/origami/mpu_controller.rb +++ b/app/controllers/origami/mpu_controller.rb @@ -11,7 +11,7 @@ class Origami::MpuController < BaseOrigamiController end total = 0 @mpucount = 0 - @shop = Shop.first + @shop = Shop.current_shop @rounding_adj = 0 @can_mpu = 0 @member_discount = 0 @@ -64,7 +64,7 @@ class Origami::MpuController < BaseOrigamiController ref_no = params[:ref_no] if(Sale.exists?(sale_id)) saleObj = Sale.find(sale_id) - shop_details = Shop.first + shop_details = Shop.current_shop # rounding adjustment # if shop_details.is_rounding_adj @@ -87,6 +87,6 @@ class Origami::MpuController < BaseOrigamiController #Shop Name in Navbor helper_method :shop_detail def shop_detail - @shop = Shop.first + @shop = Shop.current_shop end end diff --git a/app/controllers/origami/order_reservation_controller.rb b/app/controllers/origami/order_reservation_controller.rb index 3fdeee25..508bf483 100644 --- a/app/controllers/origami/order_reservation_controller.rb +++ b/app/controllers/origami/order_reservation_controller.rb @@ -4,7 +4,7 @@ class Origami::OrderReservationController < BaseOrigamiController @order = OrderReservation.latest_order #.active @count_on_order = OrderReservation.get_count_on_order @count_on_completed = OrderReservation.get_count_on_completed - @shop = Shop.find_by_id(1) + @shop = Shop.current_shop @receipt_bill = check_receipt_bill end diff --git a/app/controllers/origami/orders_controller.rb b/app/controllers/origami/orders_controller.rb index 5f34d9a3..2a7c9aa3 100755 --- a/app/controllers/origami/orders_controller.rb +++ b/app/controllers/origami/orders_controller.rb @@ -5,8 +5,8 @@ class Origami::OrdersController < BaseOrigamiController @webview = true end - @tables = Table.unscoped.all.active.order('status desc') - @rooms = Room.unscoped.all.active.order('status desc') + @tables = Table.unscope(:order).all.active.order('status desc') + @rooms = Room.unscope(:order).all.active.order('status desc') @complete = Sale.where("DATE_FORMAT(created_at,'%Y-%m-%d') = ? and sale_status != 'new'",DateTime.now.strftime('%Y-%m-%d')) @orders = Order.includes("sale_orders").where("DATE_FORMAT(date,'%Y-%m-%d') = ? and status != 'billed' and source != 'quick_service'",DateTime.now.strftime('%Y-%m-%d')).order('date desc') @order = Order.find(params[:order_id]) diff --git a/app/controllers/origami/paymal_controller.rb b/app/controllers/origami/paymal_controller.rb index 36c19327..cfabd2b5 100644 --- a/app/controllers/origami/paymal_controller.rb +++ b/app/controllers/origami/paymal_controller.rb @@ -6,7 +6,7 @@ class Origami::PaymalController < BaseOrigamiController @membership_rebate_balance=0 sale_data = Sale.find_by_sale_id(@sale_id) @receipt_no = sale_data.receipt_no - @shop = Shop.first + @shop = Shop.current_shop if @shop.is_rounding_adj new_total = Sale.get_rounding_adjustment(sale_data.grand_total) else @@ -75,7 +75,7 @@ def create puts params.to_json if(Sale.exists?(sale_id)) saleObj = Sale.find(sale_id) - shop_details = Shop.first + shop_details = Shop.current_shop # rounding adjustment # if shop_details.is_rounding_adj diff --git a/app/controllers/origami/payments_controller.rb b/app/controllers/origami/payments_controller.rb index c6c61602..3103ca38 100755 --- a/app/controllers/origami/payments_controller.rb +++ b/app/controllers/origami/payments_controller.rb @@ -10,121 +10,73 @@ class Origami::PaymentsController < BaseOrigamiController member_info = nil # For Cashier by Zone - booking = Booking.find_by_sale_id(sale_id) - # if bookings.count > 1 - # # for Multiple Booking - # table = DiningFacility.find(bookings[0].dining_facility_id) - # else - # table = DiningFacility.find(bookings[0].dining_facility_id) - # end - shift = ShiftSale.current_open_shift(current_user.id) - if !shift.nil? - cashier_terminal = CashierTerminal.find(shift.cashier_terminal_id) - else - if booking.dining_facility_id.to_i > 0 - table = DiningFacility.find(booking.dining_facility_id) - cashier_zone = CashierTerminalByZone.find_by_zone_id(table.zone_id) - cashier_terminal = CashierTerminal.find(cashier_zone.cashier_terminal_id) - else - shift = ShiftSale.find(sale_data.shift_sale_id) - cashier_terminal = CashierTerminal.find(shift.cashier_terminal_id) + booking = sale_data.booking + + if current_user.role == 'cashier' + cashier_terminal = current_user.cashier_terminal + elsif booking.dining_facility + cashier_terminal = booking.cashier_terminal_by_dining_facility + end + + cashier_terminal ||= sale_data.cashier_terminal_by_shift_sale + + customer = sale_data.customer + + #record for sale audit + action_by = current_user.name + type = "FIRST_BILL" + + remark = "#{action_by} print out first bill for Receipt No #{sale_data.receipt_no}" + sale_audit = SaleAudit.record_audit_sale(sale_id,remark,action_by,type ) + # get member information + rebate = MembershipSetting.find_by_rebate(1) + if customer.membership_id != nil && rebate + # member_info = Customer.get_member_account(customer) + # current_balance = SaleAudit.paymal_search(sale_id) + current_balance = 0 + end + + # find order id by sale id + # sale_order = SaleOrder.find_by_sale_id(@sale_data.sale_id) + + # Calculate price_by_accounts + item_price_by_accounts = SaleItem.calculate_price_by_accounts(sale_items) + discount_price_by_accounts = SaleItem.get_discount_price_by_accounts(sale_items) + + other_amount = SaleItem.calculate_other_charges(sale_items) + + print_settings = PrintSetting.where("unique_code REGEXP ?", "receipt.*bill.*pdf").first + printer = Printer::ReceiptPrinter.new(print_settings) + + #TODO :: KBZPAY ( QR ) + # On/Off setting ( show or not qr ) + # qrCode = "00020101021202021110500346KBZ005ab0ed5c1ed09d1c4585ff1313170389160831435294600062000040732kp1e78f7efddca190042638341afb88d50200006KBZPay0106KBZPay5303MMK5802MM62170813PAY_BY_QRCODE64060002my6304FBBD" + kbz_pay_method = PaymentMethodSetting.where(:payment_method => KbzPay::KBZ_PAY).last + + status = false + qr = nil + + if !kbz_pay_method.nil? + if kbz_pay_method.is_active == true + sale_payment = SalePayment.new + sale_payment.process_kbz_payment(sale_id, sale_data.grand_total, 0, 'pending') + + status, qr = KbzPay.pay(sale_data.grand_total.to_i, sale_payment.sale_payment_id, kbz_pay_method.gateway_url, kbz_pay_method.auth_token, kbz_pay_method.merchant_account_id, kbz_pay_method.additional_parameters) end end - # if ENV["SERVER_MODE"] != "cloud" #no print in cloud server - receipt_bill_a5_pdf = Lookup.collection_of("print_settings") #print_settings with name:ReceiptBillA5Pdf - # Print for First Bill to Customer - unique_code = "ReceiptBillPdf" - print_settings = PrintSetting.all - if !print_settings.nil? - print_settings.each do |setting| - if setting.unique_code == 'ReceiptBillPdf' - unique_code = "ReceiptBillPdf" - elsif setting.unique_code == 'ReceiptBillStarPdf' - unique_code = "ReceiptBillStarPdf" - end - end - end + filename, receipt_no, cashier_printer = printer.print_receipt_bill(print_settings, status, qr, cashier_terminal,sale_items,sale_data,customer.name, item_price_by_accounts, discount_price_by_accounts, member_info, shop_detail, "Frt",current_balance,nil,other_amount,nil,nil,nil) - if !receipt_bill_a5_pdf.empty? - receipt_bill_a5_pdf.each do |receipt_bilA5| - if receipt_bilA5[0] == 'ReceiptBillA5Pdf' - if receipt_bilA5[1] == '1' - unique_code = "ReceiptBillA5Pdf" - else - unique_code = unique_code#{}"ReceiptBillPdf" - end - end - end - end + result = { + :filepath => filename, + :printer_model => print_settings.brand_name, + :printer_url => print_settings.api_settings + } - #shop detail - ## shop_detail = Shop.first - # customer= Customer.where('customer_id=' +.customer_id) - customer = Customer.find(sale_data.customer_id) - # rounding adjustment - if shop_detail.is_rounding_adj - 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 - action_by = current_user.name - type = "FIRST_BILL" + # status, qr = KbzPay.query(sale_payment.sale_payment_id) - remark = "#{action_by} print out first bill for Receipt No #{sale_data.receipt_no}" - sale_audit = SaleAudit.record_audit_sale(sale_id,remark,action_by,type ) - # get member information - rebate = MembershipSetting.find_by_rebate(1) - if customer.membership_id != nil && rebate - # member_info = Customer.get_member_account(customer) - # current_balance = SaleAudit.paymal_search(sale_id) - current_balance = 0 - end - # get printer info - print_settings=PrintSetting.find_by_unique_code(unique_code) - - # find order id by sale id - # sale_order = SaleOrder.find_by_sale_id(@sale_data.sale_id) - - # Calculate price_by_accounts - item_price_by_accounts = SaleItem.calculate_price_by_accounts(sale_items) - discount_price_by_accounts = SaleItem.get_discount_price_by_accounts(sale_items) - - other_amount = SaleItem.calculate_other_charges(sale_items) - - printer = Printer::ReceiptPrinter.new(print_settings) - - #TODO :: KBZPAY ( QR ) - # On/Off setting ( show or not qr ) - # qrCode = "00020101021202021110500346KBZ005ab0ed5c1ed09d1c4585ff1313170389160831435294600062000040732kp1e78f7efddca190042638341afb88d50200006KBZPay0106KBZPay5303MMK5802MM62170813PAY_BY_QRCODE64060002my6304FBBD" - kbz_pay_method = PaymentMethodSetting.where(:payment_method => KbzPay::KBZ_PAY).last - - status = false - qr = nil - - if !kbz_pay_method.nil? - if kbz_pay_method.is_active == true - sale_payment = SalePayment.new - sale_payment.process_kbz_payment(sale_id, sale_data.grand_total, 0, 'pending') - - status, qr = KbzPay.pay(sale_data.grand_total.to_i, sale_payment.sale_payment_id, kbz_pay_method.gateway_url, kbz_pay_method.auth_token, kbz_pay_method.merchant_account_id, kbz_pay_method.additional_parameters) - end - end - - filename, receipt_no, cashier_printer = printer.print_receipt_bill(print_settings, status, qr, cashier_terminal,sale_items,sale_data,customer.name, item_price_by_accounts, discount_price_by_accounts, member_info, shop_detail, "Frt",current_balance,nil,other_amount,nil,nil,nil) - - result = { - :filepath => filename, - :printer_model => print_settings.brand_name, - :printer_url => print_settings.api_settings - } - - # status, qr = KbzPay.query(sale_payment.sale_payment_id) - - # Mobile Print - render :json => result.to_json + # Mobile Print + render :json => result.to_json # end end @@ -138,25 +90,9 @@ class Origami::PaymentsController < BaseOrigamiController latest_order_no = nil is_kbz = params[:is_kbz] - if(Sale.exists?(sale_id)) - saleObj = Sale.find(sale_id) + if saleObj = Sale.find(sale_id) sale_items = SaleItem.get_all_sale_items(sale_id) - #shop_detail = Shop.first - # rounding adjustment - if !path.include? ("credit_payment") - if shop_detail.is_rounding_adj - 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 - # if pay_from = 'kbzpay' - # salePayment = SalePayment.find(sale_payment_id) - # salePayment.process_kbz_payment(salePayment.sale_id, sale_data.grand_total, cash, 'paid') - # else - sp = SalePayment.where('sale_id=? and payment_method=? and payment_status=?', sale_id, 'kbzpay', 'paid').last if is_kbz == 'false' Rails.logger.info '################ CASH PAYMENT #################' sale_payment = SalePayment.new @@ -166,129 +102,107 @@ class Origami::PaymentsController < BaseOrigamiController sale_payment.process_payment(saleObj, current_user, cash, "cash") end else + sp = SalePayment.where('sale_id=? and payment_method=? and payment_status=?', sale_id, 'kbzpay', 'paid').last sp.kbz_edit_sale_payment(sp.received_amount.to_f, current_user) end - # end - if !path.include? ("credit_payment") rebate_amount = nil # For Cashier by Zone # bookings = Booking.where("sale_id='#{sale_id}'") - bookings = Booking.find_by_sale_id(sale_id) + booking = saleObj.booking - shift = ShiftSale.current_open_shift(current_user.id) - if !shift.nil? - cashier_terminal = CashierTerminal.find(shift.cashier_terminal_id) - else - if bookings.dining_facility_id.to_i > 0 - table = DiningFacility.find(bookings.dining_facility_id) - cashier_zone = CashierTerminalByZone.find_by_zone_id(table.zone_id) - cashier_terminal = CashierTerminal.find(cashier_zone.cashier_terminal_id) + if current_user.role == 'cashier' + cashier_terminal = current_user.cashier_terminal + elsif booking.dining_facility + cashier_terminal = booking.cashier_terminal_by_dining_facility + end - type = 'payment' - from = getCloudDomain #get sub domain in cloud mode - ActionCable.server.broadcast "order_channel",table: table,type:type,from:from - else - shift = ShiftSale.find(saleObj.shift_sale_id) - cashier_terminal = CashierTerminal.find(shift.cashier_terminal_id) - end + cashier_terminal ||= saleObj.cashier_terminal_by_shift_sale + + if booking.dining_facility + ActionCable.server.broadcast( + "order_channel", + table: booking.dining_facility, + type: 'payment', + from: getCloudDomain + ) end # For Print # if ENV["SERVER_MODE"] != "cloud" #no print in cloud server - receipt_bill_a5_pdf = Lookup.collection_of("print_settings") #print_settings with name:ReceiptBillA5Pdf - unique_code = "ReceiptBillPdf" - print_settings = PrintSetting.all - if !print_settings.nil? - print_settings.each do |setting| - if setting.unique_code == 'ReceiptBillPdf' - unique_code = "ReceiptBillPdf" - elsif setting.unique_code == 'ReceiptBillStarPdf' - unique_code = "ReceiptBillStarPdf" - end - end + if Lookup.collection_of("print_settings").any? { |x| x == ["ReceiptBillA5Pdf", "1"] } #print_settings with name:ReceiptBillA5Pdf + unique_code = "ReceiptBillA5Pdf" + else + unique_code = PrintSetting.where("unique_code REGEXP ?", "receipt.*bill.*pdf").first.unique_code + end + + customer = saleObj.customer + + # get member information + rebate = MembershipSetting.find_by_rebate(1) + credit_data = SalePayment.find_by_sale_id_and_payment_method(sale_id,'creditnote') + + if customer.membership_id != nil && rebate && credit_data.nil? + member_info = Customer.get_member_account(customer) + + if member_info["status"] == true + rebate_amount = Customer.get_membership_transactions(customer,saleObj.receipt_no) + current_balance = SaleAudit.paymal_search(sale_id) + end + end + + #orders print out + if type == "quick_service" + if booking.dining_facility_id.present? + table_id = booking.dining_facility_id + else + table_id = 0 end - if !receipt_bill_a5_pdf.empty? - receipt_bill_a5_pdf.each do |receipt_bilA5| - if receipt_bilA5[0] == 'ReceiptBillA5Pdf' - if receipt_bilA5[1] == '1' - unique_code = "ReceiptBillA5Pdf" - # else - - end - end - end + latest_order = booking.booking_orders.order("order_id DESC").limit(1).first() + if !latest_order.nil? + latest_order_no = latest_order.order_id end - customer= Customer.find(saleObj.customer_id) + booking.booking_orders.each do |order| + # Order.pay_process_order_queue(order.order_id, table_id) + oqs = OrderQueueStation.new + oqs.pay_process_order_queue(order.order_id, table_id) - # get member information - rebate = MembershipSetting.find_by_rebate(1) - credit_data = SalePayment.find_by_sale_id_and_payment_method(sale_id,'creditnote') - - if customer.membership_id != nil && rebate && credit_data.nil? - member_info = Customer.get_member_account(customer) - - if member_info["status"] == true - rebate_amount = Customer.get_membership_transactions(customer,saleObj.receipt_no) - current_balance = SaleAudit.paymal_search(sale_id) - end + assign_order = AssignedOrderItem.assigned_order_item_by_job(order.order_id) + from = getCloudDomain #get sub domain in cloud mode + ActionCable.server.broadcast "order_queue_station_channel",order: assign_order,from:from end - #orders print out - if type == "quick_service" - booking = Booking.find_by_sale_id(sale_id) - if booking.dining_facility_id.to_i>0 - table_id = booking.dining_facility_id - else - table_id = 0 - end - - latest_order = booking.booking_orders.order("order_id DESC").limit(1).first() - if !latest_order.nil? - latest_order_no = latest_order.order_id - end - - booking.booking_orders.each do |order| - # Order.pay_process_order_queue(order.order_id, table_id) - oqs = OrderQueueStation.new - oqs.pay_process_order_queue(order.order_id, table_id) - - assign_order = AssignedOrderItem.assigned_order_item_by_job(order.order_id) - from = getCloudDomain #get sub domain in cloud mode - ActionCable.server.broadcast "order_queue_station_channel",order: assign_order,from:from - end + end + #for card sale data + card_data = Array.new + card_sale_trans_ref_no = Sale.getCardSaleTrans(sale_id) + if !card_sale_trans_ref_no.nil? + card_sale_trans_ref_no.each do |cash_sale_trans| + card_res_date = cash_sale_trans.res_date.strftime("%Y-%m-%d").to_s + card_res_time = cash_sale_trans.res_time.strftime("%H:%M").to_s + card_no = cash_sale_trans.pan.last(4) + card_no = card_no.rjust(19,"**** **** **** ") + card_data.push({'res_date' => card_res_date, 'res_time' => card_res_time, 'batch_no' => cash_sale_trans.batch_no, 'trace' => cash_sale_trans.trace, 'pan' => card_no, 'app' => cash_sale_trans.app, 'tid' => cash_sale_trans.terminal_id, 'app_code' => cash_sale_trans.app_code, 'ref_no' => cash_sale_trans.ref_no, 'mid' => cash_sale_trans.merchant_id}) end + end - #for card sale data - card_data = Array.new - card_sale_trans_ref_no = Sale.getCardSaleTrans(sale_id) - if !card_sale_trans_ref_no.nil? - card_sale_trans_ref_no.each do |cash_sale_trans| - card_res_date = cash_sale_trans.res_date.strftime("%Y-%m-%d").to_s - card_res_time = cash_sale_trans.res_time.strftime("%H:%M").to_s - card_no = cash_sale_trans.pan.last(4) - card_no = card_no.rjust(19,"**** **** **** ") - card_data.push({'res_date' => card_res_date, 'res_time' => card_res_time, 'batch_no' => cash_sale_trans.batch_no, 'trace' => cash_sale_trans.trace, 'pan' => card_no, 'app' => cash_sale_trans.app, 'tid' => cash_sale_trans.terminal_id, 'app_code' => cash_sale_trans.app_code, 'ref_no' => cash_sale_trans.ref_no, 'mid' => cash_sale_trans.merchant_id}) - end - end + #card_balance amount for Paymal payment + card_balance_amount = SaleAudit.getCardBalanceAmount(sale_id) - #card_balance amount for Paymal payment - card_balance_amount = SaleAudit.getCardBalanceAmount(sale_id) + # get printer info + print_settings = PrintSetting.find_by_unique_code(unique_code) + # Calculate Food and Beverage Total + item_price_by_accounts = SaleItem.calculate_price_by_accounts(saleObj.sale_items) + discount_price_by_accounts = SaleItem.get_discount_price_by_accounts(saleObj.sale_items) + other_amount = SaleItem.calculate_other_charges(sale_items) - # get printer info - print_settings=PrintSetting.find_by_unique_code(unique_code) - # Calculate Food and Beverage Total - item_price_by_accounts = SaleItem.calculate_price_by_accounts(saleObj.sale_items) - discount_price_by_accounts = SaleItem.get_discount_price_by_accounts(saleObj.sale_items) - other_amount = SaleItem.calculate_other_charges(sale_items) - - printer = Printer::ReceiptPrinter.new(print_settings) - filename, sale_receipt_no, printer_name = printer.print_receipt_bill(print_settings, false, nil, cashier_terminal,sale_items,saleObj,customer.name, item_price_by_accounts, discount_price_by_accounts, member_info,rebate_amount,shop_detail, "Paid",current_balance,card_data,other_amount,latest_order_no,card_balance_amount,nil) + printer = Printer::ReceiptPrinter.new(print_settings) + filename, sale_receipt_no, printer_name = printer.print_receipt_bill(print_settings, false, nil, cashier_terminal,sale_items,saleObj,customer.name, item_price_by_accounts, discount_price_by_accounts, member_info,rebate_amount,shop_detail, "Paid",current_balance,card_data,other_amount,latest_order_no,card_balance_amount,nil) #end end @@ -381,7 +295,7 @@ class Origami::PaymentsController < BaseOrigamiController @shop = shop_detail #show shop info - @customer_lists = Customer.where("customer_id = 'CUS-000000000001' or customer_id = 'CUS-000000000002'") + @customer_lists = Customer.where(name: ["WALK-IN", "TAKEAWAY"]) saleObj = Sale.find(sale_id) @@ -577,7 +491,7 @@ class Origami::PaymentsController < BaseOrigamiController customer= Customer.find(saleObj.customer_id) #shop detail - #shop_detail = Shop.first + #shop_detail = Shop.current_shop # get member information rebate = MembershipSetting.find_by_rebate(1) if customer.membership_id != nil && rebate @@ -686,7 +600,7 @@ class Origami::PaymentsController < BaseOrigamiController customer= Customer.find(saleObj.customer_id) #shop detail - #shop_detail = Shop.first + #shop_detail = Shop.current_shop printer = PrintSetting.all unique_code="ReceiptBillPdf" @@ -795,7 +709,7 @@ class Origami::PaymentsController < BaseOrigamiController end end # get printer info - print_settings=PrintSetting.find_by_unique_code(unique_code) + print_settings = PrintSetting.find_by_unique_code(unique_code) printer = Printer::ReceiptPrinter.new(print_settings) printer.print_receipt_pdf(filename,receipt_no,print_settings.print_copies,printer_name) diff --git a/app/controllers/origami/paypar_payments_controller.rb b/app/controllers/origami/paypar_payments_controller.rb index fbcd348c..f2fb3c7b 100755 --- a/app/controllers/origami/paypar_payments_controller.rb +++ b/app/controllers/origami/paypar_payments_controller.rb @@ -7,7 +7,7 @@ class Origami::PayparPaymentsController < BaseOrigamiController payment_method = "paypar" if(Sale.exists?(sale_id)) saleObj = Sale.find(sale_id) - shop_details = Shop.first + shop_details = Shop.current_shop # rounding adjustment if shop_details.is_rounding_adj diff --git a/app/controllers/origami/pending_order_controller.rb b/app/controllers/origami/pending_order_controller.rb index 773a217e..aad9f792 100644 --- a/app/controllers/origami/pending_order_controller.rb +++ b/app/controllers/origami/pending_order_controller.rb @@ -14,7 +14,7 @@ class Origami::PendingOrderController < BaseOrigamiController def show id = params[:sale_id] - if id.start_with?("SAL") + if id.include? "SAL" @sale = Sale.find(id) if @sale.sale_status == "new" @bookings = @sale.bookings.first @@ -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.include? "BKI" @bookings = Booking.find(id) @order = @bookings.orders.where(status: "new").first @order_items = @bookings.order_items diff --git a/app/controllers/origami/quick_service_controller.rb b/app/controllers/origami/quick_service_controller.rb index f61da475..89f5c8ba 100644 --- a/app/controllers/origami/quick_service_controller.rb +++ b/app/controllers/origami/quick_service_controller.rb @@ -10,27 +10,24 @@ class Origami::QuickServiceController < ApplicationController def index today = DateTime.now day = Date.today.wday - # if params[:menu] == "true" + @menus = [] @menu = [] - # else - # @menus = Menu.all - # @menu = MenuCategory.active.where("menu_id =#{@menus[0].id}").order('order_by asc') - # end @zone = Zone.all @customer = Customer.all - @tables = Table.all.active.order('status desc') - @rooms = Room.all.active.order('status desc') + @tables = Table.active.order('status desc') + @rooms = Room.active.order('status desc') @cashier_type = "quick_service" display_type = Lookup.find_by_lookup_type("display_type") - if !display_type.nil? && display_type.value.to_i ==2 + if !display_type.nil? && display_type.value.to_i == 2 @display_type = display_type.value else @display_type = nil end #checked quick_service only - @quick_service_only = false + @quick_service_only = Lookup.collection_of('quickservice_add_order').any? { |x| x == ["quickserviceaddorder", "1"] } + lookup_dine_in = Lookup.collection_of('quickservice_add_order') # puts 'lookup_dine_in!!!!' # puts lookup_dine_in @@ -74,7 +71,7 @@ class Origami::QuickServiceController < ApplicationController # @menus = Menu.all # @menu = MenuCategory.active.where("menu_id =#{@menus[0].id}").order('order_by asc') # end - if(params[:id][0,3] == "BKI") + if params[:id].include? "BKI" @table_id = nil @table = nil @booking = Booking.find(params[:id]) @@ -131,7 +128,7 @@ class Origami::QuickServiceController < ApplicationController order = Order.new order.source = params[:order_source] order.order_type = params[:order_type] - order.customer_id = params[:customer_id] == ""? "CUS-000000000001" : params[:customer_id] # for no customer id from mobile + order.customer_id = params[:customer_id].present? ? params[:customer_id] : walkin.customer_id # for no customer id from mobile order.items = items_arr order.guest = params[:guest_info] order.table_id = params[:table_id] # this is dining facilities's id diff --git a/app/controllers/origami/redeem_payments_controller.rb b/app/controllers/origami/redeem_payments_controller.rb index c0edf879..0d1836c0 100755 --- a/app/controllers/origami/redeem_payments_controller.rb +++ b/app/controllers/origami/redeem_payments_controller.rb @@ -6,7 +6,7 @@ class Origami::RedeemPaymentsController < BaseOrigamiController @membership_rebate_balance=0 sale_data = Sale.find_by_sale_id(@sale_id) - @shop = Shop.first + @shop = Shop.current_shop if @shop.is_rounding_adj new_total = Sale.get_rounding_adjustment(sale_data.grand_total) else diff --git a/app/controllers/origami/request_bills_controller.rb b/app/controllers/origami/request_bills_controller.rb index 6d36f319..14daf0c9 100755 --- a/app/controllers/origami/request_bills_controller.rb +++ b/app/controllers/origami/request_bills_controller.rb @@ -18,96 +18,78 @@ class Origami::RequestBillsController < ApplicationController else table = DiningFacility.find_by(id: booking.dining_facility_id) - if sale_data = booking.sale - @status = true - elsif sale_data = Sale.generate_invoice_from_booking(booking, current_login_employee, current_user, order.source, params[:current_checkin_induties_count]) - @status = true - # in-duty update - in_duties = InDuty.where("booking_id=?", booking.id) - if !in_duties.empty? - in_duties.each do |in_duty| - induty = InDuty.find(in_duty.id) - induty.sale_id = sale_data.sale_id - induty.out_time = Time.now.utc - induty.save - end - end - end - - # Bind shift sale id to sale - # @sale_data.shift_sale_id = shift.id - # @sale_data.save - - action_by = current_user.name - type = "REQUEST_BILL" - - remark = "Request bill Receipt No #{sale_data.receipt_no}" - sale_audit = SaleAudit.record_audit_sale(sale_data.sale_id,remark,action_by,type ) - - # Promotion Activation - Promotion.promo_activate(sale_data) - - #bill channel - if ENV["SERVER_MODE"] == 'cloud' - from = request.subdomain + "." + request.domain - else - from = "" - end - - if order.source == "cashier" || order.source == "quick_service" - ActionCable.server.broadcast "bill_channel",table: table, from: from - end - if order.source == "quick_service" || order.source == "food_court" - result = {:status=> @status, :data => sale_data.sale_id } - render :json => result.to_json - else - #check checkInOut pdf print - checkout_time = Lookup.collection_of('checkout_time') - if !booking.dining_facility_id.nil? - terminal = DiningFacility.find_by_id(booking.dining_facility_id) - cashier_terminal = CashierTerminal.find_by_id(terminal.zone_id) - - if (!checkout_time.empty?) && (ENV["SERVER_MODE"] != "cloud") #no print in cloud server - unique_code = "CheckInOutPdf" - printer = PrintSetting.find_by_unique_code(unique_code) - - # print when complete click - order_queue_printer = Printer::OrderQueuePrinter.new(printer) - - if !printer.nil? - order_queue_printer.print_check_in_out(printer, cashier_terminal, booking, table) + if booking.sale_id.nil? + if sale_data = Sale.generate_invoice_from_booking(booking, current_login_employee, current_user, order.source, params[:current_checkin_induties_count]) + # in-duty update + in_duties = InDuty.where("booking_id=?", booking.id) + if !in_duties.empty? + in_duties.each do |in_duty| + induty = InDuty.find(in_duty.id) + induty.sale_id = sale_data.sale_id + induty.out_time = Time.now.utc + induty.save end end + + action_by = current_user.name + type = "REQUEST_BILL" + + remark = "Request bill Receipt No #{sale_data.receipt_no}" + sale_audit = SaleAudit.record_audit_sale(sale_data.sale_id,remark,action_by,type ) + + # Promotion Activation + Promotion.promo_activate(sale_data) + + #bill channel + if ENV["SERVER_MODE"] == 'cloud' + from = request.subdomain + "." + request.domain + else + from = "" + end + + if ["quick_service", "cashier"].include? order.source + ActionCable.server.broadcast "bill_channel", table: table, from: from + end + + unless ["quick_service", "food_court"].include? order.source + #check checkInOut pdf print + checkout_time = Lookup.collection_of('checkout_time') + if !booking.dining_facility_id.nil? + terminal = DiningFacility.find_by_id(booking.dining_facility_id) + cashier_terminal = CashierTerminal.find_by_id(terminal.zone_id) + + if (!checkout_time.empty?) && (ENV["SERVER_MODE"] != "cloud") #no print in cloud server + unique_code = "CheckInOutPdf" + printer = PrintSetting.find_by_unique_code(unique_code) + + # print when complete click + order_queue_printer = Printer::OrderQueuePrinter.new(printer) + + if !printer.nil? + order_queue_printer.print_check_in_out(printer, cashier_terminal, booking, table) + end + end + end + end + @status = true + sale_id = sale_data.sale_id + else + @status = false + sale_id = nil end + else + @status = true + sale_id = booking.sale_id end end - @status = true else @status = false @error_message = "No Current Open Shift for This Employee" end - -# Not Use for these printed bill cannot give customer - # unique_code = "ReceiptBillPdf" - # #shop detail - # shop_details = Shop.find(1) - # # customer= Customer.where('customer_id=' +.customer_id) - # customer= Customer.find(@sale_data.customer_id) - # # get member information - # member_info = Customer.get_member_account(customer) - # # get printer info - # print_settings=PrintSetting.find_by_unique_code(unique_code) - - # # find order id by sale id - # # sale_order = SaleOrder.find_by_sale_id(@sale_data.sale_id) - - # # Calculate price_by_accounts - # item_price_by_accounts = SaleItem.calculate_price_by_accounts(@sale_items) - - # printer = Printer::ReceiptPrinter.new(print_settings) - - - # printer.print_receipt_bill(print_settings, false, nil,@sale_items,@sale_data,customer.name, item_price_by_accounts,member_info,shop_details) + if ["quick_service", "food_court"].include? order.source + result = {:status=> @status, :data => sale_data.sale_id } + render :json => result.to_json + end end end diff --git a/app/controllers/origami/room_invoices_controller.rb b/app/controllers/origami/room_invoices_controller.rb index 8d805771..095eaa93 100755 --- a/app/controllers/origami/room_invoices_controller.rb +++ b/app/controllers/origami/room_invoices_controller.rb @@ -1,7 +1,6 @@ class Origami::RoomInvoicesController < BaseOrigamiController def index @room = DiningFacility.find(params[:room_id]) - puts "room bookig lenght" @sale_array = Array.new @room.bookings.each do |booking| puts booking.sale_id diff --git a/app/controllers/origami/rooms_controller.rb b/app/controllers/origami/rooms_controller.rb index 80eb5641..c94c5c18 100755 --- a/app/controllers/origami/rooms_controller.rb +++ b/app/controllers/origami/rooms_controller.rb @@ -1,7 +1,7 @@ class Origami::RoomsController < BaseOrigamiController def index - @tables = Table.unscoped.all.active.order('status desc') - @rooms = Room.unscoped.all.active.order('status desc') + @tables = Table.unscope(:order).all.active.order('status desc') + @rooms = Room.unscope(:order).all.active.order('status desc') @complete = Sale.completed_sale("cashier") @orders = Order.includes("sale_orders").where("DATE_FORMAT(date,'%Y-%m-%d') = ? and status != 'billed' and source != 'quick_service'",DateTime.now.strftime('%Y-%m-%d')).order('date desc') @shift = ShiftSale.current_open_shift(current_user.id) @@ -17,8 +17,8 @@ class Origami::RoomsController < BaseOrigamiController @webview = true end - @tables = Table.unscoped.all.active.order('status desc') - @rooms = Room.unscoped.all.active.order('status desc') + @tables = Table.unscope(:order).all.active.order('status desc') + @rooms = Room.unscope(:order).all.active.order('status desc') @complete = Sale.completed_sale("cashier") @orders = Order.includes("sale_orders").where("DATE_FORMAT(date,'%Y-%m-%d') = ? and status != 'billed' and source != 'quick_service'",DateTime.now.strftime('%Y-%m-%d')).order('date desc') @customers = Customer.pluck("customer_id, name") @@ -29,7 +29,7 @@ class Origami::RoomsController < BaseOrigamiController @status_sale = "" @sale_array = Array.new - @shop = Shop.first + @shop = Shop.current_shop @membership = MembershipSetting::MembershipSetting @payment_methods = PaymentMethodSetting.all diff --git a/app/controllers/origami/sales_controller.rb b/app/controllers/origami/sales_controller.rb index d2af3258..27f300d8 100755 --- a/app/controllers/origami/sales_controller.rb +++ b/app/controllers/origami/sales_controller.rb @@ -5,8 +5,8 @@ class Origami::SalesController < BaseOrigamiController @webview = true end - @tables = Table.unscoped.all.active.order('status desc') - @rooms = Room.unscoped.all.active.order('status desc') + @tables = Table.unscope(:order).all.active.order('status desc') + @rooms = Room.unscope(:order).all.active.order('status desc') @complete = Sale.completed_sale("cashier") @orders = Order.includes("sale_orders").where("DATE_FORMAT(date,'%Y-%m-%d') = ? and status != 'billed' and source != 'quick_service'",DateTime.now.strftime('%Y-%m-%d')).order('date desc') @customers = Customer.pluck("customer_id, name") @@ -26,52 +26,33 @@ class Origami::SalesController < BaseOrigamiController dining = params[:dining_id] sale_id = params[:sale_id] tax_type = params[:tax_type] - sale_data = [] - table = DiningFacility.find(dining) - existing_booking = Booking.find_by_sale_id(sale_id) - table.bookings.active.where("DATE_FORMAT(created_at,'%Y-%m-%d') = '#{DateTime.now.strftime('%Y-%m-%d')}' OR DATE_FORMAT(created_at,'%Y-%m-%d') = '#{Date.today.prev_day}' ").each do |booking| - if booking.sale_id.nil? - order_array = [] - booking.booking_orders.each do |booking_order| - booking.booking_status = 'moved' - order = Order.find(booking_order.order_id) - order.status = 'billed' - order.order_items.each do |item| - item.order_item_status = 'billed' - end - # create sale item - saleobj = Sale.find(sale_id) - order.order_items.each do |orer_item| - saleobj.add_item (orer_item) - if !orer_item.set_menu_items.nil? - saleobj.add_sub_item(orer_item.set_menu_items) - end - sale_data.push(orer_item) - end + Sale.transaction do + table = DiningFacility.find(dining) + booking = table.current_checkin_booking - # Re-compute for add - saleobj.compute(order.source,tax_type) - saleobj.save - order.save - booking.save + sale = Sale.find(sale_id) + existing = sale.booking - order_array.push(order.order_id) - end + sale.sale_items << booking.order_items.to_sale_items + sale.orders << booking.orders - receipt_no = Sale.find(sale_id).receipt_no - action_by = current_user.name - type = "ADD_TO_EXISTING" + sale.compute(booking.orders[0].source, tax_type) - remark = "#{action_by} add to existing order #{order_array} to Receipt No=>#{receipt_no} in #{table.name}" - sale_audit = SaleAudit.record_audit_sale(sale_id,remark,action_by,type ) + type = "ADD_TO_EXISTING" + receipt_no = sale.receipt_no + action_by = current_user.name + order_ids = booking.orders.map(&:order_id) - booking_order = BookingOrder.where('booking_id=?',booking) - booking_order.each do |bo| - bo.booking_id = existing_booking.booking_id - bo.save - end - end + remark = "#{action_by} add to existing order #{order_ids.to_s} to Receipt No=>#{receipt_no} in #{table.name}" + sale_audit = SaleAudit.record_audit_sale(sale_id, remark, action_by, type) + + booking.orders.update_all(status: "billed") + booking.order_items.update_all(order_item_status: "billed") + BookingOrder.where(booking_id: booking.booking_id).update_all(booking_id: existing) + + booking.booking_status = "moved" + booking.save end end diff --git a/app/controllers/origami/second_display_controller.rb b/app/controllers/origami/second_display_controller.rb index 21c0674d..392b85e6 100644 --- a/app/controllers/origami/second_display_controller.rb +++ b/app/controllers/origami/second_display_controller.rb @@ -27,7 +27,7 @@ class Origami::SecondDisplayController < BaseOrigamiController #Shop Name in Navbor # helper_method :shop_detail # def shop_detail - # @shop = Shop.first + # @shop = Shop.current_shop # end diff --git a/app/controllers/origami/split_bill_controller.rb b/app/controllers/origami/split_bill_controller.rb index fb6db35f..694ddb98 100755 --- a/app/controllers/origami/split_bill_controller.rb +++ b/app/controllers/origami/split_bill_controller.rb @@ -16,390 +16,118 @@ class Origami::SplitBillController < BaseOrigamiController @sale_data = Array.new @current_user = current_user - table_bookings = Booking.where("dining_facility_id = #{dining_id} and sale_id IS NOT NULL") - if !table_bookings.nil? - table_bookings.each do |table_booking| - if table_booking.sale.sale_status != 'waste' && table_booking.sale.sale_status != 'spoile' - @sale_data.push(table_booking.sale) - end - end - end + @sale_data = @table.current_sales if @booking - @booking.booking_orders.each do |booking_order| - arr_order_items = Array.new - @order = Order.find(booking_order.order_id) - if (@order.status == "new") - @orders.push(@order) + @orders = @booking.orders + @order = @orders[0] + @order_items = [] + order_items = [] - @order.order_items.each do |item| - if !item.set_menu_items.nil? - instance_item_sets = JSON.parse(item.set_menu_items) - arr_instance_item_sets = Array.new - instance_item_sets.each do |instance_item| - item_instance_name = MenuItemInstance.find_by_item_instance_code(instance_item["item_instance_code"]).item_instance_name - item.price = item.price.to_f + instance_item["price"].to_f - arr_instance_item_sets.push(item_instance_name) - end - item.set_menu_items = arr_instance_item_sets - end + @booking.order_items.each do |item| + if item.set_menu_items.present? + set_menu_items = JSON.parse(item.set_menu_items) + item.set_menu_items = set_menu_items.map { |x| x["item_instance_name"] } + item.price = item.price + set_menu_items.inject(0.0) { |sum, x| sum + x["item_instance_name"].to_f } + end - arr_item = Hash.new - if item.qty.to_i > 1 - i = 1 - while i <= item.qty.to_i do - arr_item = {'order_items_id' => item.order_items_id, - 'order_id' => item.order_id, - 'order_item_status' => item.order_item_status, - 'item_order_by' => item.item_order_by, - '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, - 'qty' => '1.0', - 'price' => item.price, - 'remark' => item.remark, - 'options' => item.options, - 'set_menu_items' => item.set_menu_items, - 'taxable' => item.taxable, - 'completed_by' => item.completed_by, - 'created_at' => item.created_at, - 'updated_at' => item.updated_at} - i += 1 - @order_items.push({@order.order_id => arr_item}) - arr_order_items.push(arr_item) - end - else - arr_order_items.push(item) - @order_items.push({@order.order_id => item}) - end - end - @order_items.push({'all_order' => arr_order_items}) - end - end - else - @booking = nil - end + @order_items += item.qty.to_i.times.map { i = item.as_json; i["qty"] = 1; order_items << i; { item.order_id => i } } + end + + @order_items << { 'all_order' => order_items } + else + @booking = nil + end end def create cashier_type = params[:cashier_type] + dining_id = params[:dining_id] order_ids = params[:order_ids] - arr_order_ids = nil - if !params[:arr_order_ids].nil? - arr_order_ids = JSON.parse(params[:arr_order_ids]) - end - orders = nil - if !params[:orders].empty? - orders = JSON.parse(params[:orders]) - end - order_items = nil - if !params[:order_items].empty? - order_items = JSON.parse(params[:order_items]) - end + arr_order_ids = JSON.parse(params[:arr_order_ids]) if params[:arr_order_ids].present? + orders = JSON.parse(params[:orders]) if params[:orders].present? + order_items = JSON.parse(params[:order_items]) if params[:order_items].present? - status = false if !ShiftSale.current_shift.nil? - #create Bill by Booking ID - table = 0 - if !params[:booking_id].empty? - booking = Booking.find(params[:booking_id]) - # for Multiple Cashier by Zone - if booking.dining_facility_id.to_i>0 - table = DiningFacility.find(booking.dining_facility_id) - cashier_zone = CashierTerminalByZone.find_by_zone_id(table.zone_id) - else - table = nil - cashier_zone = nil - end + #create Bill by Booking ID + table = DiningFacility.find_by(id: params[:dining_id]) if params[:dining_id].present? - # shift_by_terminal = ShiftSale.find_by_cashier_terminal_id_and_shift_closed_at(cashier_zone.cashier_terminal_id,nil) - # get_cashier_by_terminal = Employee.find(shift_by_terminal.employee_id) - - if sale_data = booking.sale - status = true - elsif sale_data = Sale.generate_invoice_from_booking(booking, current_user, current_user, cashier_type,params[:current_checkin_induties_count]) - status = true + Booking.transaction do + if params[:booking_id].present? + booking = Booking.find(params[:booking_id]) else - status = false - end - else - if params[:type] == "Table" - type = "TableBooking" - else - type = "RoomBooking" - end + type = "TableBooking" if params[:type] == "Table" + type ||= "RoomBooking" - booking = Booking.create({:dining_facility_id => params[:dining_id],:type => type, - :checkin_at => Time.now.utc, :checkin_by => current_user.name, - :booking_status => "assign" }) + split_orders = [] + new_order = nil - if !orders.nil? - orders.each do |order| - BookingOrder.find_by_order_id(order["id"]).delete - BookingOrder.create({:booking_id => booking.booking_id, :order_id => order["id"]}) + booking = Booking.create({:dining_facility_id => table.id, :type => type, :checkin_at => Time.now.utc, :checkin_by => current_user.name, :booking_status => "assign" }) + + if orders.present? + split_orders += orders.map { |x| x["id"] } end - elsif !order_items.nil? - order_item_count = 0 - order_id_count = 0 - order_id = nil - arr_order_ids.each do |order| - order.each do |odr| - data = Order.find(odr[0]) - if data.order_items.count == odr[1] - order_id = odr[0] - order_id_count += 1 + if order_items.present? + order_items = order_items.inject([]) do |arr, v| + v["qty"] = v["qty"].to_i + if i = arr.find { |x| x["id"] == v["id"] } + i["qty"] = i["qty"] + v["qty"] else - order_item_count += 1 + arr << v + end + arr + end + + Order.includes(:order_items).where(order_id: order_ids).each do |order| + if order.order_items.any? { |x| order_items.none? { |y| x.order_items_id == y["id"] && x.qty == y["qty"] } } + new_order ||= Order.create({ source: "cashier", order_type: order.order_type, customer_id: order.customer_id, item_count: order_items.length, waiters: current_user.name }) + order.order_items.each do |order_item| + if split_item = order_items.find { |x| x["id"] == order_item.order_items_id } + if split_item["qty"] == order_item.qty + new_order.order_items << order_item + else + order_item.qty = order_item.qty - split_item["qty"] + order_item.save + order_item_dup = order_item.dup + order_item_dup.qty = split_item["qty"] + new_order.order_items << order_item_dup + end + end + end + else + split_orders << order end end end - # puts order_id - # puts order_ids.count - # puts order_id_count - # puts order_items.count - # puts order_item_count - - if !order_id.nil? - if order_id_count > 1 - puts "order_id_count > 1" - - updated_order_id = Array.new - arr_order_ids.each do |order| - order.each do |odr| - data = Order.find(odr[0]) - if data.order_items.count != odr[1] - updated_order_id.push(odr[0]) - end - end - end - - # puts "updated_order_id" - # puts updated_order_id - - if !updated_order_id.empty? - order_ids.each do |odr_id| - unless updated_order_id.include?(odr_id) - BookingOrder.find_by_order_id(odr_id).delete - BookingOrder.create({:booking_id => booking.booking_id, :order_id => odr_id}) - end - end - - order_items.each do |order_item| - if updated_order_id.include?(order_item["order_id"]) - update_order_item(order_id, order_item) - end - end - else - order_ids.each do |odr_id| - new_order_status = true - order_items.each do |order_item| - orderItem = OrderItem.find_by_order_id(odr_id) - if !orderItem.nil? - if order_item["id"] == orderItem.order_items_id - if orderItem.qty.to_f != order_item['qty'].to_f - new_order_status = false - end - end - end - end - - # puts new_order_status - - if new_order_status - BookingOrder.find_by_order_id(odr_id).delete - BookingOrder.create({:booking_id => booking.booking_id, :order_id => odr_id}) - else - customer = Customer.find(params[:customer_id]) - order_type = "dine_in" - if !customer.nil? - if customer.customer_type == "Takeaway" - order_type = "takeaway" - elsif customer.customer_type == "Delivery" - order_type = "delivery" - end - end - - # begin - order = create_order(params,order_type,order_items.count,current_user) - - BookingOrder.create({:booking_id => booking.booking_id, :order_id => order.order_id}) - - order_items.each do |order_item| - update_order_item(order.order_id, order_item) - end - end - end - end - else - # puts "order_id_count < 1" - new_order_status = true - order_items.each do |order_item| - orderItem = OrderItem.find(order_item["id"]) - if !orderItem.nil? - if order_item["id"] == orderItem.order_items_id - if orderItem.qty.to_f != order_item['qty'].to_f - new_order_status = false - end - end - end - end - - # puts new_order_status - - if new_order_status - BookingOrder.find_by_order_id(order_id).delete - BookingOrder.create({:booking_id => booking.booking_id, :order_id => order_id}) - order_items.each do |order_item| - update_order_item(order_id, order_item) - end - else - customer = Customer.find(params[:customer_id]) - order_type = "dine_in" - if !customer.nil? - if customer.customer_type == "Takeaway" - order_type = "takeaway" - elsif customer.customer_type == "Delivery" - order_type = "delivery" - end - end - - # begin - order = create_order(params,order_type,order_items.count,current_user) - - BookingOrder.create({:booking_id => booking.booking_id, :order_id => order.order_id}) - - order_items.each do |order_item| - update_order_item(order.order_id, order_item) - end - end - end - else - if order_ids.count == 1 && order_item_count == 1 - if order_id_count == 0 - customer = Customer.find(params[:customer_id]) - order_type = "dine_in" - if !customer.nil? - if customer.customer_type == "Takeaway" - order_type = "takeaway" - elsif customer.customer_type == "Delivery" - order_type = "delivery" - end - end - - # begin - order = create_order(params,order_type,order_items.count,current_user) - - BookingOrder.create({:booking_id => booking.booking_id, :order_id => order.order_id}) - - order_items.each do |order_item| - update_order_item(order.order_id, order_item) - end - else - BookingOrder.find_by_order_id(order_ids[0]).delete - BookingOrder.create({:booking_id => booking.booking_id, :order_id => order_ids[0]}) - order_items.each do |order_item| - update_order_item(order_ids[0], order_item) - end - end - else - customer = Customer.find(params[:customer_id]) - order_type = "dine_in" - if !customer.nil? - if customer.customer_type == "Takeaway" - order_type = "takeaway" - elsif customer.customer_type == "Delivery" - order_type = "delivery" - end - end - - # begin - order = create_order(params,order_type,order_items.count,current_user) - - BookingOrder.create({:booking_id => booking.booking_id, :order_id => order.order_id}) - - order_items.each do |order_item| - update_order_item(order.order_id, order_item) - end - end + if new_order.present? + booking.orders << new_order end - end - if sale_data = Sale.generate_invoice_from_booking(booking, current_user, current_user, cashier_type ,params[:current_checkin_induties_count]) - status = true - end - end - - Promotion.promo_activate(sale_data) - if ENV["SERVER_MODE"] == 'cloud' - from = request.subdomain + "." + request.domain - else - from = "" - end - ActionCable.server.broadcast "bill_channel",table: table,from:from - - render :json => { status: status } - else - render :json => { status: false, error_message: 'No Current Open Shift!'} - end - end - - def create_order(params,order_type,items_count,current_user) - order = Order.new - order.source = "cashier" - order.order_type = order_type - order.customer_id = params[:customer_id] == ""? "CUS-000000000001" : params[:customer_id] # for no customer id from mobile - order.item_count = items_count - order.status = "new" - order.table_id = params[:dining_id] # this is dining facilities's id - order.waiters = current_user.name - order.employee_name = current_user.name - order.guest_info = nil - order.save! - - return order - end - - def update_order_item(order_id, order_item) - orderItem = OrderItem.find(order_item["id"]) - if orderItem.qty.to_f != order_item['qty'].to_f - set_menu_items_obj = Array.new - if !orderItem.set_menu_items.nil? - instance_item_sets = JSON.parse(orderItem.set_menu_items) - instance_item_sets.each_with_index do |instance_item, instance_index| - instance_item_sets[instance_index]["quantity"] = (instance_item["quantity"].to_i - order_item['qty'].to_i).to_s - set_menu_items_obj.push({'item_instance_code' => instance_item["item_instance_code"], 'quantity' => order_item['qty'].to_i, 'price' => instance_item["price"]}) - end - orderItem.set_menu_items = instance_item_sets.to_json + if split_orders.present? + BookingOrder.where(order_id: split_orders).update_all(booking_id: booking.booking_id) + end end - same_order = OrderItem.find_by_order_id(order_id) - if same_order.nil? - OrderItem.processs_item(orderItem.item_code, - orderItem.item_instance_code, - orderItem.item_name, - orderItem.alt_name, - orderItem.account_id, - order_item['qty'], - orderItem.price, - orderItem.options, - set_menu_items_obj.to_json, - order_id, - orderItem.item_order_by, - orderItem.taxable) - else - same_order.qty = same_order.qty.to_f + order_item['qty'].to_f - same_order.set_menu_items = set_menu_items_obj.to_json - same_order.save - end - orderItem.qty = orderItem.qty.to_f - order_item['qty'].to_f - else - orderItem.order_id = order_id - end - orderItem.save! + if booking.sale.nil? + sale_data = Sale.generate_invoice_from_booking(booking, current_user, current_user, cashier_type, params[:current_checkin_induties_count]) + Promotion.promo_activate(sale_data) + end + + if ENV["SERVER_MODE"] == 'cloud' + from = request.subdomain + "." + request.domain + else + from = "" + end + + ActionCable.server.broadcast "bill_channel", table: table, from:from + + render :json => { status: true } + end + else + render :json => { status: false, error_message: 'No Current Open Shift!'} + end end def update_sale @@ -413,7 +141,7 @@ class Origami::SplitBillController < BaseOrigamiController #Shop Name in Navbor helper_method :shop_detail def shop_detail - @shop = Shop.first + @shop = Shop.current_shop end end diff --git a/app/controllers/origami/surveys_controller.rb b/app/controllers/origami/surveys_controller.rb index 700159bb..201313ff 100644 --- a/app/controllers/origami/surveys_controller.rb +++ b/app/controllers/origami/surveys_controller.rb @@ -2,14 +2,14 @@ class Origami::SurveysController < BaseOrigamiController def new @webview = false if check_mobile - @webview = true + @webview = true end - + @survey = Survey.new @id = params[:id] @cashier_type = params[:type] - if(@id[0,3] == "SAL") + if @id.include? "SAL" @sale = Sale.find(@id) @receipt_no = @sale.receipt_no @grand_total = @sale.grand_total @@ -27,14 +27,14 @@ class Origami::SurveysController < BaseOrigamiController @dining_facility = nil @table_type = nil end - + else @dining_facility = DiningFacility.find(@id) @table_type = @dining_facility.type @receipt_no = nil @grand_total = nil @survey_data = Survey.find_by_dining_name_and_receipt_no(@dining_facility.name,nil) - end + end end def create @@ -63,13 +63,13 @@ class Origami::SurveysController < BaseOrigamiController shift = ShiftSale.find(sale.shift_sale_id) shift_by_terminal = ShiftSale.find_by_cashier_terminal_id_and_shift_closed_at(shift.cashier_terminal_id,nil) end - + if @type == "quick_service" || @type == "food_court" @url = "/origami/sale/"+@sale_id+"/"+@type+"/payment" else @url = "/origami/"+@dining_facility.type.downcase+"/"+params[:table_id] end - + if params[:survey_id].nil? || params[:survey_id] == "" @survey = Survey.new(survey_params) @@ -106,5 +106,5 @@ class Origami::SurveysController < BaseOrigamiController def survey_params params.require(:survey).permit(:child, :adult,:male,:female,:local,:foreigner, :dining_name,:receipt_no,:shift_id,:created_by,:total_customer,:total_amount,:survey_id) end - + end diff --git a/app/controllers/origami/table_invoices_controller.rb b/app/controllers/origami/table_invoices_controller.rb index 7082e44c..3a526ed6 100755 --- a/app/controllers/origami/table_invoices_controller.rb +++ b/app/controllers/origami/table_invoices_controller.rb @@ -1,8 +1,7 @@ class Origami::TableInvoicesController < BaseOrigamiController def index @table = DiningFacility.find(params[:table_id]) - shop = Shop.first - puts "table bookig lenght" + shop = Shop.current_shop @sale_array = Array.new @table.bookings.each do |booking| puts booking.sale_id @@ -34,30 +33,7 @@ class Origami::TableInvoicesController < BaseOrigamiController @table = DiningFacility.find(params[:table_id]) @membership = MembershipSetting::MembershipSetting @payment_methods = PaymentMethodSetting.all - shop = Shop.first - @sale_array = Array.new - @table.bookings.each do |booking| - if booking.sale_id.nil? - else - sale = Sale.find(booking.sale_id) - # rounding adjustment - if shop.is_rounding_adj - a = sale.grand_total % 25 # Modulus - b = sale.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.grand_total) - sale.rounding_adjustment = new_total-sale.grand_total - sale.update_attributes(grand_total: new_total,old_grand_total: sale.grand_total,rounding_adjustment:sale.rounding_adjustment) - end - end - #end rounding adjustment - if sale.sale_status != "completed" && sale.sale_status != 'void' && sale.sale_status != "waste" && sale.sale_status != "spoile" - @sale_array.push(sale) - end - end - end + @sale_array = @table.current_sales @sale = Sale.find(params[:invoice_id]) @date = @sale.created_at diff --git a/app/controllers/origami/unionpay_controller.rb b/app/controllers/origami/unionpay_controller.rb index b351d40a..23587ca0 100644 --- a/app/controllers/origami/unionpay_controller.rb +++ b/app/controllers/origami/unionpay_controller.rb @@ -11,7 +11,7 @@ class Origami::UnionpayController < BaseOrigamiController end total = 0 @unionpaycount = 0 - @shop = Shop.first + @shop = Shop.current_shop @rounding_adj = 0 @can_unionpay = 0 @member_discount = 0 @@ -61,7 +61,7 @@ class Origami::UnionpayController < BaseOrigamiController ref_no = params[:ref_no] if(Sale.exists?(sale_id)) saleObj = Sale.find(sale_id) - shop_details = Shop.first + shop_details = Shop.current_shop # rounding adjustment # if shop_details.is_rounding_adj @@ -85,6 +85,6 @@ class Origami::UnionpayController < BaseOrigamiController #Shop Name in Navbor helper_method :shop_detail def shop_detail - @shop = Shop.first + @shop = Shop.current_shop end end diff --git a/app/controllers/origami/visa_controller.rb b/app/controllers/origami/visa_controller.rb index c50339e4..6eb11be5 100644 --- a/app/controllers/origami/visa_controller.rb +++ b/app/controllers/origami/visa_controller.rb @@ -11,7 +11,7 @@ class Origami::VisaController < BaseOrigamiController end total = 0 @visacount = 0 - @shop = Shop.first + @shop = Shop.current_shop @rounding_adj = 0 @can_visa = 0 @member_discount = 0 @@ -61,7 +61,7 @@ class Origami::VisaController < BaseOrigamiController ref_no = params[:ref_no] if(Sale.exists?(sale_id)) saleObj = Sale.find(sale_id) - shop_details = Shop.first + shop_details = Shop.current_shop # rounding adjustment # if shop_details.is_rounding_adj @@ -85,6 +85,6 @@ class Origami::VisaController < BaseOrigamiController #Shop Name in Navbor helper_method :shop_detail def shop_detail - @shop = Shop.first + @shop = Shop.current_shop end end diff --git a/app/controllers/origami/void_controller.rb b/app/controllers/origami/void_controller.rb index 5352b7c3..7fb54825 100755 --- a/app/controllers/origami/void_controller.rb +++ b/app/controllers/origami/void_controller.rb @@ -116,7 +116,7 @@ class Origami::VoidController < BaseOrigamiController customer= Customer.find(sale.customer_id) #shop detail - shop_details = current_shop + shop_details = Shop.current_shop # get member information rebate = MembershipSetting.find_by_rebate(1) if customer.membership_id != nil && rebate diff --git a/app/controllers/origami/voucher_controller.rb b/app/controllers/origami/voucher_controller.rb index e512a48b..1b79cb49 100755 --- a/app/controllers/origami/voucher_controller.rb +++ b/app/controllers/origami/voucher_controller.rb @@ -8,7 +8,7 @@ class Origami::VoucherController < BaseOrigamiController @vouchercount = 0 others = 0 - @shop = Shop.first + @shop = Shop.current_shop if @shop.is_rounding_adj new_total = Sale.get_rounding_adjustment(sale_data.grand_total) else diff --git a/app/controllers/origami/waste_spoile_controller.rb b/app/controllers/origami/waste_spoile_controller.rb index 6a68a2b9..ba0846ee 100755 --- a/app/controllers/origami/waste_spoile_controller.rb +++ b/app/controllers/origami/waste_spoile_controller.rb @@ -89,7 +89,7 @@ class Origami::WasteSpoileController < BaseOrigamiController customer= Customer.find(sale.customer_id) #shop detail - shop_details = current_shop + shop_details = Shop.current_shop # get member information rebate = MembershipSetting.find_by_rebate(1) if customer.membership_id != nil && rebate diff --git a/app/controllers/reports/product_sale_controller.rb b/app/controllers/reports/product_sale_controller.rb index 9791545e..61f17396 100644 --- a/app/controllers/reports/product_sale_controller.rb +++ b/app/controllers/reports/product_sale_controller.rb @@ -22,6 +22,6 @@ class Reports::ProductSaleController < BaseReportController #Shop Name in Navbor helper_method :shop_detail def shop_detail - @shop = Shop.first + @shop = Shop.current_shop end end diff --git a/app/controllers/reports/receipt_no_controller.rb b/app/controllers/reports/receipt_no_controller.rb index eeff4bf0..1136bc31 100755 --- a/app/controllers/reports/receipt_no_controller.rb +++ b/app/controllers/reports/receipt_no_controller.rb @@ -183,7 +183,7 @@ authorize_resource :class => false customer= Customer.find(saleObj.customer_id) #shop detail - #shop_detail = Shop.first + #shop_detail = Shop.current_shop # get member information rebate = MembershipSetting.find_by_rebate(1) if customer.membership_id != nil && rebate diff --git a/app/controllers/settings/shops_controller.rb b/app/controllers/settings/shops_controller.rb index 598e4f9b..9e902dad 100644 --- a/app/controllers/settings/shops_controller.rb +++ b/app/controllers/settings/shops_controller.rb @@ -59,11 +59,11 @@ class Settings::ShopsController < ApplicationController File.delete(delete_path) end end - save_path = Rails.root.join("public/#{current_shop.shop_code}_#{a.original_filename}") + save_path = Rails.root.join("public/#{Shop.current_shop.shop_code}_#{a.original_filename}") File.open(save_path, 'wb') do |f| f.write a.read end - audio_name = "#{current_shop.shop_code}_#{a.original_filename}" + audio_name = "#{Shop.current_shop.shop_code}_#{a.original_filename}" @settings_shop.display_images.where(:name => "order_audio").destroy_all @display_image = @settings_shop.display_images.create!(:shop_id => @shop.id, :name => "order_audio", :image => audio_name) else diff --git a/app/controllers/transactions/sales_controller.rb b/app/controllers/transactions/sales_controller.rb index 83efc401..661b42e9 100755 --- a/app/controllers/transactions/sales_controller.rb +++ b/app/controllers/transactions/sales_controller.rb @@ -346,7 +346,7 @@ class Transactions::SalesController < ApplicationController customer= Customer.find(sale.customer_id) #shop detail - shop_details = Shop.find_by_id(1) + shop_details = Shop.current_shop # get member information rebate = MembershipSetting.find_by_rebate(1) if customer.membership_id != nil && rebate diff --git a/app/models/application_record.rb b/app/models/application_record.rb index 10a4cba8..c19491c8 100755 --- a/app/models/application_record.rb +++ b/app/models/application_record.rb @@ -1,3 +1,14 @@ class ApplicationRecord < ActiveRecord::Base self.abstract_class = true + + def self.inherited(subclass) + super + + return unless subclass.superclass == self + return unless subclass.column_names.include? 'shop_code' + + subclass.class_eval do + acts_as_tenant(:shop, foreign_key: 'shop_code', primary_key: 'shop_code') + end + end end diff --git a/app/models/assigned_order_item.rb b/app/models/assigned_order_item.rb index c1b0162e..d77248d8 100755 --- a/app/models/assigned_order_item.rb +++ b/app/models/assigned_order_item.rb @@ -41,12 +41,12 @@ class AssignedOrderItem < ApplicationRecord def self.assigned_order_item_by_job(order_id) order_item = AssignedOrderItem.select("assigned_order_items.assigned_order_item_id, - assigned_order_items.order_queue_station_id, - oqs.id as station_id, oqs.station_name, - oqs.is_active, oqpz.zone_id, - df.name as zone, df.type as table_type, - odt.order_id, odt.item_code, odt.item_instance_code, odt.item_name, - odt.price, odt.qty, odt.item_order_by, odt.options, + assigned_order_items.order_queue_station_id, + oqs.id as station_id, oqs.station_name, + oqs.is_active, oqpz.zone_id, + df.name as zone, df.type as table_type, + odt.order_id, odt.item_code, odt.item_instance_code, odt.item_name, + odt.price, odt.qty, odt.item_order_by, odt.options, cus.name as customer_name, odt.created_at") .joins(" left join order_queue_stations as oqs on oqs.id = assigned_order_items.order_queue_station_id left join order_queue_process_by_zones as oqpz on oqpz.order_queue_station_id = oqs.id @@ -62,6 +62,11 @@ class AssignedOrderItem < ApplicationRecord return order_item end + protected + def self.generate_ids(count = 1) + SeedGenerator.generate_ids(self.name, "AOI", count) + end + private def generate_custom_id if self.assigned_order_item_id.nil? diff --git a/app/models/booking.rb b/app/models/booking.rb index 9ca45ec4..c5e5d6f0 100755 --- a/app/models/booking.rb +++ b/app/models/booking.rb @@ -6,11 +6,62 @@ class Booking < ApplicationRecord belongs_to :dining_facility, :optional => true belongs_to :sale, :optional => true + has_one :cashier_terminal_by_dining_facility, through: :dining_facility, source: :cashier_terminal + has_one :current_shift_by_dining_facility, through: :dining_facility, source: :current_shift has_many :booking_orders has_many :orders, :through => :booking_orders - has_many :order_items, :through => :orders + has_many :order_items, :through => :orders do + def to_sale_items + sale_items = [] + proxy_association.load_target.select(&:order_items_id).each do |order_item| + menu_category = order_item.menu_category || OpenStruct.new(name: 'Product', code: '') #get menu category for menu items + + sale_items << SaleItem.new({ + menu_category_name: menu_category.name, + menu_category_code: menu_category.code, + product_name: order_item.item_name, + product_code: order_item.item_code, + product_alt_name: order_item.alt_name, + account_id: order_item.account_id, + is_taxable: order_item.taxable, + item_instance_code: order_item.item_instance_code, + qty: order_item.qty, + unit_price: order_item.price, + price: order_item.qty * order_item.price, + taxable_price: order_item.qty * order_item.price, + status: order_item.remark + }) + + if order_item.set_menu_items + JSON.parse(order_item.set_menu_items).each do |item| + instance = MenuItemInstance.find_by_item_instance_code(item["item_instance_code"]) + menu_item = instance.menu_item + menu_category = menu_item.menu_category #get menu category for menu items + sale_items << SaleItem.new({ + menu_category_name: menu_category.name, + menu_category_code: menu_category.code, + product_name: instance.item_instance_name, + product_code: menu_item.item_code, + product_alt_name: menu_item.alt_name, + account_id: menu_item.account_id, + is_taxable: menu_item.taxable, + item_instance_code: item["item_instance_code"], + qty: item["quantity"], + unit_price: item["price"], + price: item["quantity"].to_f * item["price"].to_f, + taxable_price: item["quantity"].to_f * item["price"].to_f + }) + end + end + end + sale_items + end + end + scope :active, -> {where("booking_status != 'moved'")} scope :today, -> {where("created_at >= #{Time.now.utc}")} + scope :assign, -> { where(booking_status: 'assign')} + scope :within_time_limit, -> { where(checkin_at: Lookup.get_checkin_time_limit.hours.ago..DateTime::Infinity.new) } def self.sync_booking_records(bookings) if !bookings.nil? diff --git a/app/models/cashier_terminal.rb b/app/models/cashier_terminal.rb index d8e38c5f..ca34ac1e 100755 --- a/app/models/cashier_terminal.rb +++ b/app/models/cashier_terminal.rb @@ -1,9 +1,10 @@ class CashierTerminal < ApplicationRecord - has_many :cashier_terminal_by_zones - has_many :zones, through: :cashier_terminal_by_zones + has_many :cashier_terminal_by_zones + has_many :zones, through: :cashier_terminal_by_zones + has_one :current_shift, -> { where.not(shift_started_at: nil).where(shift_closed_at: nil) }, class_name: "ShiftSale" - scope :available, -> {where(is_currently_login: false)} - scope :is_active, -> {where(is_active: true)} + scope :available, -> {where(is_currently_login: false)} + scope :is_active, -> {where(is_active: true)} # validations validates_presence_of :name, :printer_name diff --git a/app/models/customer.rb b/app/models/customer.rb index 04d4449c..0a17cf12 100755 --- a/app/models/customer.rb +++ b/app/models/customer.rb @@ -11,12 +11,20 @@ class Customer < ApplicationRecord validates_presence_of :name, :contact_no, :email #,:card_no validates :contact_no, numericality: true #uniqueness: true, - validates :email, uniqueness: true,format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create } + # validates :email, uniqueness: true,format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create } # validates :card_no, uniqueness: true # validates :paypar_account_no, uniqueness: true paginates_per 50 + def self.walkin + self.find_by(name: "WALK-IN") + end + + def self.takeaway + self.find_by(name: "TAKEAWAY") + end + def self.get_member_account(customer) membership = MembershipSetting.active.find_by_membership_type("paypar_url") memberaction = MembershipAction.active.find_by_membership_type("get_all_member_account") @@ -26,7 +34,7 @@ class Customer < ApplicationRecord # urltest =self.url_exist?(url) if !membership.nil? && !memberaction.nil? begin - response = HTTParty.get(url, :body => { + response = HTTParty.get(url, :body => { membership_id: customer.membership_id, merchant_uid:merchant_uid, type: "summary", @@ -39,7 +47,7 @@ class Customer < ApplicationRecord :timeout => 10) rescue HTTParty::Error response = {status: false, message: "Server Error"} - + rescue Net::OpenTimeout response = { status: false , message: "Server Time out"} @@ -107,7 +115,7 @@ class Customer < ApplicationRecord auth_token = memberaction.auth_token.to_s url = membership.gateway_url.to_s + memberaction.gateway_url.to_s - @customers = Customer.where("membership_type IS NOT NULL AND membership_id IS NULL") + @customers = Customer.where("membership_type IS NOT NULL AND membership_id IS NULL") @customers.each do |customer| member_params = { name: customer.name,phone: customer.contact_no, @@ -125,7 +133,7 @@ class Customer < ApplicationRecord paypar_account_no: customer.paypar_account_no, card_no:customer.card_no,member_group_id: customer.membership_type, merchant_uid:merchant_uid,auth_token:auth_token}.to_json - end + end begin response = HTTParty.post(url, @@ -136,7 +144,7 @@ class Customer < ApplicationRecord }) rescue Net::OpenTimeout response = { status: false, message: "Server Time out" } - + rescue OpenURI::HTTPError response = { status: false, message: "Can't connect server"} @@ -154,12 +162,12 @@ class Customer < ApplicationRecord def self.update_rebate sales = Sale.where("rebate_status = 'false'") sales.each do |sale| - if sale.customer.membership_id + if sale.customer.membership_id response = self.rebat(Sale.find(sale.sale_id)) #record an payment in sale-audit if !response.nil? remark = "UPdate Rebate Response - #{response} for Customer #{sale.customer_id} Sale Id [#{sale.sale_id}]| pay amount -> #{sale.amount_received} " - sale_audit = SaleAudit.record_paymal(sale.sale_id, remark, 1) + sale_audit = SaleAudit.record_paymal(sale.sale_id, remark, 1) end if response["status"] == true status = sale.update_attributes(rebate_status: "true") @@ -172,7 +180,7 @@ class Customer < ApplicationRecord rebate_prices,campaign_method = SaleItem.calculate_rebate_by_account(sObj.sale_items) generic_customer_id = sObj.customer.membership_id - + if generic_customer_id.present? paypar = sObj.sale_payments payparcost = 0 @@ -189,7 +197,7 @@ class Customer < ApplicationRecord end # overall_dis = SaleItem.get_overall_discount(sObj.id) overall_dis = sObj.total_discount - + if credit != 1 membership = MembershipSetting.find_by_membership_type("paypar_url") memberaction = MembershipAction.find_by_membership_type("get_member_campaign") @@ -200,8 +208,8 @@ class Customer < ApplicationRecord # Control for Paypar Cloud begin - response = HTTParty.get(url, - :body => { + response = HTTParty.get(url, + :body => { member_group_id:sObj.customer.membership_type, merchant_uid:merchant_uid, campaign_type_id: campaign_type_id, @@ -215,7 +223,7 @@ class Customer < ApplicationRecord response = { "status": false , "message": "Connect To" } rescue OpenURI::HTTPError response = { "status": false, "message": "Can't connect server"} - + rescue SocketError response = { "status": false, "message": "Can't connect server"} end @@ -232,7 +240,7 @@ class Customer < ApplicationRecord response["membership_campaign_data"].each do |a| data = {:type => a["rules_type"], :percentage => a["change_unit"].to_i * a["base_unit"].to_i} total_percentage = total_percentage + a["change_unit"].to_i * a["base_unit"].to_i - + type_arr.push(data) end end @@ -249,7 +257,7 @@ class Customer < ApplicationRecord actual = a[:amount] - amount data[:amount] = actual end - + end end rebate_arr.push(data) @@ -272,8 +280,8 @@ class Customer < ApplicationRecord # Control for Paypar Cloud begin - response = HTTParty.post(url, - :body => { + response = HTTParty.post(url, + :body => { generic_customer_id:generic_customer_id , total_sale_transaction_amount: sObj.grand_total, merchant_uid:merchant_uid, @@ -291,7 +299,7 @@ class Customer < ApplicationRecord response = { "status": false , "message": "Connect To" } rescue OpenURI::HTTPError response = { "status": false, "message": "Can't connect server"} - + rescue SocketError response = { "status": false, "message": "Can't connect server"} end @@ -302,7 +310,7 @@ class Customer < ApplicationRecord end else puts "no Response" - response = { "status": "no_member", "message": "Not membership"} + response = { "status": "no_member", "message": "Not membership"} end end @@ -313,8 +321,8 @@ class Customer < ApplicationRecord auth_token = memberaction.auth_token.to_s url = membership.gateway_url.to_s + memberaction.gateway_url.to_s begin - response = HTTParty.get(url, - :body => { paypar_account_no:account_no, + response = HTTParty.get(url, + :body => { paypar_account_no:account_no, merchant_uid:merchant_uid, auth_token:auth_token }.to_json, diff --git a/app/models/dining_charge.rb b/app/models/dining_charge.rb index 6f931bcf..bfca726e 100755 --- a/app/models/dining_charge.rb +++ b/app/models/dining_charge.rb @@ -4,7 +4,7 @@ class DiningCharge < ApplicationRecord def self.amount_calculate(dining_charges_obj, checkin , checkout) # note :: the first Charge Block will cost all, the Time rounding block will included in 2nd Charge Block - if !checkin.nil? && !checkout.nil? && !dining_charges_obj.nil? + if !checkin.nil? && !checkout.nil? && !dining_charges_obj.nil? block_count = 0 price = 0 minutes = DiningCharge.time_diff(checkout, checkin) @@ -13,18 +13,17 @@ class DiningCharge < ApplicationRecord if dining_minutes <= free_time price = 0 else - charge_type = dining_charges_obj.charge_type + charge_type = dining_charges_obj.charge_type if charge_type == 'hr' block_count, price = DiningCharge.charges(dining_charges_obj, dining_minutes, 'hr') elsif charge_type == 'day' block_count, price = DiningCharge.charges(dining_charges_obj, dining_minutes, 'day') end end - return block_count, price + return block_count, price else - puts "<<<<<<<< NO" + return 0, 0 end - end # dining charges calculate @@ -37,7 +36,7 @@ class DiningCharge < ApplicationRecord rounding_time = DiningCharge.convert_to_minutes(chargesObj.time_rounding_block.utc.strftime('%H:%M')) if result.to_i < 1 # for dining minute is under charge_block - if dining_minutes > rounding_time + if dining_minutes > rounding_time rounding_block = dining_minutes / rounding_time solid_price = rounding_block * chargesObj.time_rounding_block_price @@ -46,7 +45,7 @@ class DiningCharge < ApplicationRecord else return 1, result.to_i,chargesObj.unit_price end - elsif result.to_i >= 1 + elsif result.to_i >= 1 solid_price = result * chargesObj.unit_price @@ -64,7 +63,7 @@ class DiningCharge < ApplicationRecord else solid_price += (roundingblock * chargesObj.time_rounding_block_price) - return result.to_i, DiningCharge.check_rounding(chargesObj, solid_price, extra_minutes) + return result.to_i, DiningCharge.check_rounding(chargesObj, solid_price, extra_minutes) end end end @@ -74,7 +73,7 @@ class DiningCharge < ApplicationRecord # rounding_block_remain = roundingblock / 1 free_time = DiningCharge.convert_to_minutes(chargesObj.minimum_free_time.utc.strftime('%H:%M')) rounding_block_remain = extra_minutes - free_time - + if chargesObj.time_rounding == "down" return solid_price else diff --git a/app/models/dining_facility.rb b/app/models/dining_facility.rb index e5f35e03..b3f31fa3 100755 --- a/app/models/dining_facility.rb +++ b/app/models/dining_facility.rb @@ -1,7 +1,20 @@ class DiningFacility < ApplicationRecord belongs_to :zone - has_many :dining_charges has_many :in_juties + has_one :dining_charge + has_one :cashier_terminal_by_zone, foreign_key: "zone_id", primary_key: "zone_id" + has_one :cashier_terminal, through: :cashier_terminal_by_zone + has_one :current_shift, through: :cashier_terminal + has_many :order_queue_process_by_zones, foreign_key: "zone_id", primary_key: "zone_id" + has_many :order_queue_stations, -> { where(is_active: true) }, through: :order_queue_process_by_zones + + has_many :bookings + has_many :current_bookings, -> { left_joins(:sale).assign.within_time_limit.merge(Booking.where(checkout_at: nil).or(Booking.merge(Sale.where(sale_status: ['new', nil])))) }, class_name: "Booking" + has_one :current_checkin_booking, -> { left_joins(:sale).assign.within_time_limit.merge(Sale.where(sale_status: nil)) }, class_name: "Booking" + has_one :current_checkout_booking, -> { left_joins(:sale).assign.within_time_limit.where.not(checkout_at: nil).merge(Sale.where(sale_status: 'new')) }, class_name: "Booking" + has_one :current_reserved_booking, -> { left_joins(:sale).assign.within_time_limit.where.not(reserved_at: nil).merge(Sale.where(sale_status: nil)) }, class_name: "Booking" + + has_many :current_sales, -> { where(sale_status: 'new').merge(Booking.assign.within_time_limit) }, through: :bookings, class_name: "Sale", source: "sale" TABLE_TYPE = "Table" ROOM_TYPE = "Room" @@ -21,7 +34,7 @@ class DiningFacility < ApplicationRecord end def get_booking - booking = self.get_current_booking + booking = self.current_checkin_booking if booking if booking.dining_facility_id.to_i == self.id if booking.booking_status == 'assign' @@ -33,54 +46,11 @@ class DiningFacility < ApplicationRecord def get_current_booking checkin_time_lookup = Lookup.get_checkin_time_limit - booking = Booking.where("dining_facility_id = #{self.id} and booking_status ='assign' and (CASE WHEN checkin_at > '#{DateTime.now.utc}' THEN checkin_at >= '#{DateTime.now.utc}' ELSE checkin_at between '#{DateTime.now.utc - checkin_time_lookup.hours}' and '#{DateTime.now.utc}' END) and checkout_by is null").limit(1) #and checkout_at is null - # booking = Booking.where("dining_facility_id = #{self.id} and booking_status ='assign' and checkin_at between '#{DateTime.now.utc - 5.hours}' and '#{DateTime.now.utc}' and checkout_by is null").limit(1) #and checkout_at is null - if booking.count > 0 then - return booking[0] - else - return nil - end - end - - def get_moved_booking - checkin_time_lookup = Lookup.get_checkin_time_limit - booking = Booking.where("dining_facility_id = #{self.id} and booking_status ='moved' and checkin_at between '#{DateTime.now.utc - checkin_time_lookup.hours}' and '#{DateTime.now.utc}' and checkout_at is null").limit(1) - - if booking.count > 0 then - return booking[0] - else - return nil - end - end - - def get_new_booking - # query for new - # if status - # to ask when req bill booking_status? - booking = Booking.where("dining_facility_id = #{self.id} and booking_status ='assign' and sale_id is null and checkout_at is null").limit(1) - # else - # booking = Booking.where("dining_facility_id = #{self.id} and booking_status ='assign' and sale_id not null").limit(1) - # end - - if booking.count > 0 then - return booking[0].booking_id - else - return nil - end - end - - def get_current_checkout_booking - checkin_time_lookup = Lookup.get_checkin_time_limit - booking = Booking.where("dining_facility_id = #{self.id} and booking_status ='assign' and checkin_at between '#{DateTime.now.utc - checkin_time_lookup.hours}' and '#{DateTime.now.utc}' and reserved_by is not null and checkout_by is null").limit(1) - if booking.count > 0 then - return booking[0] - else - return nil - end + Booking.where(dining_facility_id: self.id, booking_status: 'assign', checkout_at: nil).where("checkin_at > ?", checkin_time_lookup.hours.ago).first #and checkout_at is null end def get_checkout_booking - booking = self.get_current_checkout_booking + booking = self.current_reserved_booking if booking lookup_checkout_time = Lookup.collection_of("checkout_alert_time") free_time_min = 0 @@ -119,7 +89,7 @@ class DiningFacility < ApplicationRecord def self.get_checkin_booking checkin_time_lookup = Lookup.get_checkin_time_limit - bookings = Booking.where("booking_status ='assign' and checkin_at between '#{DateTime.now.utc - checkin_time_lookup.hours}' and '#{DateTime.now.utc}' and reserved_by is not null and checkout_by is null") + bookings = self.current_checkin_booking arr_booking = Array.new if bookings lookup_checkout_time = Lookup.collection_of("checkout_alert_time") diff --git a/app/models/employee.rb b/app/models/employee.rb index f27adf29..0a103ab7 100755 --- a/app/models/employee.rb +++ b/app/models/employee.rb @@ -2,6 +2,8 @@ class Employee < ApplicationRecord has_secure_password has_many :commissioners has_many :shit_sales + has_one :current_shift, -> { where.not(shift_started_at: nil).where(shift_closed_at: nil) },class_name: "ShiftSale" + has_one :cashier_terminal, through: :current_shift belongs_to :order_queue_station validates_presence_of :name, :role diff --git a/app/models/kbz_pay.rb b/app/models/kbz_pay.rb index 5893e048..523a7fc5 100644 --- a/app/models/kbz_pay.rb +++ b/app/models/kbz_pay.rb @@ -3,13 +3,13 @@ class KbzPay KBZ_PAY = 'KBZPay' def self.pay(amount, receipt_no, url, key, app_id, code) - shop = Shop.first + shop = Shop.current_shop prefix = shop.shop_code receipt_no = "#{prefix}#{receipt_no}" datetime = DateTime.now.strftime("%d%m%Y%H%M") kbz_app_id = app_id - kbz_merch_code = code + kbz_merch_code = code kbz_api_key = key kbz_provider_url = "#{url}/precreate" @@ -58,17 +58,17 @@ class KbzPay # Rails.logger.debug result['Response'] return false, result['Response'] end - + end def self.query(receipt_no, current_user, url, key, app_id, code) - shop = Shop.first + shop = Shop.current_shop prefix = shop.shop_code receipt_no = "#{prefix}#{receipt_no}" amount = 0 datetime = DateTime.now.strftime("%d%m%Y%H%M") kbz_app_id = app_id - kbz_merch_code = code + kbz_merch_code = code kbz_api_key = key kbz_provider_url = "#{url}/queryorder" @@ -122,7 +122,7 @@ class KbzPay # return true, "successfully paid by KBZ PAY" elsif result['Response']['trade_status'] == "PAY_FAILED" - + # return false, "pay failed by KBZ PAY" elsif result['Response']['trade_status'] == "WAIT_PAY" # return false , "Waiting to pay by KBZ PAY" @@ -135,4 +135,4 @@ class KbzPay return amount end -end \ No newline at end of file +end diff --git a/app/models/lookup.rb b/app/models/lookup.rb index 5b45822c..a9cb2348 100755 --- a/app/models/lookup.rb +++ b/app/models/lookup.rb @@ -4,6 +4,8 @@ class Lookup < ApplicationRecord scope :number_formats, -> { where(lookup_type: 'number_format')} + TIME_LIMIT = 5 + def available_types {'Employee Roles' => 'employee_roles', 'Dining Facilities Status' => 'dining_facilities_status', @@ -23,15 +25,13 @@ class Lookup < ApplicationRecord # Lookup.select("value, name").where("lookup_type = ?", lookup_type ).order("name asc").map { |r| [r.name, r.value] } # end + def self.time_limit + TIME_LIMIT + end + def self.get_checkin_time_limit - time_limit = 5 - - lookup = Lookup.find_by_lookup_type('checkin_time_limit') - if !lookup.nil? - time_limit = lookup.value.to_i - end - - return time_limit + return RequestStore[:checkin_time_limit] if RequestStore[:checkin_time_limit] + RequestStore[:checkin_time_limit] = Lookup.find_by_lookup_type('checkin_time_limit').value.to_i rescue time_limit end def self.sync_url @@ -57,8 +57,7 @@ class Lookup < ApplicationRecord end def self.collection_of(type) - Lookup.select("name, value").where("lookup_type" => type ).map { |l| [l.name, l.value] } - + Lookup.where("lookup_type" => type ).pluck("name, value") end def self.create_shift_sale_lookup diff --git a/app/models/menu.rb b/app/models/menu.rb index a825cc7b..1dd0aaed 100755 --- a/app/models/menu.rb +++ b/app/models/menu.rb @@ -141,7 +141,7 @@ class Menu < ApplicationRecord end else # Menu by Menu Import - @shop = Shop.first + @shop = Shop.current_shop shop_code = "" if !@shop.nil? if @shop.shop_code diff --git a/app/models/menu_item.rb b/app/models/menu_item.rb index 59791cb2..5edf9513 100755 --- a/app/models/menu_item.rb +++ b/app/models/menu_item.rb @@ -31,26 +31,26 @@ class MenuItem < ApplicationRecord # Work with item_code = item_instance_code def self.search_by_item_code(item_code) - menu_item_hash = Hash.new - mt_instance = MenuItemInstance.find_by_item_instance_code(item_code) - if (!mt_instance.nil?) - menu_item = MenuItem.find(mt_instance.menu_item_id) - menu_item_hash[:type] = menu_item.type - menu_item_hash[:account_id] = menu_item.account_id - menu_item_hash[:item_code] = menu_item.item_code - menu_item_hash[:item_instance_code] = mt_instance.item_instance_code - menu_item_hash[:name] = menu_item.name.to_s + " - " + mt_instance.item_instance_name.to_s - menu_item_hash[:alt_name] = menu_item.alt_name.to_s # + " - " + mt_instance.item_instance_name.to_s - menu_item_hash[:price] = mt_instance.price - menu_item_hash[:promotion_price] = mt_instance.promotion_price - menu_item_hash[:is_on_promotion] = mt_instance.is_on_promotion - menu_item_hash[:is_available] = mt_instance.is_available - menu_item_hash[:taxable] = menu_item.taxable - - return menu_item_hash - end - - return nil + MenuItem.left_joins(:menu_item_instances => :menu_instance_item_sets) + .where(menu_item_instances: {item_instance_code: item_code}) + .pluck(:type, :account_id, :item_code, :item_instance_code, :name, :alt_name, :item_instance_name, :price, :promotion_price, :is_on_promotion, "menu_item_instances.is_available", :taxable, :item_set_id) + .map { |type, account_id, item_code, item_instance_code, item_name, item_alt_name, item_instance_name, price, promotion_price, is_on_promotion, is_available, taxable, item_set_id| + name = item_instance_name if item_set_id + name ||= "#{item_name}#{' - ' + item_instance_name if item_instance_name.present?}" + { + type: type, + account_id: account_id, + item_code: item_code, + item_instance_code: item_instance_code, + name: "#{name}", + alt_name: "#{item_alt_name}", + price: price, + promotion_price: promotion_price, + is_on_promotion: is_on_promotion, + is_available: is_available, + taxable: taxable + } + } end def self.deleteRecursive(menu_item) diff --git a/app/models/order.rb b/app/models/order.rb index cd350e34..0a6b8ddb 100755 --- a/app/models/order.rb +++ b/app/models/order.rb @@ -26,16 +26,11 @@ class Order < ApplicationRecord def generate booking = nil if self.new_booking - if self.table_id.to_i > 0 - table_id = self.table_id - else - table_id = nil - end #add extra time if self.is_extra_time && self.extra_time booking = Booking.create({:dining_facility_id => table_id,:type => "TableBooking", - :checkin_at => Time.now.utc,:checkout_at => Time.now.utc + self.extra_time.to_i, - :checkin_by => self.employee_name, + :checkin_at => Time.now.utc, :checkout_at => Time.now.utc + self.extra_time.to_i, + :checkin_by => self.employee_name, :booking_status => "assign" }) else booking = Booking.create({:dining_facility_id => table_id,:type => "TableBooking", @@ -50,7 +45,6 @@ class Order < ApplicationRecord # table.status = "occupied" # table.save end - else booking = Booking.find(self.booking_id) #add extra time @@ -70,7 +64,7 @@ class Order < ApplicationRecord self.adding_line_items #Add Order Table and Room relation afrer order creation - BookingOrder.create({:booking_id => booking.booking_id, :order => self}) + booking.orders << self #Send order to queue one it done! # if self.source != "quick_service" @@ -107,7 +101,7 @@ class Order < ApplicationRecord self.adding_line_items #Add Order Table and Room relation afrer order creation - BookingOrder.create({:booking_id => booking.booking_id, :order => self}) + booking.orders << self #Send order to queue one it done! # if self.source != "quick_service" @@ -118,7 +112,6 @@ class Order < ApplicationRecord send_order_broadcast(booking) return true, booking - end return false @@ -133,49 +126,36 @@ class Order < ApplicationRecord def adding_line_items if self.items #re-order to - ordered_list = re_order_items(self.items) - + items = re_order_items(self.items) #loop to add all items to order - ordered_list.each do |item| + item_instance_codes = items.map { |i| i[:item_instance_code] } + menu_items = MenuItem.search_by_item_code(item_instance_codes) + menu_items += Product.search_by_product_code(item_instance_codes) if menu_items.length < item_instance_codes.length - menu_item = MenuItem.search_by_item_code(item[:item_instance_code]) - - # For Product while item code not in menu item - if menu_item.nil? - menu_item = Product.search_by_product_code(item[:item_instance_code]) - end - - #if (!menu_item.nil?) - # Rails.logger.debug menu_item - set_order_items = Array.new - ##If menu Item set item - must add child items to order as well, where price is only take from menu_item - if (menu_item[:type] == "SetMenuItem") - if (item.include? 'sub_items') || (item.include? :sub_items) - item[:sub_items].each do |si| - # Retrive instance's Price - set_item = MenuItem.search_by_item_code(si[:item_instance_code]) - set_order_items.push({"item_instance_code"=>si[:item_instance_code], "item_instance_name"=>set_item[:name], "quantity"=>si[:quantity], "price"=>set_item[:price], "options"=>si[:options]}) - end - end - set_order_items = set_order_items.to_json - else - set_order_items = nil + items.each do |order_item| + menu_item = menu_items.find { |i| i[:item_instance_code].downcase == order_item[:item_instance_code].downcase } + sub_order_items = [] + if order_item[:sub_items].length > 0 + sub_menu_items = MenuItem.search_by_item_code(order_item[:sub_items].map { |i| i[:item_instance_code] }) + order_item[:sub_items].each do |sub_order_item| + sub_menu_item = sub_menu_items.find { |i| i[:item_instance_code] == sub_order_item[:item_instance_code] } + sub_order_items << { item_instance_code: sub_order_item[:item_instance_code], item_instance_name: sub_menu_item[:name], quantity: sub_order_item[:quantity], price: sub_menu_item[:price], options: sub_order_item[:options] } end - - # not insert with price 0 - # puts item[:price] - # puts item - # if(item[:price] != 0 ) - # OrderItem.processs_item(menu_item[:item_code], menu_item[:name], menu_item[:account_id], - # item[:quantity],menu_item[:price], item[:options], set_order_items, self.id, - # self.employee_name) - # end - - OrderItem.processs_item(menu_item[:item_code], item[:item_instance_code], menu_item[:name], menu_item[:alt_name], menu_item[:account_id], - item[:quantity],menu_item[:price], item[:options], set_order_items, self.id, - self.employee_name, menu_item[:taxable]) - - #end + end + sub_order_items = sub_order_items.to_json + self.order_items.build({ + item_code: menu_item[:item_code], + item_instance_code: order_item[:item_instance_code], + item_name: menu_item[:name], + alt_name: menu_item[:alt_name], + account_id: menu_item[:account_id], + qty: order_item[:quantity], + price: menu_item[:price], + options: order_item[:options], + set_menu_items: sub_order_items, + item_order_by: employee_name, + taxable: menu_item[:taxable] + }) end self.item_count = self.order_items.count @@ -186,7 +166,6 @@ class Order < ApplicationRecord self.errors.add(:order_items, :blank, message: "Order items cannot be blank") return false end - end def update_items_status_to_billed(items) @@ -207,72 +186,14 @@ class Order < ApplicationRecord end def default_values - self.customer = Customer.find(1) if self.customer_id.nil? + self.customer = Customer.walkin if self.customer_id.nil? self.source = "emenu" if self.source.nil? self.order_type = "dine-in" if self.order_type.nil? end protected - def re_order_items(form_items) #reorder inputs items as parents and child - parent_id = Array.new - parents = Array.new - parents_and_children_items = Array.new - - new_items_list = Array.new - - form_items.each do |parent| - if !parent[:parent_order_item_id].nil? - if (!parent_id.include?(parent[:parent_order_item_id])) - parent_id.push(parent[:parent_order_item_id]) - - end - end - end - Rails.logger.debug "Parent Id count -> " + parent_id.count.to_s - - - parent_id.each do |pid| - form_items.each do |item| - Rails.logger.debug "Adding - Parents -> " + pid.to_s + " - " + item[:order_item_id].to_s - if (pid == item[:order_item_id]) - parents.push(item) - end - end - end - Rails.logger.debug "Parents count -> " + parents.count.to_s - - parents.each do |parent| - children = Array.new - form_items.each do |item| - if (parent[:order_item_id] == item[:parent_order_item_id] ) - children.push(item) - #Items to remove for new list - parents_and_children_items.push(item) - end - end - parent[:sub_items] = children - end - Rails.logger.debug "Parent/children Items to remove -> " + parents_and_children_items.count.to_s - - #Remove process items - #c = a.reject{ |e| b.include? e } - - new_items_list = form_items - parents_and_children_items - - - Rails.logger.debug "New list count -> " + new_items_list.count.to_s - - #Add parent to the list - #new_items_list = new_items_list + parents - - Rails.logger.debug "Re-Order List (Parent)-" - - Rails.logger.debug parents - - Rails.logger.debug "Re-Order List -" - Rails.logger.debug new_items_list - - return new_items_list + def re_order_items(items) #reorder inputs items as parents and child + new_items = items.select { |i| i[:parent_order_item_id].blank? }.map { |x| x[:sub_items] = items.select { |y| x[:order_item_id] == y[:parent_order_item_id] }; x } end @@ -485,62 +406,28 @@ class Order < ApplicationRecord print_status = nil cup_status = nil - #Send to background job for processing - order = Order.find(order_id) - sidekiq = Lookup.find_by_lookup_type("sidekiq") + #Send to background job for processing + order = Order.find(order_id) + sidekiq = Lookup.find_by_lookup_type("sidekiq") - if ENV["SERVER_MODE"] != 'cloud' - cup_status = `#{"sudo service cups status"}` - print_status = check_cup_status(cup_status) + if ENV["SERVER_MODE"] != 'cloud' + if Printer::PrinterWorker.printers.blank? + msg = 'Print Error ! Please contact to service' + ActionCable.server.broadcast "call_waiter_channel", table: msg, time:'print_error', from: '' end + end - if print_status - if !sidekiq.nil? - OrderQueueProcessorJob.perform_later(order_id, table_id) - else - if order - oqs = OrderQueueStation.new - oqs.process_order(order, table_id, source) - end - # assign_order = AssignedOrderItem.assigned_order_item_by_job(order_id) - # ActionCable.server.broadcast "order_queue_station_channel",order: assign_order - end - else - if ENV["SERVER_MODE"] != 'cloud' - cup_start = `#{"sudo service cups start"}` - cup_status = `#{"sudo service cups status"}` - print_status = check_cup_status(cup_status) - end - - if print_status - if !sidekiq.nil? - OrderQueueProcessorJob.perform_later(order_id, table_id) - else - if order - oqs = OrderQueueStation.new - oqs.process_order(order, table_id, source) - end - # assign_order = AssignedOrderItem.assigned_order_item_by_job(order_id) - # ActionCable.server.broadcast "order_queue_station_channel",order: assign_order - end - else - if ENV["SERVER_MODE"] != 'cloud' - - msg = ' Print Error ! Please contact to service' - ActionCable.server.broadcast "call_waiter_channel",table: msg,time:'print_error' - end - if !sidekiq.nil? - OrderQueueProcessorJob.perform_later(order_id, table_id) - else - if order - oqs = OrderQueueStation.new - oqs.process_order(order, table_id, source) - end - assign_order = AssignedOrderItem.assigned_order_item_by_job(order_id) - ActionCable.server.broadcast "order_queue_station_channel",order: assign_order - end - end + if !sidekiq.nil? + OrderQueueProcessorJob.perform_later(order_id, table_id) + else + if order + oqs = OrderQueueStation.new + oqs.process_order(order, table_id, order_source) end + from = getCloudDomain #get sub domain in cloud mode + assign_order = AssignedOrderItem.assigned_order_item_by_job(order_id) + ActionCable.server.broadcast "order_queue_station_channel", order: assign_order, from: from + end end def self.check_cup_status(status) diff --git a/app/models/order_item.rb b/app/models/order_item.rb index 3e75ecba..4ff895af 100755 --- a/app/models/order_item.rb +++ b/app/models/order_item.rb @@ -5,8 +5,10 @@ class OrderItem < ApplicationRecord before_create :generate_custom_id #Associations - belongs_to :order, autosave: true - # belongs_to :order, counter_cache: true + belongs_to :order, autosave: true + has_one :menu_item, foreign_key: "item_code", primary_key: "item_code" + has_one :menu_category, through: :menu_item + # belongs_to :order, counter_cache: true #Validation validates_presence_of :item_code, :item_name, :qty @@ -102,7 +104,13 @@ class OrderItem < ApplicationRecord end end + protected + def self.generate_ids(count = 1) + SeedGenerator.generate_ids(self.name, "ODI", count) + end + private + def generate_custom_id if self.order_items_id.nil? self.order_items_id = SeedGenerator.generate_id(self.class.name, "ODI") diff --git a/app/models/order_queue_station.rb b/app/models/order_queue_station.rb index 147ebdc4..f650b807 100755 --- a/app/models/order_queue_station.rb +++ b/app/models/order_queue_station.rb @@ -5,7 +5,7 @@ class OrderQueueStation < ApplicationRecord has_many :assigned_order_items has_many :order_items - has_many :order_queue_process_by_zones + has_many :order_queue_process_by_zones has_many :zones, through: :order_queue_process_by_zones belongs_to :employee @@ -14,110 +14,45 @@ class OrderQueueStation < ApplicationRecord # validations validates_presence_of :station_name, :printer_name - def process_order (order, table_id, order_source = nil, pdf_status = nil ,change_to=nil,current_user=nil) - - oqs_stations = OrderQueueStation.active - - + def process_order(order, table_id, order_source = nil, pdf_status = nil ,change_to=nil, current_user=nil) order_items = order.order_items if table_id.to_i > 0 - # get dining - dining = DiningFacility.find(table_id) - oqs_by_zones = OrderQueueProcessByZone.where("zone_id=#{dining.zone_id}") - booking = Booking.find_by_dining_facility_id(dining.id) - - # ToDo per item per printer - - oqs_by_zones.each do |oqpbz| - oqs = OrderQueueStation.find(oqpbz.order_queue_station_id) - is_auto_printed = false - oqs_order_items = [] - - if oqs.is_active - #Get List of items - - pq_items = JSON.parse(oqs.processing_items) - #Loop through the processing items - pq_items.each do |pq_item| - #Processing through the looping items - order_items.each do |order_item| - if (pq_item == order_item.item_code) - # if oqs.id == oqpbz.order_queue_station_id - # #Same Order_items can appear in two location. - # AssignedOrderItem.assigned_order_item(order, order_item.item_code, oqs) - # else - - if (order_item.qty > 0) - if pdf_status.nil? - AssignedOrderItem.assigned_order_item(order, order_item.item_code, order_item.item_instance_code, oqs) - end - oqs_order_items.push(order_item) - end - # end - end - end - end - - if oqs.auto_print && order_source != "quick_service" - if oqs_order_items.length > 0 - if oqs.cut_per_item - print_slip_item(oqs, order, oqs_order_items,pdf_status,change_to,current_user,table_id) - else - print_slip(oqs, order, oqs_order_items,pdf_status,change_to,current_user,table_id) - end - is_auto_printed = true - end - end - end - end + # get dining + dining = DiningFacility.find(table_id) + oqs_stations = dining.order_queue_stations else - oqs_stations.each do |oqs| - is_auto_printed = false - oqs_order_items = [] + oqs_stations = OrderQueueStation.active + end - if oqs.is_active - #Get List of items - - pq_items = JSON.parse(oqs.processing_items) - #Loop through the processing items - pq_items.each do |pq_item| - #Processing through the looping items - order_items.each do |order_item| - if (pq_item == order_item.item_code) - # if oqs.id == oqpbz.order_queue_station_id - # #Same Order_items can appear in two location. - # AssignedOrderItem.assigned_order_item(order, order_item.item_code, oqs) - # else - - if (order_item.qty > 0) - if pdf_status.nil? - AssignedOrderItem.assigned_order_item(order, order_item.item_code, order_item.item_instance_code, oqs) - end - oqs_order_items.push(order_item) - end - # end - end - end + assigned_order_items = [] + oqs_order_items_by_zones = [] + + # ToDo per item per printer + oqs_stations.each do |oqs| + oqs_order_items = order_items.select { |i| JSON.parse(oqs.processing_items).include? i.item_code } + oqs_order_items_by_zones << { oqs: oqs, oqs_order_items: oqs_order_items } + + print_status = false + if oqs.auto_print && order_source != "quick_service" + print_status = true + if oqs_order_items.length > 0 + if oqs.cut_per_item + print_slip_item(oqs, order, oqs_order_items, pdf_status, change_to, current_user, table_id) + else + print_slip(oqs, order, oqs_order_items, pdf_status, change_to, current_user, table_id) end - - if oqs.auto_print && order_source != "quick_service" - if oqs_order_items.length > 0 - if oqs.cut_per_item - print_slip_item(oqs, order, oqs_order_items,pdf_status,change_to,current_user,table_id) - else - print_slip(oqs, order, oqs_order_items,pdf_status,change_to,current_user,table_id) - end - is_auto_printed = true - end - end end end - end #end else + + oqs_order_items.each { |i| AssignedOrderItem.create({ order: order, item_code: i.item_code, instance_code: i.item_instance_code, order_queue_station: oqs, print_status: print_status, delivery_status: false }) } + end end - def pay_process_order_queue (order_id, table_id) + def pay_process_order_queue (order_id, table_id) oqs_stations = OrderQueueStation.active - + order = Order.find(order_id) order_items = order.order_items @@ -129,22 +64,22 @@ class OrderQueueStation < ApplicationRecord # assign_order = AssignedOrderItem.assigned_order_item_by_job(order_id) # if ENV["SERVER_MODE"] == 'cloud' # from = request.subdomain + "." + request.domain - # else + # else # from = "" # end # ActionCable.server.broadcast "order_queue_station_channel",order: assign_order,from:from if table_id.to_i > 0 - # get dining - dining = DiningFacility.find(table_id) + # get dining + dining = DiningFacility.find(table_id) oqs_by_zones = OrderQueueProcessByZone.where("zone_id=#{dining.zone_id}") - booking = Booking.find_by_dining_facility_id(dining.id) - + booking = Booking.find_by_dining_facility_id(dining.id) + # ToDo per item per printer oqs_by_zones.each do |oqpbz| oqs = OrderQueueStation.find(oqpbz.order_queue_station_id) - is_auto_printed = false + is_auto_printed = false oqs_order_items = [] if oqs.is_active @@ -157,26 +92,26 @@ class OrderQueueStation < ApplicationRecord if (pq_item == order_item.item_code) if (order_item.qty > 0) oqs_order_items.push(order_item) - end + end end end end - + if oqs.auto_print - if oqs_order_items.length > 0 + if oqs_order_items.length > 0 if oqs.cut_per_item print_slip_item(oqs, order, oqs_order_items) - else + else print_slip(oqs, order, oqs_order_items) end is_auto_printed = true end - end + end end end else oqs_stations.each do |oqs| - is_auto_printed = false + is_auto_printed = false oqs_order_items = [] if oqs.is_active @@ -186,107 +121,58 @@ class OrderQueueStation < ApplicationRecord pq_items.each do |pq_item| #Processing through the looping items order_items.each do |order_item| - if (pq_item == order_item.item_code) + if (pq_item == order_item.item_code) if (order_item.qty > 0) oqs_order_items.push(order_item) - end + end end end end - + if oqs.auto_print - if oqs_order_items.length > 0 + if oqs_order_items.length > 0 if oqs.cut_per_item print_slip_item(oqs, order, oqs_order_items) - else + else print_slip(oqs, order, oqs_order_items) end is_auto_printed = true end - end + end end end - end #end else + end #end else end private #Print order_items in 1 slip def print_slip(oqs, order, order_items ,pdf_status=nil,change_to=nil,current_user=nil,table_id=nil) if pdf_status.nil? - printer = PrintSetting.all.order("id ASC") - unique_code="OrderSummaryPdf" - - if !printer.empty? - printer.each do |printer_setting| - if printer_setting.unique_code == 'OrderSummaryPdf' - unique_code="OrderSummaryPdf" - elsif printer_setting.unique_code == 'OrderSummarySlimPdf' - unique_code="OrderSummarySlimPdf" - elsif printer_setting.unique_code == 'OrderSummarySetPdf' - unique_code="OrderSummarySetPdf" - elsif printer_setting.unique_code == 'OrderSummaryCustomisePdf' - unique_code="OrderSummaryCustomisePdf" - elsif printer_setting.unique_code == 'OrderSummarySetCustomisePdf' - unique_code="OrderSummarySetCustomisePdf" - elsif printer_setting.unique_code == 'OrderSummarySlimCustomisePdf' - unique_code="OrderSummarySlimCustomisePdf" - end - end - end - - print_settings=PrintSetting.find_by_unique_code(unique_code) - order_queue_printer= Printer::OrderQueuePrinter.new(print_settings) - order_queue_printer.print_order_summary(print_settings, oqs,order.order_id, order_items, print_status="") + if print_settings = PrintSetting.where("unique_code REGEXP ?", "order.*summary.*pdf").first + order_queue_printer = Printer::OrderQueuePrinter.new(print_settings) + order_queue_printer.print_order_summary(print_settings, oqs, order.order_id, order_items, print_status="") + end else move_print_pdf(change_to,current_user,table_id,order_items,oqs) end - - assigned =AssignedOrderItem.where("order_id = '#{ order.order_id }'").pluck(:assigned_order_item_id) - AssignedOrderItem.where('assigned_order_item_id IN (?)', assigned).update_all(print_status: true) end #Print order_item in 1 slip per item def print_slip_item(oqs, order, assigned_items,pdf_status=nil,change_to=nil,current_user=nil,table_id=nil) - if pdf_status.nil? - printer = PrintSetting.all.order("id ASC") - unique_code="OrderItemPdf" - - if !printer.empty? - printer.each do |printer_setting| - if printer_setting.unique_code == 'OrderItemPdf' - unique_code="OrderItemPdf" - elsif printer_setting.unique_code == 'OrderItemStarPdf' - unique_code="OrderItemStarPdf" - elsif printer_setting.unique_code == 'OrderItemSlimPdf' - unique_code="OrderItemSlimPdf" - elsif printer_setting.unique_code == 'OrderSetItemPdf' - unique_code="OrderSetItemPdf" - elsif printer_setting.unique_code == 'OrderItemCustomisePdf' - unique_code="OrderItemCustomisePdf" - elsif printer_setting.unique_code == 'OrderSetItemCustomisePdf' - unique_code="OrderSetItemCustomisePdf" - elsif printer_setting.unique_code == 'OrderItemSlimCustomisePdf' - unique_code="OrderItemSlimCustomisePdf" - end - end - end - # order_item = OrderItem.where("order_id='#{assigned_item.order_id}' AND item_instance_code='#{assigned_item.instance_code}'").first() - # print when complete click - print_settings=PrintSetting.find_by_unique_code(unique_code) - order_queue_printer= Printer::OrderQueuePrinter.new(print_settings) - if !assigned_items.nil? - assigned_items.each do |order_item| - order_queue_printer.print_order_item(print_settings, oqs,order_item.order_id, order_item.order_items_id, print_status="" ) + # print when complete click + if print_settings = PrintSetting.where("unique_code REGEXP ?", "order.*item.*pdf").first + order_queue_printer = Printer::OrderQueuePrinter.new(print_settings) + if !assigned_items.nil? + assigned_items.each do |order_item| + order_queue_printer.print_order_item(print_settings, oqs,order_item.order_id, order_item.order_items_id, print_status="" ) + end end end else move_print_pdf(change_to,current_user,table_id,assigned_items,oqs) end - - assigned =AssignedOrderItem.where("order_id = '#{ order.order_id }'").pluck(:assigned_order_item_id) - AssignedOrderItem.where('assigned_order_item_id IN (?)', assigned).update_all(print_status: true) end def move_print_pdf(change_to,current_user,change_from,order_items,oqs) @@ -297,8 +183,8 @@ class OrderQueueStation < ApplicationRecord @type = (DiningFacility.find(change_to)).type @moved_by = current_user @date = DateTime.now - @shop = Shop.first - unique_code = "MoveTablePdf" + @shop = Shop.current_shop + unique_code = "MoveTablePdf" # pdf_no = PrintSetting.where(:unique_code => unique_code).count print_settings = PrintSetting.find_by_unique_code(unique_code) # printer_array = [] @@ -307,10 +193,10 @@ class OrderQueueStation < ApplicationRecord # for i in 0..pdf_no # if i != pdf_no # print_settings = printer_array[i] - printer = Printer::ReceiptPrinter.new(print_settings) + printer = Printer::ReceiptPrinter.new(print_settings) printer.print_move_table(print_settings,@to,@from ,@shop,@date,@type,@moved_by,order_items,oqs) - # end - # end + # end + # end end end end diff --git a/app/models/order_reservation.rb b/app/models/order_reservation.rb index 8de88ee2..60c33d2e 100644 --- a/app/models/order_reservation.rb +++ b/app/models/order_reservation.rb @@ -157,7 +157,7 @@ class OrderReservation < ApplicationRecord def self.update_doemal_payment(order,current_user,receipt_bill) if(Sale.exists?(order.sale_id)) saleObj = Sale.find(order.sale_id) - shop_details = Shop.first + shop_details = Shop.current_shop # rounding adjustment if shop_details.is_rounding_adj a = saleObj.grand_total % 25 # Modulus @@ -194,7 +194,7 @@ class OrderReservation < ApplicationRecord shift = ShiftSale.find(saleObj.shift_sale_id) cashier_terminal = CashierTerminal.find(shift.cashier_terminal_id) - shop_detail = Shop.first + shop_detail = Shop.current_shop order_reservation = OrderReservation.get_order_reservation_info(saleObj.sale_id) if !cashier_terminal.nil? # Calculate Food and Beverage Total @@ -400,7 +400,7 @@ class OrderReservation < ApplicationRecord end def self.check_new_order - shop = Shop.find_by_id(1) + shop = Shop.current_shop if !shop.shop_code.nil? shop_code = shop.shop_code else @@ -418,7 +418,7 @@ class OrderReservation < ApplicationRecord end def self.check_order_send_to_kitchen - shop = Shop.find_by_id(1) + shop = Shop.current_shop if !shop.shop_code.nil? shop_code = shop.shop_code else @@ -436,7 +436,7 @@ class OrderReservation < ApplicationRecord end def self.check_order_ready_to_delivery - shop = Shop.find_by_id(1) + shop = Shop.current_shop if !shop.shop_code.nil? shop_code = shop.shop_code else diff --git a/app/models/printer/order_queue_printer.rb b/app/models/printer/order_queue_printer.rb index ed14d884..20da8fcd 100755 --- a/app/models/printer/order_queue_printer.rb +++ b/app/models/printer/order_queue_printer.rb @@ -1,44 +1,21 @@ class Printer::OrderQueuePrinter < Printer::PrinterWorker - def print_order_item(print_settings,oqs, order_id, order_item_id, print_status, before_updated_qty="", options="") + def print_order_item(print_settings, oqs, order_id, order_item_id, print_status, before_updated_qty="", options="") # Must be one print if print_settings.print_copies == 0 print_settings.print_copies = 1 print_settings.save! end - order_item = print_query('order_item', order_item_id) #OrderItem.find_by_item_code(item_code) + order_item = print_query('order_item', order_item_id) #OrderItem.find_by_item_code(item_code) options = order_item[0].options - # filename = "tmp/order_item_#{order_id}_#{order_item_id}" + ".pdf" - - # pdf = OrderItemPdf.new(print_settings,order_item[0], print_status, options, oqs.use_alternate_name, before_updated_qty) - print_setting = PrintSetting.all # check for item not to show - pdf = '' # if order_item[0].price != 0 - if !print_setting.empty? - print_setting.each do |print_settings| - if print_settings.unique_code == 'OrderItemPdf' - pdf = OrderItemPdf.new(print_settings,order_item[0], print_status, options, oqs.use_alternate_name, before_updated_qty) - elsif print_settings.unique_code == 'OrderItemStarPdf' - pdf = OrderItemStarPdf.new(print_settings,order_item[0], print_status, options, oqs.use_alternate_name, before_updated_qty) - elsif print_settings.unique_code == 'OrderItemSlimPdf' - pdf = OrderItemSlimPdf.new(print_settings,order_item[0], print_status, options, oqs.use_alternate_name, before_updated_qty) - elsif print_settings.unique_code == 'OrderSetItemPdf' - pdf = OrderSetItemPdf.new(print_settings,order_item[0], print_status, options, oqs.use_alternate_name, before_updated_qty) - elsif print_settings.unique_code == 'OrderItemCustomisePdf' - pdf = OrderItemCustomisePdf.new(print_settings,order_item[0], print_status, options, oqs.use_alternate_name, before_updated_qty) - elsif print_settings.unique_code == 'OrderSetItemCustomisePdf' - pdf = OrderSetItemCustomisePdf.new(print_settings,order_item[0], print_status, options, oqs.use_alternate_name, before_updated_qty) - elsif print_settings.unique_code == 'OrderItemSlimCustomisePdf' - pdf = OrderItemSlimCustomisePdf.new(print_settings,order_item[0], print_status, options, oqs.use_alternate_name, before_updated_qty) - end - end - end + pdf = print_settings.unique_code.constantize.new(print_settings,order_item[0], print_status, options, oqs.use_alternate_name, before_updated_qty) # end - shop = Shop.first + shop = Shop.current_shop directory_name = 'public/orders_'+shop.shop_code Dir.mkdir(directory_name) unless File.exists?(directory_name) @@ -46,28 +23,18 @@ class Printer::OrderQueuePrinter < Printer::PrinterWorker pdf.render_file filename - if oqs.print_copy - #no print in cloud server - if ENV["SERVER_MODE"] != "cloud" - self.print(filename, oqs.printer_name) - end - #For print copy - # pdf.render_file filename.gsub(".","-copy.") - # self.print(filename.gsub(".","-copy."), oqs.printer_name) - else - print_settings.print_copies = 1 - print_settings.save! - #no print in cloud server - if ENV["SERVER_MODE"] != "cloud" - self.print(filename, oqs.printer_name) - end + if ENV["SERVER_MODE"] != "cloud" + self.print(filename, oqs.printer_name) end + #For print copy + # pdf.render_file filename.gsub(".","-copy.") + # self.print(filename.gsub(".","-copy."), oqs.printer_name) return filename, order_id, oqs.printer_name end # Query for per order - def print_order_summary(print_settings,oqs, order_id, order_items, print_status, before_updated_qty="", options="") + def print_order_summary(print_settings, oqs, order_id, order_items, print_status, before_updated_qty="", options="") #Use CUPS service #Generate PDF #Print @@ -77,111 +44,56 @@ class Printer::OrderQueuePrinter < Printer::PrinterWorker print_settings.save! end - print_setting = PrintSetting.all.order("id ASC") - order=print_query('order_summary', order_id) - - shop = Shop.first - directory_name = 'public/orders_'+shop.shop_code + shop = Shop.current_shop + directory_name = "public/orders_#{shop.shop_code}" Dir.mkdir(directory_name) unless File.exists?(directory_name) # For Print Per Item if oqs.cut_per_item - order_items.each do|odi| - odi_item=print_query('order_item', odi.order_items_id) + order_items.each do |odi| + odi_item = print_query('order_item', odi.order_items_id) - filename = directory_name + "/order_item_#{order_id}" + ".pdf" + filename = directory_name + "/order_item_#{order_id}.pdf" # filename = "tmp/order_item_#{order_id}" + ".pdf" # For Item Options - options = odi.options == "[]"? "" : odi.options + options = odi.options == "[]" ? "" : odi.options # check for item not to show #if odi.price != 0 - pdf = OrderItemPdf.new(print_settings,odi_item[0], print_status, options, oqs.use_alternate_name,before_updated_qty) - if !print_setting.empty? - print_setting.each do |print_settings| - if print_settings.unique_code == 'OrderItemPdf' - pdf = OrderItemPdf.new(print_settings,odi_item[0], print_status, options, oqs.use_alternate_name,before_updated_qty) - elsif print_settings.unique_code == 'OrderItemStarPdf' - pdf = OrderItemStarPdf.new(print_settings,order_item[0], print_status, options, oqs.use_alternate_name, before_updated_qty) - elsif print_settings.unique_code == 'OrderItemSlimPdf' - pdf = OrderItemSlimPdf.new(print_settings,odi_item[0], print_status, options, oqs.use_alternate_name,before_updated_qty) - elsif print_settings.unique_code == 'OrderSetItemPdf' - pdf = OrderSetItemPdf.new(print_settings,odi_item[0], print_status, options, oqs.use_alternate_name,before_updated_qty) - elsif print_settings.unique_code == 'OrderItemCustomisePdf' - pdf = OrderItemCustomisePdf.new(print_settings,odi_item[0], print_status, options, oqs.use_alternate_name,before_updated_qty) - elsif print_settings.unique_code == 'OrderSetItemCustomisePdf' - pdf = OrderSetItemCustomisePdf.new(print_settings,odi_item[0], print_status, options, oqs.use_alternate_name,before_updated_qty) - elsif print_settings.unique_code == 'OrderItemSlimCustomisePdf' - pdf = OrderItemSlimCustomisePdf.new(print_settings,odi_item[0], print_status, options, oqs.use_alternate_name,before_updated_qty) - end - end - end + pdf = print_settings.unique_code.constantize.new(print_settings, odi_item[0], print_status, options, oqs.use_alternate_name, before_updated_qty) - # pdf.render_file "tmp/order_item.pdf" - pdf.render_file filename - if oqs.print_copy - #no print in cloud server - if ENV["SERVER_MODE"] != "cloud" - self.print(filename, oqs.printer_name) - # self.print(filename.gsub(".","-copy."), oqs.printer_name) - end - else - print_settings.print_copies = 1 - print_settings.save! - #no print in cloud server - if ENV["SERVER_MODE"] != "cloud" - self.print(filename, oqs.printer_name) - end - end + # pdf.render_file "tmp/order_item.pdf" + pdf.render_file filename + #no print in cloud server + if ENV["SERVER_MODE"] != "cloud" + self.print(filename, oqs.printer_name) + # self.print(filename.gsub(".","-copy."), oqs.printer_name) + end #end end # For Print Order Summary else - filename = directory_name + "/order_summary_#{order_id}" + ".pdf" + order = print_query('order_summary', order_id) + + filename = directory_name + "/order_summary_#{order_id}.pdf" # filename = "tmp/order_summary_#{order_id}" + ".pdf" - pdf = OrderSummaryPdf.new(print_settings,order, print_status, order_items, oqs.use_alternate_name,before_updated_qty) - if !print_setting.empty? - print_setting.each do |print_settings| - if print_settings.unique_code == 'OrderSummaryPdf' - pdf = OrderSummaryPdf.new(print_settings,order, print_status, order_items, oqs.use_alternate_name,before_updated_qty) - elsif print_settings.unique_code == 'OrderSummarySlimPdf' - pdf = OrderSummarySlimPdf.new(print_settings,order, print_status, order_items, oqs.use_alternate_name,before_updated_qty) - elsif print_settings.unique_code == 'OrderSummarySetPdf' - pdf = OrderSummarySetPdf.new(print_settings,order, print_status, order_items, oqs.use_alternate_name,before_updated_qty) - elsif print_settings.unique_code == 'OrderSummaryCustomisePdf' - pdf = OrderSummaryCustomisePdf.new(print_settings,order, print_status, order_items, oqs.use_alternate_name,before_updated_qty) - elsif print_settings.unique_code == 'OrderSummarySetCustomisePdf' - pdf = OrderSummarySetCustomisePdf.new(print_settings,order, print_status, order_items, oqs.use_alternate_name,before_updated_qty) - elsif print_settings.unique_code == 'OrderSummarySlimCustomisePdf' - pdf = OrderSummarySlimCustomisePdf.new(print_settings,order, print_status, order_items, oqs.use_alternate_name,before_updated_qty) - end - end - end + pdf = print_settings.unique_code.constantize.new(print_settings, order, print_status, order_items, oqs.use_alternate_name, before_updated_qty) pdf.render_file filename - if oqs.print_copy - #no print in cloud server - if ENV["SERVER_MODE"] != "cloud" - self.print(filename, oqs.printer_name) - end - #For print copy - # pdf.render_file filename.gsub(".","-copy.") - # self.print(filename.gsub(".","-copy."), oqs.printer_name) - else - print_settings.print_copies = 1 - print_settings.save! - #no print in cloud server - if ENV["SERVER_MODE"] != "cloud" - self.print(filename, oqs.printer_name) - end + #no print in cloud server + if ENV["SERVER_MODE"] != "cloud" + self.print(filename, oqs.printer_name) end + #For print copy + # pdf.render_file filename.gsub(".","-copy.") + # self.print(filename.gsub(".","-copy."), oqs.printer_name) end return filename, order_id, oqs.printer_name end # Print for orders in booking - def print_booking_summary(print_settings,oqs, booking_id, print_status,before_updated_qty="") + def print_booking_summary(print_settings, oqs, booking_id, print_status,before_updated_qty="") # Must be one print if print_settings.print_copies == 0 print_settings.print_copies = 1 @@ -190,9 +102,9 @@ class Printer::OrderQueuePrinter < Printer::PrinterWorker print_setting = PrintSetting.all.order("id ASC") - order=print_query('booking_summary', booking_id) + order = print_query('booking_summary', booking_id) - shop = Shop.first + shop = Shop.current_shop directory_name = 'public/orders_'+shop.shop_code Dir.mkdir(directory_name) unless File.exists?(directory_name) @@ -206,72 +118,10 @@ class Printer::OrderQueuePrinter < Printer::PrinterWorker # check for item not to show #if odi.price != 0 - pdf = OrderItemPdf.new(print_settings,odi, print_status, options,oqs.use_alternate_name,before_updated_qty) - if !print_setting.empty? - print_setting.each do |print_settings| - if print_settings.unique_code == 'OrderItemPdf' - pdf = OrderItemPdf.new(print_settings,odi, print_status, options,oqs.use_alternate_name,before_updated_qty) - elsif print_settings.unique_code == 'OrderItemStarPdf' - pdf = OrderItemStarPdf.new(print_settings,odi, print_status, options,oqs.use_alternate_name,before_updated_qty) - elsif print_settings.unique_code == 'OrderItemSlimPdf' - pdf = OrderItemSlimPdf.new(print_settings,odi, print_status, options,oqs.use_alternate_name,before_updated_qty) - elsif print_settings.unique_code == 'OrderSetItemPdf' - pdf = OrderSetItemPdf.new(print_settings,odi, print_status, options,oqs.use_alternate_name,before_updated_qty) - elsif print_settings.unique_code == 'OrderItemCustomisePdf' - pdf = OrderItemCustomisePdf.new(print_settings,odi, print_status, options,oqs.use_alternate_name,before_updated_qty) - elsif print_settings.unique_code == 'OrderSetItemCustomisePdf' - pdf = OrderSetItemCustomisePdf.new(print_settings,odi, print_status, options,oqs.use_alternate_name,before_updated_qty) - elsif print_settings.unique_code == 'OrderItemSlimCustomisePdf' - pdf = OrderItemSlimCustomisePdf.new(print_settings,odi, print_status, options,oqs.use_alternate_name,before_updated_qty) - end - end - end - pdf.render_file filename + pdf = print_settings.unique_code.constantize.new(print_settings, odi, print_status, options, oqs.use_alternate_name, before_updated_qty) - if oqs.print_copy - #no print in cloud server - if ENV["SERVER_MODE"] != "cloud" - self.print(filename, oqs.printer_name) - end - #For print copy - # pdf.render_file filename.gsub(".","-copy.") - # self.print(filename.gsub(".","-copy."), oqs.printer_name) - else - print_settings.print_copies = 1 - print_settings.save! - #no print in cloud server - if ENV["SERVER_MODE"] != "cloud" - self.print(filename, oqs.printer_name) - end - end - #end - end - # For Print Order Summary - else - # filename = "tmp/booking_summary_#{booking_id}" + ".pdf" - filename = directory_name + "/booking_summary_#{booking_id}" + ".pdf" - pdf = OrderSummaryPdf.new(print_settings,order, print_status,oqs.use_alternate_name,before_updated_qty) + pdf.render_file filename - if !print_setting.empty? - print_setting.each do |print_settings| - if print_settings.unique_code == 'OrderSummaryPdf' - pdf = OrderSummaryPdf.new(print_settings,order, print_status,oqs.use_alternate_name,before_updated_qty) - elsif print_settings.unique_code == 'OrderSummarySlimPdf' - pdf = OrderSummarySlimPdf.new(print_settings,order, print_status,oqs.use_alternate_name,before_updated_qty) - elsif print_settings.unique_code == 'OrderSummarySetPdf' - pdf = OrderSummarySetPdf.new(print_settings,order, print_status,oqs.use_alternate_name,before_updated_qty) - elsif print_settings.unique_code == 'OrderSummaryCustomisePdf' - pdf = OrderSummaryCustomisePdf.new(print_settings,order, print_status,oqs.use_alternate_name,before_updated_qty) - elsif print_settings.unique_code == 'OrderSummarySetCustomisePdf' - pdf = OrderSummarySetCustomisePdf.new(print_settings,order, print_status,oqs.use_alternate_name,before_updated_qty) - elsif print_settings.unique_code == 'OrderSummarySlimCustomisePdf' - pdf = OrderSummarySlimCustomisePdf.new(print_settings,order, print_status,oqs.use_alternate_name,before_updated_qty) - end - end - end - - pdf.render_file filename - if oqs.print_copy #no print in cloud server if ENV["SERVER_MODE"] != "cloud" self.print(filename, oqs.printer_name) @@ -279,50 +129,45 @@ class Printer::OrderQueuePrinter < Printer::PrinterWorker #For print copy # pdf.render_file filename.gsub(".","-copy.") # self.print(filename.gsub(".","-copy."), oqs.printer_name) - else - print_settings.print_copies = 1 - print_settings.save! - #no print in cloud server - if ENV["SERVER_MODE"] != "cloud" - self.print(filename, oqs.printer_name) - end + #end end + # For Print Order Summary + else + # filename = "tmp/booking_summary_#{booking_id}" + ".pdf" + filename = directory_name + "/booking_summary_#{booking_id}" + ".pdf" + pdf = print_settings.unique_code.constantize.new(print_settings, order, print_status, oqs.use_alternate_name, before_updated_qty) + + pdf.render_file filename + #no print in cloud server + if ENV["SERVER_MODE"] != "cloud" + self.print(filename, oqs.printer_name) + end + #For print copy + # pdf.render_file filename.gsub(".","-copy.") + # self.print(filename.gsub(".","-copy."), oqs.printer_name) end return filename, booking_id, oqs.printer_name end # Query for OQS with status def print_query(type, id) + query = OrderItem.select("order_items.order_id, order_items.item_code, order_items.item_name, order_items.qty, order_items.price, order_items.options, order_items.item_order_by as order_by, order_items.created_at as order_at, order_items.set_menu_items, cus.name as customer, df.type, df.name as dining,item.alt_name as alt_name") + .joins("left join orders ON orders.order_id = order_items.order_id") + .joins("left join booking_orders AS bo ON bo.order_id=order_items.order_id") + .joins("left join bookings AS b ON b.booking_id = bo.booking_id") + .joins("left join dining_facilities AS df ON df.id = b.dining_facility_id") + .joins("left join customers as cus ON cus.customer_id = orders.customer_id") + .joins("left join menu_items as item ON item.item_code = order_items.item_code") + if type == "order_item" - OrderItem.select("order_items.order_id, order_items.item_code, order_items.item_name, order_items.qty, order_items.price, order_items.options, order_items.item_order_by as order_by, order_items.created_at as order_at, order_items.set_menu_items, cus.name as customer, df.type, df.name as dining,item.alt_name as alt_name") - .joins("left join orders ON orders.order_id = order_items.order_id - left join booking_orders AS bo ON bo.order_id=order_items.order_id - left join bookings AS b ON b.booking_id = bo.booking_id - left join dining_facilities AS df ON df.id = b.dining_facility_id - left join customers as cus ON cus.customer_id = orders.customer_id - left join menu_items as item ON item.item_code = order_items.item_code") - .where("order_items.order_items_id = '#{ id }'") + query.where("order_items.order_items_id = ?", id) .group("order_items.item_code") elsif type == "order_summary" - OrderItem.select("order_items.order_id, order_items.item_code, order_items.item_name, order_items.qty, order_items.price, order_items.options, order_items.item_order_by as order_by, order_items.created_at as order_at, order_items.set_menu_items, cus.name as customer, df.type, df.name as dining,item.alt_name as alt_name") - .joins("left join orders ON orders.order_id = order_items.order_id - left join booking_orders AS bo ON bo.order_id=order_items.order_id - left join bookings AS b ON b.booking_id = bo.booking_id - left join dining_facilities AS df ON df.id = b.dining_facility_id - left join customers as cus ON cus.customer_id = orders.customer_id - left join menu_items as item ON item.item_code = order_items.item_code") - .where("orders.order_id = '#{ id }'") + query.where("orders.order_id = ?", id) .group("order_items.order_items_id") else # order summary for booking - OrderItem.select("order_items.order_id, order_items.item_code, order_items.item_name, order_items.qty, order_items.price, order_items.options, order_items.item_order_by as order_by, order_items.created_at as order_at, order_items.set_menu_items, cus.name as customer, df.type, df.name as dining,item.alt_name as alt_name") - .joins("left join orders ON orders.order_id = order_items.order_id - left join booking_orders AS bo ON bo.order_id=order_items.order_id - left join bookings AS b ON b.booking_id = bo.booking_id - left join dining_facilities AS df ON df.id = b.dining_facility_id - left join customers as cus ON cus.customer_id = orders.customer_id - left join menu_items as item ON item.item_code = order_items.item_code") - .where("b.booking_id = '#{ id }'") + query.where("b.booking_id = ?", id) end end diff --git a/app/models/printer/printer_worker.rb b/app/models/printer/printer_worker.rb index e0d4fc85..d30af42d 100755 --- a/app/models/printer/printer_worker.rb +++ b/app/models/printer/printer_worker.rb @@ -37,14 +37,15 @@ class Printer::PrinterWorker Cups.default_printer end - def print(file_path,printer_destination = nil ) + def self.printer_exists?(printer) + Cups.show_destinations.include? printer + end + + def print(file_path, printer_destination = nil ) if printer_destination.nil? printer_destination = self.printer_destination end - puts printer_destination - puts '........Printer Destination..........' - copy = self.print_copies #Print only when printer information is not null if !self.printer_destination.nil? diff --git a/app/models/printer/receipt_printer.rb b/app/models/printer/receipt_printer.rb index f7b35a5a..4d96112f 100755 --- a/app/models/printer/receipt_printer.rb +++ b/app/models/printer/receipt_printer.rb @@ -4,26 +4,9 @@ class Printer::ReceiptPrinter < Printer::PrinterWorker #Use CUPS service #Generate PDF #Print - printer = PrintSetting.all - pdf = OrderItemPdf.new + printer = PrintSetting.where("unique_code REGEXP ?", "order.*item.*pdf").first + pdf = printer.unique_code.constantize.new - if !printer.empty? - printer.each do |printer_setting| - if printer_setting.unique_code == 'OrderItemPdf' - pdf = OrderItemPdf.new - elsif printer_setting.unique_code == 'OrderItemSlimPdf' - pdf = OrderItemSlimPdf.new - elsif printer_setting.unique_code == 'OrderSetItemPdf' - pdf = OrderSetItemPdf.new - elsif printer_setting.unique_code == 'OrderItemCustomisePdf' - pdf = OrderItemCustomisePdf.new - elsif printer_setting.unique_code == 'OrderSetItemCustomisePdf' - pdf = OrderSetItemCustomisePdf.new - elsif printer_setting.unique_code == 'OrderItemSlimCustomisePdf' - pdf = OrderItemSlimCustomisePdf.new - end - end - end pdf.render_file "tmp/order_item_queue_#{order_id}_#{order_item_id}" + ".pdf" #no print in cloud server if ENV["SERVER_MODE"] != "cloud" @@ -36,26 +19,9 @@ class Printer::ReceiptPrinter < Printer::PrinterWorker #Generate PDF #Print filename = "tmp/order_summary_#{booking_id}" + ".pdf" - printer = PrintSetting.all - pdf = OrderSummaryPdf.new + printer = PrintSetting.where("unique_code REGEXP ?", "order.*summary.*pdf").first + pdf = printer.unique_code.constantize.new - if !printer.empty? - printer.each do |printer_setting| - if printer_setting.unique_code == 'OrderSummaryPdf' - pdf = OrderSummaryPdf.new - elsif printer_setting.unique_code == 'OrderSummarySlimPdf' - pdf = OrderSummarySlimPdf.new - elsif printer_setting.unique_code == 'OrderSummarySetPdf' - pdf = OrderSummarySetPdf.new - elsif printer_setting.unique_code == 'OrderSummaryCustomisePdf' - pdf = OrderSummaryCustomisePdf.new - elsif printer_setting.unique_code == 'OrderSummarySetCustomisePdf' - pdf = OrderSummarySetCustomisePdf.new - elsif printer_setting.unique_code == 'OrderSummarySlimCustomisePdf' - pdf = OrderSummarySlimCustomisePdf.new - end - end - end pdf.render_file filename #no print in cloud server if ENV["SERVER_MODE"] != "cloud" @@ -67,26 +33,10 @@ class Printer::ReceiptPrinter < Printer::PrinterWorker #Use CUPS service #Generate PDF #Print - printer = PrintSetting.all + printer = PrintSetting.where("unique_code REGEXP ?", "order.*summary.*pdf").first filename = "tmp/order_summary_#{booking_id}" + ".pdf" - pdf = OrderSummaryPdf.new - if !printer.empty? - printer.each do |printer_setting| - if printer_setting.unique_code == 'OrderSummaryPdf' - pdf = OrderSummaryPdf.new - elsif printer_setting.unique_code == 'OrderSummarySlimPdf' - pdf = OrderSummarySlimPdf.new - elsif printer_setting.unique_code == 'OrderSummarySetPdf' - pdf = OrderSummarySetPdf.new - elsif printer_setting.unique_code == 'OrderSummaryCustomisePdf' - pdf = OrderSummaryCustomisePdf.new - elsif printer_setting.unique_code == 'OrderSummarySetCustomisePdf' - pdf = OrderSummarySetCustomisePdf.new - elsif printer_setting.unique_code == 'OrderSummarySlimCustomisePdf' - pdf = OrderSummarySlimCustomisePdf.new - end - end - end + pdf = printer.unique_code.constantize.new + pdf.render_file filename #no print in cloud server if ENV["SERVER_MODE"] != "cloud" @@ -98,26 +48,10 @@ class Printer::ReceiptPrinter < Printer::PrinterWorker #Use CUPS service #Generate PDF #Print - printer = PrintSetting.all + printer = PrintSetting.where("unique_code REGEXP ?", "order.*summary.*pdf").first filename = "tmp/order_summary_#{booking_id}" + ".pdf" - pdf = OrderSummaryPdf.new - if !printer.empty? - printer.each do |printer_setting| - if printer_setting.unique_code == 'OrderSummaryPdf' - pdf = OrderSummaryPdf.new - elsif printer_setting.unique_code == 'OrderSummarySlimPdf' - pdf = OrderSummarySlimPdf.new - elsif printer_setting.unique_code == 'OrderSummarySetPdf' - pdf = OrderSummarySetPdf.new - elsif printer_setting.unique_code == 'OrderSummaryCustomisePdf' - pdf = OrderSummaryCustomisePdf.new - elsif printer_setting.unique_code == 'OrderSummarySetCustomisePdf' - pdf = OrderSummarySetCustomisePdf.new - elsif printer_setting.unique_code == 'OrderSummarySlimCustomisePdf' - pdf = OrderSummarySlimCustomisePdf.new - end - end - end + pdf = printer.unique_code.constantize.new + pdf.render_file filename #no print in cloud server if ENV["SERVER_MODE"] != "cloud" @@ -129,26 +63,10 @@ class Printer::ReceiptPrinter < Printer::PrinterWorker #Use CUPS service #Generate PDF #Print - printer = PrintSetting.all + printer = PrintSetting.where("unique_code REGEXP ?", "order.*summary.*pdf").first filename = "tmp/order_summary_#{booking_id}" + ".pdf" - pdf = OrderSummaryPdf.new - if !printer.empty? - printer.each do |printer_setting| - if printer_setting.unique_code == 'OrderSummaryPdf' - pdf = OrderSummaryPdf.new - elsif printer_setting.unique_code == 'OrderSummarySlimPdf' - pdf = OrderSummarySlimPdf.new - elsif printer_setting.unique_code == 'OrderSummarySetPdf' - pdf = OrderSummarySetPdf.new - elsif printer_setting.unique_code == 'OrderSummaryCustomisePdf' - pdf = OrderSummaryCustomisePdf.new - elsif printer_setting.unique_code == 'OrderSummarySetCustomisePdf' - pdf = OrderSummarySetCustomisePdf.new - elsif printer_setting.unique_code == 'OrderSummarySlimCustomisePdf' - pdf = OrderSummarySlimCustomisePdf.new - end - end - end + pdf = printer.unique_code.constantize.new + pdf.render_file filename #no print in cloud server if ENV["SERVER_MODE"] != "cloud" @@ -160,26 +78,10 @@ class Printer::ReceiptPrinter < Printer::PrinterWorker #Use CUPS service #Generate PDF #Print - printer = PrintSetting.all + printer = PrintSetting.where("unique_code REGEXP ?", "order.*summary.*pdf").first filename = "tmp/order_summary_#{booking_id}" + ".pdf" - pdf = OrderSummaryPdf.new - if !printer.empty? - printer.each do |printer_setting| - if printer_setting.unique_code == 'OrderSummaryPdf' - pdf = OrderSummaryPdf.new - elsif printer_setting.unique_code == 'OrderSummarySlimPdf' - pdf = OrderSummarySlimPdf.new - elsif printer_setting.unique_code == 'OrderSummarySetPdf' - pdf = OrderSummarySetPdf.new - elsif printer_setting.unique_code == 'OrderSummaryCustomisePdf' - pdf = OrderSummaryCustomisePdf.new - elsif printer_setting.unique_code == 'OrderSummarySetCustomisePdf' - pdf = OrderSummarySetCustomisePdf.new - elsif printer_setting.unique_code == 'OrderSummarySlimCustomisePdf' - pdf = OrderSummarySlimCustomisePdf.new - end - end - end + pdf = printer.unique_code.constantize.new + pdf.render_file filename #no print in cloud server if ENV["SERVER_MODE"] != "cloud" @@ -192,31 +94,12 @@ class Printer::ReceiptPrinter < Printer::PrinterWorker #Use CUPS service #Generate PDF #Print - if !printer_settings.nil? - if !printer_settings.unique_code.strip.downcase.include? ("receiptbillorder") - pdf = ReceiptBillPdf.new(printer_settings, kbz_pay_status, qr_code, sale_items, sale_data, customer_name, item_price_by_accounts, discount_price_by_accounts, member_info,rebate_amount,shop_details,printed_status,balance,card_data,other_amount,latest_order_no,card_balance_amount) - settings = PrintSetting.all - if !settings.nil? - settings.each do |setting| - if setting.unique_code == 'ReceiptBillPdf' - pdf = ReceiptBillPdf.new(printer_settings, kbz_pay_status, qr_code, sale_items, sale_data, customer_name, item_price_by_accounts, discount_price_by_accounts, member_info,rebate_amount,shop_details,printed_status,balance,card_data,other_amount,latest_order_no,card_balance_amount) - elsif setting.unique_code == 'ReceiptBillStarPdf' - pdf = ReceiptBillStarPdf.new(printer_settings, kbz_pay_status, qr_code, sale_items, sale_data, customer_name, item_price_by_accounts, discount_price_by_accounts, member_info,rebate_amount,shop_details,printed_status,balance,card_data,other_amount,latest_order_no,card_balance_amount) - end - end - end - - receipt_bill_a5_pdf = Lookup.collection_of("print_settings") #print_settings with name:ReceiptBillA5Pdf - if !receipt_bill_a5_pdf.empty? - receipt_bill_a5_pdf.each do |receipt_bilA5| - if receipt_bilA5[0] == 'ReceiptBillA5Pdf' - if receipt_bilA5[1] == '1' - pdf = ReceiptBillA5Pdf.new(printer_settings, sale_items, sale_data, customer_name, item_price_by_accounts, discount_price_by_accounts, member_info,rebate_amount,shop_details,printed_status,balance,card_data,other_amount,latest_order_no,card_balance_amount) - # else - # pdf = ReceiptBillPdf.new(printer_settings, sale_items, sale_data, customer_name, item_price_by_accounts, discount_price_by_accounts, member_info,rebate_amount,shop_details,printed_status,balance,card_data,other_amount,latest_order_no,card_balance_amount) - end - end - end + if printer_settings + if !printer_settings.unique_code.match?(/receiptbillorder/i) + if Lookup.collection_of("print_settings").any? { |x| x == ["ReceiptBillA5Pdf", "1"] } #print_settings with name:ReceiptBillA5Pdf + pdf = ReceiptBillA5Pdf.new(printer_settings, sale_items, sale_data, customer_name, item_price_by_accounts, discount_price_by_accounts, member_info,rebate_amount,shop_details,printed_status,balance,card_data,other_amount,latest_order_no,card_balance_amount) + else + pdf = PrintSetting.where("unique_code REGEXP ?", "receipt.*bill.*pdf").first.unique_code.constantize.new(printer_settings, kbz_pay_status, qr_code, sale_items, sale_data, customer_name, item_price_by_accounts, discount_price_by_accounts, member_info,rebate_amount,shop_details,printed_status,balance,card_data,other_amount,latest_order_no,card_balance_amount) end else #doemal online order pdf template diff --git a/app/models/product.rb b/app/models/product.rb index 3256fe17..69037e2a 100755 --- a/app/models/product.rb +++ b/app/models/product.rb @@ -5,29 +5,23 @@ class Product < ApplicationRecord mount_uploader :image_path, ProductImageUploader def self.search_by_product_code(item_code) - account = Account.find_by_title('Product') - if !account.nil? - account_id = account.id - else - account_id = 1 - end - - menu_item_hash = Hash.new - mt_instance = Product.find_by_item_code(item_code) - if (!mt_instance.nil?) - menu_item_hash[:type] = 'Product' - menu_item_hash[:account_id] = account_id - menu_item_hash[:item_code] = mt_instance.item_code - menu_item_hash[:item_instance_code] = mt_instance.item_code - menu_item_hash[:name] = mt_instance.name.to_s - menu_item_hash[:alt_name] = mt_instance.alt_name.to_s - menu_item_hash[:price] = mt_instance.unit_price - menu_item_hash[:promotion_price] = 0 - menu_item_hash[:is_on_promotion] = 0 - menu_item_hash[:is_available] = 0 - menu_item_hash[:taxable] = mt_instance.taxable - - return menu_item_hash - end -end + Product.joins("JOIN accounts ON accounts.title = 'Product'") + .where(item_code: item_code) + .pluck("accounts.id AS account_id", :item_code, :name, :alt_name, :unit_price, :taxable) + .map { |account_id, item_code, item_name, item_alt_name, price, taxable| + { + type: 'Product', + account_id: account_id, + item_code: item_code, + item_instance_code: item_code, + name: "#{item_name}", + alt_name: "#{item_name}", + price: price, + promotion_price: 0, + is_on_promotion: 0, + is_available: 0, + taxable: taxable + } + } + end end diff --git a/app/models/room.rb b/app/models/room.rb index 87f232e9..63c548ec 100755 --- a/app/models/room.rb +++ b/app/models/room.rb @@ -1,4 +1,3 @@ class Room < DiningFacility - has_many :bookings, :foreign_key => 'dining_facility_id' end diff --git a/app/models/sale.rb b/app/models/sale.rb index 85a81950..dd20fa2c 100644 --- a/app/models/sale.rb +++ b/app/models/sale.rb @@ -5,21 +5,25 @@ class Sale < ApplicationRecord #primary key - need to be unique generated for multiple shops before_create :generate_custom_id before_create :generate_receipt_no + belongs_to :cashier, foreign_key: "cashier_id", class_name: "Employee" belongs_to :customer, :optional => true belongs_to :shift_sale - has_one :survey, foreign_key: "receipt_no" + has_one :current_shift_by_cashier, through: :cashier, source: :current_shift + has_one :cashier_terminal_by_shift_sale, through: :shift_sale, source: :cashier_terminal + has_one :survey, foreign_key: "receipt_no" has_many :sale_audits has_many :sale_items has_many :sale_discount_items has_many :sale_discounts has_many :sale_taxes has_many :sale_payments + has_many :payments_for_credits, through: :sale_audits has_many :sale_orders - has_many :sale_payments_for_credits, through: :sale_audits has_many :orders, through: :sale_orders has_many :order_items, through: :sale_orders has_many :bookings + has_one :booking has_many :product_commissions before_validation :round_to_precision @@ -30,7 +34,7 @@ class Sale < ApplicationRecord scope :paid, -> { where(payment_status: 'paid')} scope :completed, -> { where(sale_status: 'completed') } scope :receipt_date_between, -> (from, to) { where(receipt_date: from..to) } - scope :along_with_sale_payments_except_void_between, -> (from, to) { joins(sanitize_sql_array(["LEFT JOIN sale_payments on sales.sale_status != 'void' AND sale_payments.sale_id = sales.sale_id AND sale_payments.created_at BETWEEN ? and ?", from, to])) } + scope :along_with_sale_payments_except_void_between, -> (from, to) { joins(sanitize_sql_array(["LEFT JOIN sale_payments ON sales.sale_status != 'void' AND sale_payments.sale_id = sales.sale_id AND sale_payments.created_at BETWEEN ? and ?", from, to])) } 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 @@ -79,188 +83,114 @@ class Sale < ApplicationRecord Rails.logger.debug '........ Sale data sync completed .......' end end - def self.generate_invoice_from_booking(booking, requested_by, cashier, order_source = nil, current_checkin_induties_count) - if booking - Rails.logger.debug "Booking -> " + booking.id.to_s - Rails.logger.debug "Booking -> Booking Order Count -> " + booking.booking_orders.count.to_s - #get all order attached to this booking and combine into 1 invoice - unless sale = booking.sale - sale = booking.build_sale( + def self.generate_invoice_from_booking(booking, requested_by, cashier, order_source = nil, in_duties_count = 0) + Sale.transaction do + if booking + current = Time.now + #get all order attached to this booking and combine into 1 invoice + sale = booking.sale || booking.build_sale( { tax_type: "execulive" # Default Tax - Values } ) - end - booking.booking_orders.each do |order| - sale.generate_invoice_from_order(order.order_id, booking, requested_by, cashier, order_source) - # saleObj = Sale.find(sale_id) - # order = booking.booking_orders.take.order - # link_order_sale(order.order_id) - end - # InventoryJob.perform_now(self.id) - # InventoryDefinition.calculate_product_count(saleObj) - - # dining charges - charges = DiningCharge.where('dining_facility_id=?', booking.dining_facility_id).take - if !charges.nil? - block_count, diningprice = DiningCharge.amount_calculate(charges, booking.checkin_at, booking.checkout_at) - if charges.charge_type =='hr' - dining_time = booking.checkin_at.strftime('%H:%M %p').to_s + " - " + booking.checkout_at.strftime('%H:%M %p').to_s - else - dining_time = booking.checkin_at.strftime('%B %d, %H:%M %p').to_s + " - " + booking.checkout_at.strftime('%B %d, %H:%M %p').to_s - end - later_time = booking.checkout_at - early_time = booking.checkin_at - distance_in_minutes = ((later_time - early_time)/60.0).round - basic_pay_amount = 0 - name = "" - if current_checkin_induties_count != "0" - basic_pay = Commission.where('commission_type=?','Basic Pay') - basic_pay.each do |pay| - basic_pay_amount = pay.amount - name = pay.name - end - induties_pay_amount = (current_checkin_induties_count.to_i * (distance_in_minutes / 60.0).to_f * basic_pay_amount).to_i - sale.create_saleitem_indutycharges(charges, current_checkin_induties_count.to_i, induties_pay_amount, booking.dining_facility.name, dining_time, order_source, basic_pay_amount) - end - sale.create_saleitem_diningcharges(charges, block_count, diningprice, booking.dining_facility.name, dining_time, order_source) - end - - return sale - end - end - - def generate_invoice_from_order(order_id, booking, requested_by, cashier = nil, order_source = nil) - taxable = true - - order = Order.find(order_id) - - # current cashier login - open_cashier = Employee.where("role = 'cashier' AND token_session <> ''") - current_shift = ShiftSale.current_shift - # shift with terminal zone - - # set cashier - if order_source.present? && order_source.downcase == "emenu" - if !booking.dining_facility_id.nil? - table = DiningFacility.find(booking.dining_facility_id) - cashier_zone = CashierTerminalByZone.find_by_zone_id(table.zone_id) - shift = ShiftSale.where("shift_started_at is not null and shift_closed_at is null and cashier_terminal_id = #{cashier_zone.cashier_terminal_id}").first - #for multiple zone with terminal - if shift.nil? - multiple_zone = CashierTerminalByZone.where("zone_id = #{table.zone_id}") - multiple_zone.each do |zone| - shift = ShiftSale.where("shift_started_at is not null and shift_closed_at is null and cashier_terminal_id = #{zone.cashier_terminal_id}").first - if !shift.nil? then - break - end + if cashier.role == 'cashier' + sale.cashier = cashier + sale.shift_sale = cashier.current_shift + elsif booking.dining_facility + if sale.shift_sale = booking.current_shift_by_dining_facility + sale.cashier = sale.shift_sale.employee end end - end - else - shift = ShiftSale.current_open_shift(cashier.id) - end - # set cashier - if shift != nil #if current login employee open shift - self.cashier_id = cashier.id - self.cashier_name = cashier.name - self.shift_sale_id = shift.id - else - if open_cashier.count>0 # if we have two open cashier - # table and terminal in multiple shift - self.cashier_id = open_cashier[0].id - self.cashier_name = open_cashier[0].name - shift_id = ShiftSale.current_open_shift(open_cashier[0].id) - if shift_id - self.shift_sale_id = shift_id.id + + if sale.shift_sale.nil? + if sale.cashier = Employee.where(role: 'cashier').where.not(token_session: [nil, '']).first + sale.shift_sale = sale.current_shift_by_cashier else - self.shift_sale_id = current_shift.id + sale.shift_sale = ShiftSale.current_shift + sale.cashier = sale.shift_sale.employee end - else - self.cashier_id = current_shift.employee_id - self.cashier_name = Employee.find(current_shift.employee_id).name - self.shift_sale_id = current_shift.id - end - end - - - # set waiter - self.requested_by = requested_by.name - - self.requested_at = DateTime.now.utc.getlocal - - Rails.logger.debug "Order -> #{order.id} | order_status -> #{order.status}" - if order - self.customer_id = order.customer_id - Rails.logger.debug "Order -> #{order.id} | Items Count -> #{order.order_items.count}" - - order.order_items.each do |item| - self.add_item(item) - if !item.set_menu_items.nil? - self.add_sub_item(item.set_menu_items) end + + sale.cashier_name = sale.cashier.name + sale.requested_by = requested_by.name + sale.requested_at = current + + sale.sale_items << booking.order_items.to_sale_items + + if booking.dining_facility.present? && dining_charge = booking.dining_facility.dining_charge + block_count, dining_price = DiningCharge.amount_calculate(dining_charge, booking.checkin_at, booking.checkout_at) + format = "%I:%M %p" if dining_charge.charge_type == "hr" + format ||= "%B %d, %I:%M %p" + dining_time = "#{booking.checkin_at.strftime(format)} - #{booking.checkout_at.strftime(format)}" + + sale.sale_items.build({ + menu_category_name: "Dining Charge", + menu_category_code: "DiningCharge", + product_name: "#{booking.dining_facility.name} ( #{dining_time} )", + product_code: dining_charge.item_code, + product_alt_name: '-', + account_id: 0, + is_taxable: dining_charge.taxable, + qty: block_count, + unit_price: dining_charge.unit_price, + price: dining_price, + taxable_price: dining_price, + }) + + if in_duties_count.to_i > 0 + basic_pay = Commission.find_by(commission_type: 'Basic Pay') + in_duties_pay_amount = (in_duties_count.to_i * ((booking.checkout_at - booking.checkin_at) / 1.hours) * basic_pay_amount).to_i + + sale.sale_items.build({ + menu_category_name: "Induty Charge", + menu_category_code: "IndutyCharge", + product_name: "#{basic_pay.name} ( #{dining_time} )", + product_code: "", + product_alt_name: '-', + account_id: 0, + is_taxable: dining_charge.taxable, + qty: in_duties_count, + unit_price: basic_pay.amount, + price: in_duties_pay_amount, + taxable_price: in_duties_pay_amount, + }) + end + end + + sale.orders << booking.orders + sale.customer_id = booking.orders[0].customer_id + + sale.compute(booking.orders[0].source) + + booking.orders.update_all(status: "billed") + booking.order_items.update_all(order_item_status: "billed") + + booking.checkout_at = current unless booking.checkout_at && booking.checkout_at > current + booking.checkout_by = requested_by.name + + booking.save + return sale end - self.orders << order end - - #compute sales summary - if order_source.nil? - order_source = order.source - end - self.compute(order_source) - - #Update the order items that is billed - order.update_items_status_to_billed(nil) - order.status = "billed" - order.save - - if !booking.checkout_at.nil? - if booking.checkout_at.utc < Time.now.utc - booking.checkout_at = Time.now.utc.getlocal - end - else - booking.checkout_at = Time.now.utc.getlocal - end - - booking.checkout_by = requested_by.name - booking.save - - # InventoryJob.perform_now(self.id) - # saleObj = Sale.find(self.id) - # InventoryDefinition.calculate_product_count(saleObj) - - return self end #fOR Quick Service pay and create - def self.request_bill(order,current_user,current_login_employee) + def self.request_bill(order, current_user, current_login_employee) if !ShiftSale.current_shift.nil? order_id = order.order_id # order_id - bk_order = BookingOrder.find_by_order_id(order_id) - check_booking = Booking.find_by_booking_id(bk_order.booking_id) + booking = order.booking - if @sale_data = check_booking.sale - # Create Sale if it doesn't exist - # puts "current_login_employee" - # puts current_login_employee.name - @sale_items = SaleItem.where("sale_id=?",@sale_id) - elsif @sale_data = Sale.generate_invoice_from_booking(check_booking,current_login_employee,current_user,order.source) - @sale_items = SaleItem.where("sale_id=?",@sale_data.sale_id) + if booking.sale.nil? + sale_data = Sale.generate_invoice_from_booking(booking, current_login_employee, current_user, order.source) + # Promotion Activation + Promotion.promo_activate(sale_data) end - # Bind shift sale id to sale - # @sale_data.shift_sale_id = shift.id - # @sale_data.save - - # Promotion Activation - Promotion.promo_activate(@sale_data) - @status = true - return @status, @sale_data + return true, sale_data else - @status = false - @message = "No Current Open Shift for This Employee" + return false, "No Current Open Shift for This Employee" end end #This is when spilt bill is request - then we cannot link order to invoice @@ -440,7 +370,7 @@ class Sale < ApplicationRecord #compute - invoice total def compute_by_sale_items(total_discount, discount_type=nil, order_source=nil, tax_type=nil, type=nil) - shop = Shop.first + shop = Shop.current_shop #Computation Fields subtotal_price = 0 @@ -507,7 +437,7 @@ class Sale < ApplicationRecord # Tax Re-Calculte def compute_tax(total_taxable, total_discount = 0, order_source = nil, tax_type=nil) - shop = Shop.first + shop = Shop.current_shop #if tax is not apply create new record # SaleTax.where("sale_id='#{sale.sale_id}'").find_each do |existing_tax| @@ -527,6 +457,19 @@ class Sale < ApplicationRecord end tax_profiles = unique_tax_profiles(order_source, self.customer_id) + if tax_type.nil? + if tax_profiles.count == 2 + tax_type = "all" + elsif tax_profiles.count == 1 + if tax_profiles.name.downcase == "service charges" + tax_type = "Service Charges" + else + tax_type = "Commercial Tax" + end + elsif tax_profiles.count < 1 + tax_type = "no_tax" + end + end # #Creat new tax records if self.payment_status != 'foc' && tax_type.to_s == "all" @@ -627,7 +570,7 @@ class Sale < ApplicationRecord # Tax Calculate def apply_tax(total_taxable, order_source = nil, tax_type = nil) - shop = Shop.first + shop = Shop.current_shop #if tax is not apply create new record # SaleTax.where("sale_id='#{self.sale_id}'").find_each do |existing_tax| @@ -645,7 +588,7 @@ class Sale < ApplicationRecord order_source = "cashier" end - # tax_data = TaxProfile.unscoped.where("group_type=?",order_source).pluck(:id) + # tax_data = TaxProfile.unscope(:order).where("group_type=?",order_source).pluck(:id) # customer = Customer.find(self.customer_id).tax_profiles tax_profiles = unique_tax_profiles(order_source, self.customer_id) @@ -684,14 +627,6 @@ class Sale < ApplicationRecord self.total_tax = total_tax_amount end - def product_get_unit_price(item_code) - menu_item_hash =MenuItem.search_by_item_code(item_code) - if (menu_instance_code) - return menu_ item_hash[:item_instance_code], menu_item_hash[:price] - end - return nil,nil - end - def link_order_sale(order_id) #create if it doesn't exist saleOrder = SaleOrder.where("sale_id=? and order_id=?", self.id, order_id).take @@ -710,7 +645,7 @@ class Sale < ApplicationRecord end def adjust_rounding - shop_details = Shop.first + shop_details = Shop.current_shop # rounding adjustment if shop_details.is_rounding_adj new_total = Sale.get_rounding_adjustment(self.grand_total) @@ -726,7 +661,7 @@ class Sale < ApplicationRecord #Generate new Receipt No when it is not assigned def generate_receipt_no #shop_code and client_code - shop_details = Shop.first + shop_details = Shop.current_shop #Date-Shift- if self.receipt_no.nil? prefix = DateTime.now().utc @@ -1121,7 +1056,7 @@ def self.get_by_shift_items(shift_sale_range, shift, from, to, status,type,accou return query,other_charges, product, discount_query , total_cash_amount , total_card_amount , total_credit_amount , total_foc_amount , total_grand_total , change_amount end -def self.get_staff_meal_items(shift_sale_range, shift, from, to, status,account_type,customer_id) +def self.get_staff_meal_items(shift_sale_range, shift, from, to, status, account_type, customer_id) # date_type_selection = get_sql_function_for_report_type(report_type) if account_type.blank? account_type = '' @@ -1133,8 +1068,6 @@ def self.get_staff_meal_items(shift_sale_range, shift, from, to, status,account_ customer_id = customer_id.to_s customer_id[0] = "" customer_id = customer_id.chomp("]") - else - customer_id = '"CUS-000000000000"' end query = self.get_staff_meal_query() @@ -1239,7 +1172,7 @@ end #product sale report query def self.get_menu_item_query(order_by) - query = MenuItem.unscoped.select("acc.id as account_id, + query = MenuItem.unscope(:order).select("acc.id as account_id, acc.title as account_name, mii.item_instance_code as item_code, " + "(CASE WHEN si.qty IS NOT NULL THEN SUM(si.qty) ELSE 0 END) as total_item," + @@ -1291,7 +1224,7 @@ def self.get_shift_sales_by_receipt_no_detail(shift_sale_range,shift,from,to,pay .includes(:bookings => :dining_facility) .select("sales.*, SUM(sale_payments.payment_amount) AS payments_for_credits_amount") .joins(:bookings) - .left_joins(:sale_payments_for_credits) + .left_joins(:payments_for_credits) .completed .where.not(total_amount: 0) .group(:sale_id) @@ -2025,7 +1958,7 @@ end query = query.joins("join sale_orders as sale_orders on sale_orders.sale_id = sales.sale_id") .joins("join orders as orders on orders.order_id = sale_orders.order_id") query = query.where("sales.sale_status != 'new' AND orders.status = 'billed' #{type}") - query = query.where("DATE_FORMAT(sales.receipt_date,'%Y-%m-%d') = ? ",DateTime.now.strftime('%Y-%m-%d')) + query = query.receipt_date_between(Time.now.beginning_of_day, Time.now.end_of_day) .group("sales.sale_id") end @@ -2084,8 +2017,7 @@ 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) + tax_data = TaxProfile.where(group_type: order_source) customer_tax_profiles = Customer.select(:tax_profiles).where(customer_id: customer_id).first if customer_tax_profiles.present? diff --git a/app/models/sale_item.rb b/app/models/sale_item.rb index 3510b7c4..f686ca09 100755 --- a/app/models/sale_item.rb +++ b/app/models/sale_item.rb @@ -280,6 +280,11 @@ class SaleItem < ApplicationRecord # Loader Service SFTP End + protected + def self.generate_ids(count = 1) + SeedGenerator.generate_ids(self.name, "SLI", count) + end + private def generate_custom_id if self.sale_item_id.nil? diff --git a/app/models/sale_payment.rb b/app/models/sale_payment.rb index e0ad2383..7bf5b323 100755 --- a/app/models/sale_payment.rb +++ b/app/models/sale_payment.rb @@ -66,7 +66,7 @@ class SalePayment < ApplicationRecord return self.save end - def process_payment(invoice, action_by, cash_amount, payment_method,remark=nil,payment_for=false) + def process_payment(invoice, action_by, cash_amount, payment_method, remark=nil, payment_for=false) self.sale = invoice self.received_amount = cash_amount self.payment_reference = remark @@ -87,13 +87,14 @@ class SalePayment < ApplicationRecord amount_due = amount_due - payment.payment_amount end end - if (amount_due >= 0) + + if (amount_due > 0) payment_status = false membership_data = nil #route to payment type case payment_method when "cash" - payment_status ,outstanding_amount ,balance_amount = cash_payment(payment_for) + payment_status, outstanding_amount, balance_amount = cash_payment(payment_for) when "creditnote" if !self.sale.customer_id.nil? payment_status = creditnote_payment(self.customer_id) @@ -157,7 +158,7 @@ class SalePayment < ApplicationRecord # update complete order items in oqs booking = Booking.find_by_sale_id(sale_id) booking.booking_orders.each do |sodr| - assigned =AssignedOrderItem.where("order_id = '#{ sodr.order_id }'").pluck(:assigned_order_item_id) + assigned = AssignedOrderItem.where("order_id = '#{ sodr.order_id }'").pluck(:assigned_order_item_id) AssignedOrderItem.where('assigned_order_item_id IN (?)', assigned).update_all(delivery_status: true) # AssignedOrderItem.where("order_id = '#{ sodr.order_id }'").find_each do |aoi| # aoi.delivery_status = 1 @@ -165,7 +166,7 @@ class SalePayment < ApplicationRecord # end end - return true, self.save,membership_data, outstanding_amount ,balance_amount + return true, self.save, membership_data, outstanding_amount, balance_amount else #record an payment in sale-audit remark = "Payment failed - Grand Total [#{invoice.grand_total}] | Due [#{amount_due}] | Paid [#{invoice.amount_received}]" @@ -173,6 +174,7 @@ class SalePayment < ApplicationRecord return false, "Payment failed" end else + sale_update_payment_status(0) #record an payment in sale-audit remark = "No outstanding Amount - Grand Total [#{invoice.grand_total}] | Due [#{amount_due}] | Paid [#{invoice.amount_received}]" sale_audit = SaleAudit.record_payment(invoice.id, remark,action_by.name) @@ -640,85 +642,62 @@ class SalePayment < ApplicationRecord return payment_status end - def sale_update_payment_status(paid_amount,check_foc = false) + def sale_update_payment_status(paid_amount, check_foc = false) #update amount_outstanding - self.sale.amount_received = self.sale.amount_received.to_f + paid_amount.to_f - self.sale.save! - self.sale.amount_changed = self.sale.amount_received.to_f - self.sale.grand_total.to_f - all_received_amount = 0.0 - sObj = Sale.find(self.sale_id) - is_credit = 0 - is_foc = 0 - is_kbz_pay = 0 - method_status = false - sObj.sale_payments.each do |spay| - all_received_amount += spay.payment_amount.to_f - if spay.payment_method == "creditnote" - is_credit = 1 - end - if spay.payment_method == "foc" - is_foc = 1 - end - if spay.payment_method == KbzPay::KBZ_PAY - is_kbz_pay = 1 - end - if spay.payment_method == "cash" || spay.payment_method == "foc" || spay.payment_method == "creditnote" || spay.payment_method == KbzPay::KBZ_PAY - method_status = true - end - end - if (self.sale.grand_total <= all_received_amount) && method_status - if is_credit == 0 - self.sale.payment_status = "paid" + sale = self.sale + sale.amount_received = sale.amount_received.to_f + paid_amount.to_f + sale.amount_changed = sale.amount_received.to_f - sale.grand_total.to_f + + all_received_amount = sale.sale_payments.reload.sum(&:payment_amount) + + is_credit = sale.sale_payments.any? { |x| x.payment_method == "creditnote" } + is_foc = sale.sale_payments.any? { |x| x.payment_method == "foc" } + + if (sale.grand_total <= all_received_amount) + if is_credit + sale.payment_status = "outstanding" + elsif is_foc + sale.payment_status = "foc" else - self.sale.payment_status = "outstanding" + sale.payment_status = "paid" end - if is_foc == 0 - self.sale.payment_status = "paid" - else - self.sale.payment_status = "foc" - end - - if is_kbz_pay == 1 - self.sale.payment_status = 'paid' - end - - self.sale.sale_status = "completed" + sale.sale_status = "completed" if MembershipSetting.find_by_rebate(1) && is_foc == 0 && is_credit == 0 - response = rebat(sObj) + response = rebat(sale) #record an payment in sale-audit - remark = "#{response} Rebate- for Customer #{self.sale.customer_id} | Sale Id [#{self.sale.sale_id}]| pay amount -> #{self.received_amount} " - sale_audit = SaleAudit.record_paymal(sObj.sale_id, remark, 1) + remark = "#{response} Rebate- for Customer #{sale.customer_id} | Sale Id [#{sale.sale_id}]| pay amount -> #{self.received_amount} " + sale_audit = SaleAudit.record_paymal(sale.sale_id, remark, 1) if !response.nil? if response["status"] == true - self.sale.rebate_status = 'true' + sale.rebate_status = 'true' end if response["status"] == false - self.sale.rebate_status = 'false' + sale.rebate_status = 'false' end if response[:status] == false - self.sale.rebate_status = 'false' + sale.rebate_status = 'false' end if response[:status] == "no_member" - self.sale.rebate_status = nil + sale.rebate_status = nil end end end - self.sale.save! + sale.save! if check_foc - table_update_status(sObj) + table_update_status(sale) update_shift elsif paid_amount.to_f > 0 #|| paid_amount != "0.0" - table_update_status(sObj) + table_update_status(sale) update_shift - elsif method_status && paid_amount.to_f == 0 && is_credit == 0 - table_update_status(sObj) + elsif paid_amount.to_f == 0 && !is_credit + table_update_status(sale) update_shift end end @@ -778,45 +757,16 @@ class SalePayment < ApplicationRecord end def table_update_status(sale_obj) - status = true - sale_count = 0 - booking = Booking.find_by_sale_id(sale_obj.id) - if booking - if booking.dining_facility_id.to_i > 0 - table = DiningFacility.find(booking.dining_facility_id) - bookings = table.bookings - bookings.each do |tablebooking| - if tablebooking.booking_status != 'moved' - if tablebooking.sale_id - if tablebooking.sale.sale_status != 'completed' && tablebooking.sale.sale_status != 'void' && tablebooking.sale.sale_status != 'spoile' && tablebooking.sale.sale_status != 'waste' - status = false - sale_count += 1 - else - status = true - end - else - status = false - sale_count += 1 - end - end + puts "Update staus 1" + if booking = sale_obj.booking + puts "Update staus 2" + if booking.dining_facility + puts "Update staus 3" + table = booking.dining_facility + if !table.current_bookings.exists? + puts "Update staus 3" + table.update_attributes(status: "available") end - if status && sale_count == 0 - table.update_attributes(status: "available") - # table.status = "available" - # table.save - end - - # type = 'payment' - #Send to background job for processing - # OrderBroadcastJob.perform_later(table,type) - #if ENV["SERVER_MODE"] != 'cloud' - # if ENV["SERVER_MODE"] == 'cloud' - # from = request.subdomain + "." + request.domain - # else - # from = "" - # end - # ActionCable.server.broadcast "order_channel",table: table,type:type,from:from - #end end end end @@ -973,37 +923,30 @@ class SalePayment < ApplicationRecord #credit payment query def self.get_credit_sales(params) - receipt_no = "" - customer = "" - if !params["receipt_no"].blank? - receipt_no = " and s.receipt_no LIKE '%#{params["receipt_no"]}%'" + payments = SalePayment.select("sale_payments.sale_id, sale_payments.sale_payment_id, sale_payments.payment_method, sale_payments.payment_amount") + .select("SUM(sale_payments.payment_amount) OVER (PARTITION BY sale_payments.sale_id) total_payment_amount") + + credit_sales = Sale.select("sales.sale_id, sales.receipt_no, sales.receipt_date as sale_date, sales.cashier_name") + .select("sale_payments.sale_payment_id, sale_payments.payment_amount").select("customers.name as customer_name") + .joins("JOIN (#{payments.to_sql}) AS sale_payments ON sale_payments.sale_id = sales.sale_id").joins(:customer).joins(:orders) + .completed.paid.where("sale_payments.payment_method = 'creditnote' AND sales.grand_total > sale_payments.total_payment_amount - sale_payments.payment_amount") + .group(:receipt_no) + .order(:receipt_date).order(:receipt_no) + + if params["receipt_no"].present? + credit_sales = credit_sales.where("sales.receipt_no LIKE ?", "%#{params["receipt_no"]}%") end - if !params["customer_id"].blank? - customer = " and s.customer_id = '#{params["customer_id"]}'" + if params["customer_id"].present? + credit_sales = credit_sales.where("sales.customer_id = ?", params["customer_id"]) 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)" - - query = SalePayment.select("s.receipt_no, sale_payments.sale_payment_id, - sale_payments.payment_method, - SUM(sale_payments.payment_amount) as payment_amount, - s.receipt_date as sale_date, - s.sale_id, - s.cashier_name as cashier_name, c.name as customer_name") - .joins("INNER JOIN sales s ON s.sale_id = sale_payments.sale_id") - .joins("INNER JOIN customers c ON c.customer_id = s.customer_id") - - if params[:type].nil? - query = query.where("(CASE WHEN (s.grand_total + s.amount_changed)=(select SUM(payment_amount) FROM sale_payments WHERE sale_id=s.sale_id AND payment_method!='creditnote') THEN NULL ELSE payment_method='creditnote' END) and s.sale_status = 'completed' and s.payment_status='paid' #{receipt_no} #{customer}") - elsif params[:type] == "cashier" - query = query.where("(CASE WHEN (s.grand_total + s.amount_changed)=(select SUM(payment_amount) FROM sale_payments WHERE sale_id=s.sale_id AND payment_method!='creditnote') THEN NULL ELSE payment_method='creditnote' AND #{order_source_query}='#{params[:type]}' OR #{order_source_query}='emenu' END) and s.sale_status = 'completed' and s.payment_status='paid' #{receipt_no} #{customer}") - else - query = query.where("(CASE WHEN (s.grand_total + s.amount_changed)=(select SUM(payment_amount) FROM sale_payments WHERE sale_id=s.sale_id AND payment_method!='creditnote') THEN NULL ELSE payment_method='creditnote' AND #{order_source_query}='#{params[:type]}' END) and s.sale_status = 'completed' and s.payment_status='paid' #{receipt_no} #{customer}") + if params[:type].present? + sources = [] + sources << params[:type] + sources << 'emenu' if params[:type] == 'cashier' + credit_sales = credit_sales.where("orders.source IN (?)", sources) end - query = query.group("s.receipt_no") - .order("s.receipt_date ASC, s.receipt_no ASC") - return query end def self.get_credit_amount_due_left(sale_id) diff --git a/app/models/seed_generator.rb b/app/models/seed_generator.rb index 2a363dd8..badde01f 100755 --- a/app/models/seed_generator.rb +++ b/app/models/seed_generator.rb @@ -3,19 +3,44 @@ class SeedGenerator < ApplicationRecord def self.generate_id(model, prefix) model_name = self.get_model_name(model) + prefix ||= '' + prefix << '-' if prefix.present? + if ENV["SERVER_MODE"] == 'cloud' - prefix = "C#{prefix}" + prefix << 'C' + else + prefix << 'L' end - cur_val, next_val = self.update_seed(model_name) - - if (cur_val == 0) - cur_val, next_val = self.execute_query(model_name) + if shop = Shop.current_shop + prefix << shop.shop_code end - padding_len = 15 - prefix.length - saleOrderId = prefix +"-"+ cur_val.to_s.to_s.rjust((14-prefix.length)+1,'0') - return saleOrderId + seed = self.update_seed(model_name) + length = 15 - prefix.length + prefix + seed.to_s.rjust(padding_len, '0') + end + + def self.generate_ids(model, prefix, count = 1) + model_name = self.get_model_name(model) + + prefix ||= '' + prefix << '-' if prefix.present? + + if ENV["SERVER_MODE"] == 'cloud' + prefix << 'C' + else + prefix << 'L' + end + + if shop = Shop.current_shop + prefix << shop.shop_code + end + + start = self.update_seed(model_name, count) + stop = start + count - 1 + length = 15 - prefix.length + (start..stop).map { |c| prefix + c.to_s.rjust(length, '0') } end def self.sync_seed_generator_records(seed_generators) @@ -58,7 +83,7 @@ class SeedGenerator < ApplicationRecord end end - return new_receipt_no + return new_receipt_no end # Generate for 4 digit Code @@ -85,7 +110,7 @@ class SeedGenerator < ApplicationRecord # padding_len = 6 - prefix.length # count = 5-prefix.length # end - # next_code = prefix + seed.current.to_s.to_s.rjust((count)+1,'0') + # next_code = prefix + seed.current.to_s.to_s.rjust((count)+1,'0') # return next_code # end @@ -100,41 +125,13 @@ class SeedGenerator < ApplicationRecord return model_name end - def self.execute_query(model) - current = 0 - nex = 0 - - sql = "INSERT INTO seed_generators (model, created_at, updated_at) - VALUES('#{ model }', NOW(), NOW()) - ON DUPLICATE KEY UPDATE current = current + 1, next = next + 1;" - - select_sql = "select * from seed_generators where model='#{model}';" - ActiveRecord::Base.connection.execute(sql); - select_result = ActiveRecord::Base.connection.execute(select_sql); - - select_result.each do |row| - current = row [3] - nex = row[4] + def self.update_seed(model, count = 1) + SeedGenerator.transaction do + seed = SeedGenerator.lock.find_by_model(model) + seed.next = seed.next + (count * seed.increase_by) + seed.current = seed.next - seed.increase_by + seed.save! + seed.next_before_last_save end - - return current, nex - end - - def self.update_seed(model) - current = 0 - nex = 0 - - update_sql = "UPDATE seed_generators set current = next, next = next + 1 WHERE model='#{model}';" - select_sql = "select * from seed_generators where model='#{model}';" - update_result = ActiveRecord::Base.connection.execute(update_sql); - - select_result = ActiveRecord::Base.connection.execute(select_sql); - - select_result.each do |row| - current = row [3] - nex = row[4] - end - - return current, nex end end diff --git a/app/models/shift_sale.rb b/app/models/shift_sale.rb index 07217103..56db452f 100755 --- a/app/models/shift_sale.rb +++ b/app/models/shift_sale.rb @@ -19,7 +19,7 @@ class ShiftSale < ApplicationRecord def self.current_shift # today_date = DateTime.now.strftime("%Y-%m-%d") - shift = ShiftSale.where("shift_started_at is not null and shift_closed_at is null").first + shift = ShiftSale.where.not(shift_started_at: nil).where(shift_closed_at: nil).first return shift end diff --git a/app/models/shop.rb b/app/models/shop.rb index 75c30dd7..41110515 100755 --- a/app/models/shop.rb +++ b/app/models/shop.rb @@ -1,13 +1,17 @@ class Shop < ApplicationRecord - #ShopDetail = Shop.find_by_id(1) + #ShopDetail = Shop.current_shop # Shop Image Uploader - mount_uploader :logo, ShopImageUploader + mount_uploader :logo, ShopImageUploader - has_many :display_images + has_many :display_images accepts_nested_attributes_for :display_images def file_data=(input_data) self.data = input_data.read end + + def self.current_shop + ActsAsTenant.current_tenant + end end diff --git a/app/models/tax_profile.rb b/app/models/tax_profile.rb index a9e56fac..5ae936ba 100755 --- a/app/models/tax_profile.rb +++ b/app/models/tax_profile.rb @@ -1,4 +1,6 @@ class TaxProfile < ApplicationRecord + has_one :lookup, -> { where(lookup_type: 'tax_profiles') }, foreign_key: "value", primary_key: "group_type" + default_scope { order('order_by asc') } # validations validates_presence_of :name, :rate, :group_type diff --git a/app/pdf/order_summary_pdf.rb b/app/pdf/order_summary_pdf.rb index f3d25ff1..c1710cda 100755 --- a/app/pdf/order_summary_pdf.rb +++ b/app/pdf/order_summary_pdf.rb @@ -1,7 +1,7 @@ class OrderSummaryPdf < Prawn::Document include NumberFormattable attr_accessor :label_width,:price_column_width,:page_width, :page_height, :margin, :price_width, :item_width, :header_font_size, :item_font_size,:item_height,:qty_width,:total_width,:item_description_width - def initialize(print_settings,order, print_status, order_items = nil,alt_name,before_updated_qty) + def initialize(print_settings, order, print_status, order_items = nil, alt_name, before_updated_qty) self.page_width = print_settings.page_width self.page_height = print_settings.page_height self.header_font_size = print_settings.header_font_size.to_i diff --git a/app/uploaders/commissioner_image_uploader.rb b/app/uploaders/commissioner_image_uploader.rb index 9b65e4a8..42e90a16 100644 --- a/app/uploaders/commissioner_image_uploader.rb +++ b/app/uploaders/commissioner_image_uploader.rb @@ -20,11 +20,11 @@ class CommissionerImageUploader < CarrierWave::Uploader::Base end def filename - if Shop.first.shop_code.nil? - "#{original_filename}" if original_filename.present? + if Shop.current_shop.shop_code.nil? + "#{original_filename}" if original_filename.present? else - "#{Shop.first.shop_code}_#{original_filename}" if original_filename.present? - end + "#{Shop.current_shop.shop_code}_#{original_filename}" if original_filename.present? + end end # def cache_dir @@ -62,6 +62,6 @@ class CommissionerImageUploader < CarrierWave::Uploader::Base # Avoid using model.id or version_name here, see uploader/store.rb for details. # def filename # "something.jpg" if original_filename - # end + # end -end \ No newline at end of file +end diff --git a/app/uploaders/customer_image_uploader.rb b/app/uploaders/customer_image_uploader.rb index be1326d6..77a133af 100644 --- a/app/uploaders/customer_image_uploader.rb +++ b/app/uploaders/customer_image_uploader.rb @@ -20,11 +20,11 @@ class CustomerImageUploader < CarrierWave::Uploader::Base end def filename - if Shop.first.shop_code.nil? - "#{original_filename}" if original_filename.present? + if Shop.current_shop.shop_code.nil? + "#{original_filename}" if original_filename.present? else - "#{Shop.first.shop_code}_#{original_filename}" if original_filename.present? - end + "#{Shop.current_shop.shop_code}_#{original_filename}" if original_filename.present? + end end # def cache_dir @@ -62,6 +62,6 @@ class CustomerImageUploader < CarrierWave::Uploader::Base # Avoid using model.id or version_name here, see uploader/store.rb for details. # def filename # "something.jpg" if original_filename - # end + # end -end \ No newline at end of file +end diff --git a/app/uploaders/employee_image_uploader.rb b/app/uploaders/employee_image_uploader.rb index 17c9d120..62aa3e15 100644 --- a/app/uploaders/employee_image_uploader.rb +++ b/app/uploaders/employee_image_uploader.rb @@ -20,11 +20,11 @@ class EmployeeImageUploader < CarrierWave::Uploader::Base end def filename - if Shop.first.shop_code.nil? - "#{original_filename}" if original_filename.present? + if Shop.current_shop.shop_code.nil? + "#{original_filename}" if original_filename.present? else - "#{Shop.first.shop_code}_#{original_filename}" if original_filename.present? - end + "#{Shop.current_shop.shop_code}_#{original_filename}" if original_filename.present? + end end # def cache_dir @@ -62,6 +62,6 @@ class EmployeeImageUploader < CarrierWave::Uploader::Base # Avoid using model.id or version_name here, see uploader/store.rb for details. # def filename # "something.jpg" if original_filename - # end + # end -end \ No newline at end of file +end diff --git a/app/uploaders/menu_item_image_uploader.rb b/app/uploaders/menu_item_image_uploader.rb index 7a4b2039..5f23cafc 100755 --- a/app/uploaders/menu_item_image_uploader.rb +++ b/app/uploaders/menu_item_image_uploader.rb @@ -15,16 +15,16 @@ class MenuItemImageUploader < CarrierWave::Uploader::Base # Override the directory where uploaded files will be stored. # This is a sensible default for uploaders that are meant to be mounted: def store_dir - "image/menu_images/#{Shop.first.shop_code}" + "image/menu_images/#{Shop.current_shop.shop_code}" # "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" end def filename - if Shop.first.shop_code.nil? - "#{original_filename}" if original_filename.present? + if Shop.current_shop.shop_code.nil? + "#{original_filename}" if original_filename.present? else - "#{Shop.first.shop_code}_#{original_filename}" if original_filename.present? - end + "#{Shop.current_shop.shop_code}_#{original_filename}" if original_filename.present? + end end # def cache_dir @@ -42,7 +42,7 @@ class MenuItemImageUploader < CarrierWave::Uploader::Base # Process files as they are uploaded: # process scale: [200, 300] process :resize_to_fit => [400, 250]#[200, 150] - + # # def scale(width, height) # # do something diff --git a/app/uploaders/product_image_uploader.rb b/app/uploaders/product_image_uploader.rb index c39d867d..35fde675 100755 --- a/app/uploaders/product_image_uploader.rb +++ b/app/uploaders/product_image_uploader.rb @@ -20,11 +20,11 @@ class ProductImageUploader < CarrierWave::Uploader::Base end def filename - if Shop.first.shop_code.nil? - "#{original_filename}" if original_filename.present? + if Shop.current_shop.shop_code.nil? + "#{original_filename}" if original_filename.present? else - "#{Shop.first.shop_code}_#{original_filename}" if original_filename.present? - end + "#{Shop.current_shop.shop_code}_#{original_filename}" if original_filename.present? + end end # def cache_dir diff --git a/app/uploaders/shop_image_uploader.rb b/app/uploaders/shop_image_uploader.rb index 394704c3..c27fb65c 100644 --- a/app/uploaders/shop_image_uploader.rb +++ b/app/uploaders/shop_image_uploader.rb @@ -20,11 +20,11 @@ class ShopImageUploader < CarrierWave::Uploader::Base end def filename - if Shop.first.shop_code.nil? - "#{original_filename}" if original_filename.present? + if Shop.current_shop.shop_code.nil? + "#{original_filename}" if original_filename.present? else - "#{Shop.first.shop_code}_#{original_filename}" if original_filename.present? - end + "#{Shop.current_shop.shop_code}_#{original_filename}" if original_filename.present? + end end # def cache_dir @@ -62,6 +62,6 @@ class ShopImageUploader < CarrierWave::Uploader::Base # Avoid using model.id or version_name here, see uploader/store.rb for details. # def filename # "something.jpg" if original_filename - # end + # end -end \ No newline at end of file +end diff --git a/app/views/api/restaurant/menu/_menu_item.json.jbuilder b/app/views/api/restaurant/menu/_menu_item.json.jbuilder index c6cc8468..1ac16ebc 100755 --- a/app/views/api/restaurant/menu/_menu_item.json.jbuilder +++ b/app/views/api/restaurant/menu/_menu_item.json.jbuilder @@ -1,57 +1,26 @@ # Format for attributes json attr_format = [] -# Format for attributes json +# Format for attributes json if item.is_available - if item.item_attributes.count > 0 - item.item_attributes.each do|attr_id| - menu_attr = MenuItemAttribute.find(attr_id) - if attr_format.count == 0 - attr_format.push({ type: menu_attr.attribute_type, values: [menu_attr.name] }) - next - end - - attr_format.each do |af| - if menu_attr.attribute_type.in? attr_format.map {|k| k[:type]} - if menu_attr.attribute_type == af[:type] - af[:values].push(menu_attr.name) - end - else - new_attr = {type: menu_attr.attribute_type, values: [ menu_attr.name ] } - attr_format.push(new_attr) - break - end - end - end + # Format for attributes json + attr_format = [] + # Format for attributes json + if item.item_attributes.count > 0 + item_attributes = item.item_attributes.map(&:to_s) + attr_format = @item_attributes.select { |x| item_attributes.include?(x.id.to_s) }.group_by {|att| att.attribute_type.strip }.map { |type, values| {type: type, values: values.map { |x| x.name.strip } } } end # Format for option json opt_format = [] - # Format for attributes json - if item.item_options.count > 0 - item.item_options.each do|opt| - menu_opt = MenuItemOption.find(opt) - if opt_format.count == 0 - opt_format.push({ type: menu_opt.option_type, values: [menu_opt.name] }) - next - end - - opt_format.each do |of| - if menu_opt.option_type.in? opt_format.map {|k| k[:type]} - if menu_opt.option_type == of[:type] - of[:values].push(menu_opt.name) - end - else - new_opt = {type: menu_opt.option_type, values: [ menu_opt.name ] } - opt_format.push(new_opt) - break - end - end - end + # Format for attributes json + if item.item_options.count > 0 + item_options = item.item_options.map(&:to_s) + opt_format = @item_options.select { |x| item_options.include?(x.id.to_s) }.group_by {|opt| opt.option_type.strip }.map { |type, values| {type: type, values: values.map { |x| x.name.strip } } } end #Menu Item Information json.id item.id - json.code item.item_code + json.code item.item_code json.name item.name json.alt_name item.alt_name if !request_url.nil? && request_url != '' && !item.image_path.nil? @@ -68,17 +37,15 @@ if item.is_available json.is_sub_item item.is_sub_item json.unit item.unit - # Item Sets of Menu Item + # Item Sets of Menu Item json.item_sets item.item_sets do |its| json.id its.id json.name its.name json.alt_name its.alt_name json.min_selectable_qty its.min_selectable_qty json.max_selectable_qty its.max_selectable_qty - json.instances its.menu_item_instances do |i| - json.id i.id - end - end + json.instances its.menu_item_instances.map { |i| {id: i.id} } + end json.attributes attr_format json.options opt_format @@ -97,25 +64,19 @@ if item.is_available json.instances item.menu_item_instances do |is| if is.is_available # Convert id to name for attributes - instance_attr = [] + item_attributes = is.item_attributes.map(&:to_s) + instance_attr = @item_attributes.select{ |x| item_attributes.include?(x.id.to_s) }.pluck(:name) - is.item_attributes.each do |ia| - # mItemAttr = MenuItemAttribute.find(is) - # instance_attr.push(ia) - mItemAttr = MenuItemAttribute.find(ia).name - instance_attr.push(mItemAttr) - end - - json.id is.id - json.code is.item_instance_code - json.name is.item_instance_name - json.price is.price - json.is_available is.is_available - json.is_default is.is_default - json.is_on_promotion is.is_on_promotion - json.promotion_price is.promotion_price - json.values instance_attr - # json.item_sets is.item_sets + json.id is.id + json.code is.item_instance_code + json.name is.item_instance_name + json.price is.price + json.is_available is.is_available + json.is_default is.is_default + json.is_on_promotion is.is_on_promotion + json.promotion_price is.promotion_price + json.values instance_attr + # json.item_sets is.item_sets end end @@ -125,4 +86,4 @@ if item.is_available # json.partial! 'api/restaurant/menu/menu_item', item: item # end # end -end \ No newline at end of file +end diff --git a/app/views/origami/addorders/detail.html.erb b/app/views/origami/addorders/detail.html.erb index ce3d709d..27d13860 100644 --- a/app/views/origami/addorders/detail.html.erb +++ b/app/views/origami/addorders/detail.html.erb @@ -54,7 +54,7 @@ <% end%> <% else %> - <% if @table.get_current_checkout_booking.nil? %> + <% if @table.current_checkout_booking.nil? %> <% if !menu.code.include? "SPL" %>