diff --git a/Gemfile b/Gemfile
index 957e9968..11a34b3c 100644
--- a/Gemfile
+++ b/Gemfile
@@ -1,6 +1,6 @@
source 'https://rubygems.org'
-ruby '2.4.1'
+#ruby '2.4.1'
#ruby '2.5.7'
git_source(:github) do |repo_name|
@@ -44,9 +44,6 @@ gem 'rack-cors'
# Multi-tenancy for shops
gem 'acts_as_tenant'
-# Activerecord-Import is a library for bulk inserting data using ActiveRecord.
-gem 'activerecord-import'
-
# image upload
gem 'carrierwave', '~> 1.0'
gem 'mini_magick'
diff --git a/Gemfile.lock b/Gemfile.lock
index 76ce8948..bbcc1085 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -41,8 +41,6 @@ GEM
activemodel (= 5.1.7)
activesupport (= 5.1.7)
arel (~> 8.0)
- activerecord-import (1.0.3)
- activerecord (>= 3.2)
activesupport (5.1.7)
concurrent-ruby (~> 1.0, >= 1.0.2)
i18n (>= 0.7, < 2)
@@ -322,7 +320,6 @@ PLATFORMS
ruby
DEPENDENCIES
- activerecord-import
acts_as_tenant
aescrypt
axlsx (= 2.0.1)
diff --git a/app/assets/javascripts/addorder.js b/app/assets/javascripts/addorder.js
index 93ec79c1..ca5a6932 100755
--- a/app/assets/javascripts/addorder.js
+++ b/app/assets/javascripts/addorder.js
@@ -1097,16 +1097,28 @@ $(function() {
var total_price = 0;
var total_qty = 0;
var taxable_amount = 0;
+ var exclusive_total =0;
+ var inclusive_total =0;
+ var inclusive_tax =$('#inclusive_tax').val();
+ var exclusive_tax =$('#exclusive_tax').val();
var item_row = $('.summary-items tbody tr');
-
$(item_row).each(function(i){
var unit_price = parseFloat($(item_row[i]).attr('data-price'));
var qty = parseFloat($(item_row[i]).children('#item_qty').text());
total_qty += qty;
total_price += qty*unit_price;
});
+ if (inclusive_tax >0){
+ inclusive_total = total_price / inclusive_tax;
+ }
+ if (exclusive_tax >0){
+ exclusive_total = total_price * exclusive_tax;
+ }
+ total_price = total_price + exclusive_total + inclusive_total;
var fixed_total_price = parseFloat(total_price).toFixed(2);
var fixed_taxable_amount = parseFloat(taxable_amount).toFixed(2);
+ $('#total_tax').empty();
+ $('#total_tax').append(exclusive_total + inclusive_total);
$('#sub_total').empty();
$('#sub_total').append(fixed_total_price);
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 c60b3f0f..8c6aaf65 100755
--- a/app/controllers/api/api_controller.rb
+++ b/app/controllers/api/api_controller.rb
@@ -1,9 +1,9 @@
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
diff --git a/app/controllers/api/bill_controller.rb b/app/controllers/api/bill_controller.rb
index 77fc9204..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
@@ -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/orders_controller.rb b/app/controllers/api/orders_controller.rb
index a1e9ad9e..0c79f303 100755
--- a/app/controllers/api/orders_controller.rb
+++ b/app/controllers/api/orders_controller.rb
@@ -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/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/application_controller.rb b/app/controllers/application_controller.rb
index 8f537383..6d5a413e 100755
--- a/app/controllers/application_controller.rb
+++ b/app/controllers/application_controller.rb
@@ -1,6 +1,7 @@
class ApplicationController < ActionController::Base
include MultiTenancy
include LoginVerification
+ include Customers
#before_action :check_installation
protect_from_forgery with: :exception
diff --git a/app/controllers/base_crm_controller.rb b/app/controllers/base_crm_controller.rb
index 1f6ad484..273a3639 100755
--- a/app/controllers/base_crm_controller.rb
+++ b/app/controllers/base_crm_controller.rb
@@ -1,5 +1,4 @@
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 b591fe85..64cdd2cd 100755
--- a/app/controllers/base_inventory_controller.rb
+++ b/app/controllers/base_inventory_controller.rb
@@ -1,5 +1,4 @@
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 776f8749..6b01383d 100755
--- a/app/controllers/base_oqs_controller.rb
+++ b/app/controllers/base_oqs_controller.rb
@@ -1,8 +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 cd011ca4..468a2fab 100755
--- a/app/controllers/base_origami_controller.rb
+++ b/app/controllers/base_origami_controller.rb
@@ -1,7 +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 cab046ad..eb7be119 100755
--- a/app/controllers/base_report_controller.rb
+++ b/app/controllers/base_report_controller.rb
@@ -1,5 +1,4 @@
class BaseReportController < ActionController::Base
-
include MultiTenancy
include LoginVerification
layout "application"
diff --git a/app/controllers/base_waiter_controller.rb b/app/controllers/base_waiter_controller.rb
index 598b93d6..f89a8f31 100755
--- a/app/controllers/base_waiter_controller.rb
+++ b/app/controllers/base_waiter_controller.rb
@@ -1,5 +1,4 @@
class BaseWaiterController < ActionController::Base
-
include MultiTenancy
include LoginVerification
layout "waiter"
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/number_formattable.rb b/app/controllers/concerns/number_formattable.rb
index 2507b10a..60f6c4c0 100644
--- a/app/controllers/concerns/number_formattable.rb
+++ b/app/controllers/concerns/number_formattable.rb
@@ -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,7 +42,7 @@ 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
diff --git a/app/controllers/crm/customers_controller.rb b/app/controllers/crm/customers_controller.rb
index 023b453c..0263740d 100644
--- a/app/controllers/crm/customers_controller.rb
+++ b/app/controllers/crm/customers_controller.rb
@@ -21,7 +21,7 @@ class Crm::CustomersController < BaseCrmController
# paymal_customer = Customer.search_paypar_account_no(filter)
# search account no from paypar
if type == "card"
-
+
response = Customer.search_paypar_account_no(filter)
if !@crm_customers.present?
if response["status"] == true
@@ -70,7 +70,7 @@ class Crm::CustomersController < BaseCrmController
else
flash[:member_error]="Need to press sync button "
end
-
+
end
end
end
@@ -82,8 +82,9 @@ class Crm::CustomersController < BaseCrmController
@membership_types = Lookup.collection_of("member_group_type")
# @taxes = TaxProfile.where(:group_type => 'cashier')
- @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")
+ @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
@@ -95,7 +96,7 @@ class Crm::CustomersController < BaseCrmController
lookup_customer = Lookup.collection_of('customer_settings')
if !lookup_customer.empty?
lookup_customer.each do |create_setting|
- if create_setting[0].downcase == "create"
+ if create_setting[0].downcase == "create"
if create_setting[1] == '0' && current_login_employee.role == 'cashier'
@create_flag = false
end
@@ -135,7 +136,7 @@ class Crm::CustomersController < BaseCrmController
params[:type] = nil
params[:customer_id] = params[:id]
@credit_sales = SalePayment.get_credit_sales(params)
-
+
#get customer amount
@customer = Customer.find(params[:id])
@response = Customer.get_membership_transactions(@customer)
@@ -158,8 +159,9 @@ class Crm::CustomersController < BaseCrmController
def edit
@customer = Customer.find(params[:id])
end
+
def sync
- @customer = Customer.find(params[:id])
+ @customer = Customer.find(params[:id])
respond_to do |format|
name = @customer.name
phone = @customer.contact_no
@@ -169,17 +171,15 @@ class Crm::CustomersController < BaseCrmController
nrc = @customer.nrc_no
card_no = @customer.card_no
paypar_account_no = @customer.paypar_account_no
- id = @crm_customer.membership_id
- member_group_id = @customer.membership_type
- if !id.present? && !member_group_id.nil?
+ id = @customer.membership_id
+ member_group_id = @customer.membership_type
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
-
member_params = { name: name,phone: phone,email: email,
- dob: dob,address: address,nrc:nrc,card_no:card_no,
+ 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
@@ -193,7 +193,6 @@ class Crm::CustomersController < BaseCrmController
member_group_id: member_group_id,
id:id,
merchant_uid:merchant_uid,auth_token:auth_token}.to_json
- end
begin
response = HTTParty.post(url,
@@ -221,7 +220,7 @@ class Crm::CustomersController < BaseCrmController
Rails.logger.debug "--------Sync Member response -------"
Rails.logger.debug response.to_json
if response["status"] == true
-
+
status = customer.update_attributes(membership_id: response["customer_datas"]["id"],membership_type:member_group_id )
format.html { redirect_to crm_customers_path }
@@ -252,9 +251,9 @@ class Crm::CustomersController < BaseCrmController
end
# POST /crm/customers
# POST /crm/customers.json
- def create
- # Remove "" default first
- params[:customer][:tax_profiles].delete_at(0)
+ def create
+ # Remove "" default first
+ params[:customer][:tax_profiles].delete_at(0)
@checked_contact = Customer.find_by_contact_no(customer_params[:contact_no])
if @checked_contact.nil?
respond_to do |format|
@@ -272,7 +271,7 @@ class Crm::CustomersController < BaseCrmController
nrc = customer_params[:nrc_no]
card_no = customer_params[:card_no]
paypar_account_no = customer_params[:paypar_account_no]
- member_group_id = params[:member_group_id]
+ member_group_id = params[:member_group_id]
if member_group_id.present?
membership = MembershipSetting.find_by_membership_type("paypar_url")
@@ -282,7 +281,7 @@ class Crm::CustomersController < BaseCrmController
url = membership.gateway_url.to_s + memberaction.gateway_url.to_s
member_params = { name: name,phone: phone,email: email,
- dob: dob,address: address,nrc:nrc,card_no:card_no,
+ dob: dob,address: address,nrc:nrc,card_no:card_no,
member_group_id: member_group_id,
merchant_uid:merchant_uid,auth_token:auth_token}.to_json
@@ -333,7 +332,7 @@ class Crm::CustomersController < BaseCrmController
end
# format.json { render :index, status: :created, location: @crm_customers }
else
- customer = Customer.find(@crm_customers.customer_id)
+ customer = Customer.find(@crm_customers.customer_id)
# Check membership id and bind to user
if response["membership_id"] != nil
@@ -399,7 +398,7 @@ class Crm::CustomersController < BaseCrmController
# PATCH/PUT /crm/customers/1
# PATCH/PUT /crm/customers/1.json
def update
- # Remove "" default first
+ # Remove "" default first
params[:customer][:tax_profiles].delete_at(0)
@checked_contact = nil
@existed_contact = Customer.find_by_customer_id_and_contact_no(customer_params[:id], customer_params[:contact_no])
@@ -409,7 +408,7 @@ class Crm::CustomersController < BaseCrmController
if !@existed_contact.nil? || @checked_contact.nil?
respond_to do |format|
if @crm_customer.update(customer_params)
- # update tax profile
+ # update tax profile
@crm_customer.update_attributes(tax_profiles: params[:customer][:tax_profiles])
name = customer_params[:name]
phone = customer_params[:contact_no]
@@ -420,7 +419,7 @@ class Crm::CustomersController < BaseCrmController
card_no = customer_params[:card_no]
paypar_account_no = customer_params[:paypar_account_no]
id = @crm_customer.membership_id
- member_group_id = params[:member_group_id]
+ member_group_id = params[:member_group_id]
if !id.present? && !member_group_id.nil?
membership = MembershipSetting.find_by_membership_type("paypar_url")
@@ -430,7 +429,7 @@ class Crm::CustomersController < BaseCrmController
url = membership.gateway_url.to_s + memberaction.gateway_url.to_s
member_params = { name: name,phone: phone,email: email,
- dob: dob,address: address,nrc:nrc,card_no:card_no,
+ 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
@@ -471,7 +470,7 @@ class Crm::CustomersController < BaseCrmController
Rails.logger.debug "--------Update Member response -------"
Rails.logger.debug response.to_json
if response["status"] == true
-
+
status = customer.update_attributes(membership_id: response["customer_datas"]["id"],membership_type:member_group_id )
format.html { redirect_to crm_customers_path }
@@ -496,7 +495,7 @@ class Crm::CustomersController < BaseCrmController
url = membership.gateway_url.to_s + memberaction.gateway_url.to_s
member_params = { name: name,phone: phone,email: email,
- dob: dob,address: address,nrc:nrc,card_no:card_no,
+ 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
@@ -601,7 +600,7 @@ class Crm::CustomersController < BaseCrmController
flash[:member_notice]='Membership was successfully updated'
end
end
-
+
end
@@ -617,6 +616,5 @@ class Crm::CustomersController < BaseCrmController
params.require(:customer).permit(:id, :name, :company, :contact_no, :email,
:date_of_birth,:salutation,:gender,:nrc_no,:address,:card_no, :paypar_account_no, :customer_type, :image_path)
end
-
-end
+end
diff --git a/app/controllers/origami/addorders_controller.rb b/app/controllers/origami/addorders_controller.rb
index 90bc9183..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
@@ -126,67 +126,68 @@ class Origami::AddordersController < BaseOrigamiController
}
# 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
+ @order.is_extra_time = is_extra_time
+ @order.extra_time = extra_time
- 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
+ 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
- # 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')
+ @status, @booking = @order.generate
- @status, @sale = Sale.request_bill(@order,current_user,current_login_employee)
-
- # for second display
- if @order.source == 'quick_service'
+ 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 "second_display_channel",data: @sale,status:"sale",from:from
+ ActionCable.server.broadcast "order_channel", table: table,type:type,from:from
end
- #end
- result = {:status=> @status, :data => @sale }
+ 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')
+
+ @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
+ end
+ #end
+ result = {:status=> @status, :data => @sale }
+ render :json => result.to_json
+ end
+ 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
@@ -235,15 +236,9 @@ class Origami::AddordersController < BaseOrigamiController
sidekiq = Lookup.find_by_lookup_type("sidekiq")
if ENV["SERVER_MODE"] != 'cloud'
- cup_status = `#{"sudo service cups status"}`
- if !check_cup_status(cup_status)
- cup_start = `#{"sudo service cups start"}`
- cup_status = `#{"sudo service cups status"}`
- if !check_cup_status(cup_status)
- from = ''
- msg = 'Print Error ! Please contact to service'
- ActionCable.server.broadcast "call_waiter_channel", table: msg, time:'print_error', from: from
- end
+ 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
diff --git a/app/controllers/origami/customers_controller.rb b/app/controllers/origami/customers_controller.rb
index b77137a9..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)
@@ -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/food_court_controller.rb b/app/controllers/origami/food_court_controller.rb
index 1ccc9b86..7bd9d131 100644
--- a/app/controllers/origami/food_court_controller.rb
+++ b/app/controllers/origami/food_court_controller.rb
@@ -56,7 +56,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])
@@ -113,7 +113,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/home_controller.rb b/app/controllers/origami/home_controller.rb
index 5393dc96..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.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')
+ @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')
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/payments_controller.rb b/app/controllers/origami/payments_controller.rb
index 0ce60790..3103ca38 100755
--- a/app/controllers/origami/payments_controller.rb
+++ b/app/controllers/origami/payments_controller.rb
@@ -10,38 +10,18 @@ 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)
- end
+ 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
- #shop detail
- ## shop_detail = Shop.current_shop
- # 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
+ 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"
@@ -110,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.current_shop
- # 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
@@ -138,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 = saleObj.bookings[0]
+ 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 = bookings.dining_facility
- 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
@@ -353,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)
@@ -767,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/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 3e69485a..89f5c8ba 100644
--- a/app/controllers/origami/quick_service_controller.rb
+++ b/app/controllers/origami/quick_service_controller.rb
@@ -10,30 +10,27 @@ 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
+ # puts 'lookup_dine_in!!!!'
+ # puts lookup_dine_in
if !lookup_dine_in.empty?
lookup_dine_in.each do |dine_in|
if dine_in[0].downcase == "quickserviceaddorder"
@@ -43,7 +40,23 @@ class Origami::QuickServiceController < ApplicationController
end
end
end
-
+ divided_value =0
+ exclusive =0
+ tax_profiles = TaxProfile.where(group_type: "quick_service")
+ if !tax_profiles.empty?
+ tax_profiles.each do |tax|
+ #include or execulive
+ if tax.inclusive
+ tax_incl_exec = "inclusive"
+ rate = tax.rate
+ divided_value += (100 + rate)/rate
+ else
+ exclusive +=tax.rate / 100
+ end
+ end
+ end
+ @inclusive_tax =divided_value
+ @exclusive_tax =exclusive
render "origami/addorders/detail"
end
@@ -58,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])
@@ -115,13 +128,13 @@ 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
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
diff --git a/app/controllers/origami/request_bills_controller.rb b/app/controllers/origami/request_bills_controller.rb
index 69a316f5..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.current_shop
- # # 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/sales_controller.rb b/app/controllers/origami/sales_controller.rb
index 98bbd288..27f300d8 100755
--- a/app/controllers/origami/sales_controller.rb
+++ b/app/controllers/origami/sales_controller.rb
@@ -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/split_bill_controller.rb b/app/controllers/origami/split_bill_controller.rb
index 12a232a6..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
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 e3f9f0ab..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.current_shop
- 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.current_shop
- @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/models/application_record.rb b/app/models/application_record.rb
index 590cdf8d..c19491c8 100755
--- a/app/models/application_record.rb
+++ b/app/models/application_record.rb
@@ -5,10 +5,10 @@ class ApplicationRecord < ActiveRecord::Base
super
return unless subclass.superclass == self
- return unless subclass.column_names.include? 'shop_id'
+ return unless subclass.column_names.include? 'shop_code'
subclass.class_eval do
- acts_as_tenant(:shop)
+ acts_as_tenant(:shop, foreign_key: 'shop_code', primary_key: 'shop_code')
end
end
end
diff --git a/app/models/booking.rb b/app/models/booking.rb
index f99df507..c5e5d6f0 100755
--- a/app/models/booking.rb
+++ b/app/models/booking.rb
@@ -6,9 +6,57 @@ 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}")}
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 052c4a69..b3f31fa3 100755
--- a/app/models/dining_facility.rb
+++ b/app/models/dining_facility.rb
@@ -1,13 +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, -> { assign.within_time_limit.where(checkout_at: 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', nil])) }, 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_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"
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/menu_item.rb b/app/models/menu_item.rb
index 4735e6d8..5edf9513 100755
--- a/app/models/menu_item.rb
+++ b/app/models/menu_item.rb
@@ -31,17 +31,19 @@ class MenuItem < ApplicationRecord
# Work with item_code = item_instance_code
def self.search_by_item_code(item_code)
- MenuItem.joins(:menu_item_instances)
+ 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, "menu_item_instances.item_instance_name AS item_instance_name", :price, :promotion_price, :is_on_promotion, "menu_item_instances.is_available", :taxable)
- .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|
+ .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: item_name.to_s + (' - ' + item_instance_name.to_s) || '',
- alt_name: item_alt_name || '',
+ name: "#{name}",
+ alt_name: "#{item_alt_name}",
price: price,
promotion_price: promotion_price,
is_on_promotion: is_on_promotion,
diff --git a/app/models/order.rb b/app/models/order.rb
index 09caef45..0a6b8ddb 100755
--- a/app/models/order.rb
+++ b/app/models/order.rb
@@ -132,7 +132,6 @@ class Order < ApplicationRecord
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
- new_order_items = []
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 = []
@@ -144,8 +143,7 @@ class Order < ApplicationRecord
end
end
sub_order_items = sub_order_items.to_json
- new_order_items << OrderItem.new({
- order_id: id,
+ self.order_items.build({
item_code: menu_item[:item_code],
item_instance_code: order_item[:item_instance_code],
item_name: menu_item[:name],
@@ -160,17 +158,6 @@ class Order < ApplicationRecord
})
end
- ids = OrderItem.generate_ids(new_order_items.length)
- new_order_items.each_with_index do |order_item, index|
- order_item.order_items_id = ids[index]
- end
-
- OrderItem.import new_order_items, validate: false
-
- new_order_items.each do |order_item|
- order_item.run_callbacks(:save) { true }
- end
-
self.item_count = self.order_items.count
self.save!
@@ -199,7 +186,7 @@ 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
@@ -419,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 e696bf5a..4ff895af 100755
--- a/app/models/order_item.rb
+++ b/app/models/order_item.rb
@@ -6,6 +6,8 @@ class OrderItem < ApplicationRecord
#Associations
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
diff --git a/app/models/order_queue_station.rb b/app/models/order_queue_station.rb
index da7be3c2..f650b807 100755
--- a/app/models/order_queue_station.rb
+++ b/app/models/order_queue_station.rb
@@ -15,15 +15,14 @@ class OrderQueueStation < ApplicationRecord
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
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}").pluck(:order_queue_station_id)
- oqs_stations = oqs_stations.select { |s| oqs_by_zones.include? s.id }
+ oqs_stations = dining.order_queue_stations
+ else
+ oqs_stations = OrderQueueStation.active
end
assigned_order_items = []
@@ -31,12 +30,12 @@ class OrderQueueStation < ApplicationRecord
# ToDo per item per printer
oqs_stations.each do |oqs|
- oqs_order_items = nil
oqs_order_items = order_items.select { |i| JSON.parse(oqs.processing_items).include? i.item_code }
- assigned_order_items += oqs_order_items.map { |i| AssignedOrderItem.new({ order: order, item_code: i.item_code, instance_code: i.item_instance_code, order_queue_station: oqs, print_status: false, delivery_status: false }) }
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)
@@ -45,15 +44,8 @@ class OrderQueueStation < ApplicationRecord
end
end
end
- end
- if pdf_status.nil?
- ids = AssignedOrderItem.generate_ids(assigned_order_items.length)
- assigned_order_items.each_with_index do |assigned_order_item, index|
- assigned_order_item.assigned_order_item_id = ids[index]
- end
-
- AssignedOrderItem.import assigned_order_items, validate: false
+ 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
@@ -163,13 +155,10 @@ class OrderQueueStation < ApplicationRecord
else
move_print_pdf(change_to,current_user,table_id,order_items,oqs)
end
-
- AssignedOrderItem.where("order_id = ?", order.order_id).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?
# order_item = OrderItem.where("order_id='#{assigned_item.order_id}' AND item_instance_code='#{assigned_item.instance_code}'").first()
# print when complete click
@@ -184,8 +173,6 @@ class OrderQueueStation < ApplicationRecord
else
move_print_pdf(change_to,current_user,table_id,assigned_items,oqs)
end
-
- AssignedOrderItem.where("order_id = ?", order.order_id).update_all(print_status: true)
end
def move_print_pdf(change_to,current_user,change_from,order_items,oqs)
diff --git a/app/models/printer/order_queue_printer.rb b/app/models/printer/order_queue_printer.rb
index 9909539b..20da8fcd 100755
--- a/app/models/printer/order_queue_printer.rb
+++ b/app/models/printer/order_queue_printer.rb
@@ -23,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
@@ -55,7 +45,7 @@ class Printer::OrderQueuePrinter < Printer::PrinterWorker
end
shop = Shop.current_shop
- directory_name = 'public/orders_'+shop.shop_code
+ directory_name = "public/orders_#{shop.shop_code}"
Dir.mkdir(directory_name) unless File.exists?(directory_name)
# For Print Per Item
@@ -64,10 +54,10 @@ class Printer::OrderQueuePrinter < Printer::PrinterWorker
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
@@ -75,19 +65,10 @@ class Printer::OrderQueuePrinter < Printer::PrinterWorker
# 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
+ #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
@@ -95,33 +76,24 @@ class Printer::OrderQueuePrinter < Printer::PrinterWorker
else
order = print_query('order_summary', order_id)
- filename = directory_name + "/order_summary_#{order_id}" + ".pdf"
+ filename = directory_name + "/order_summary_#{order_id}.pdf"
# filename = "tmp/order_summary_#{order_id}" + ".pdf"
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
@@ -146,36 +118,10 @@ class Printer::OrderQueuePrinter < Printer::PrinterWorker
# check for item not to show
#if odi.price != 0
- pdf = print_settings.unique_code.constantize.new(print_settings,odi, print_status, options,oqs.use_alternate_name,before_updated_qty)
+ pdf = print_settings.unique_code.constantize.new(print_settings, odi, print_status, options, 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
- 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
- if oqs.print_copy
#no print in cloud server
if ENV["SERVER_MODE"] != "cloud"
self.print(filename, oqs.printer_name)
@@ -183,14 +129,22 @@ 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
@@ -206,14 +160,14 @@ class Printer::OrderQueuePrinter < Printer::PrinterWorker
.joins("left join menu_items as item ON item.item_code = order_items.item_code")
if type == "order_item"
- query.where("order_items.order_items_id = '#{ id }'")
+ query.where("order_items.order_items_id = ?", id)
.group("order_items.item_code")
elsif type == "order_summary"
- query.where("orders.order_id = '#{ id }'")
+ query.where("orders.order_id = ?", id)
.group("order_items.order_items_id")
else
# order summary for booking
- query.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 39cbb431..4795be34 100755
--- a/app/models/printer/printer_worker.rb
+++ b/app/models/printer/printer_worker.rb
@@ -37,21 +37,22 @@ class Printer::PrinterWorker
Cups.default_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?
- # (1..copy).each do
- # page = Cups::PrintJob.new(file_path, printer_destination)
- # page.print
- # end
- # end
+ 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
+
+ copy = self.print_copies
+ #Print only when printer information is not null
+ if !self.printer_destination.nil?
+ (1..copy).each do
+ page = Cups::PrintJob.new(file_path, printer_destination)
+ page.print
+ end
+ end
end
end
diff --git a/app/models/product.rb b/app/models/product.rb
index 5d1a5fe6..69037e2a 100755
--- a/app/models/product.rb
+++ b/app/models/product.rb
@@ -14,8 +14,8 @@ class Product < ApplicationRecord
account_id: account_id,
item_code: item_code,
item_instance_code: item_code,
- name: item_name || '',
- alt_name: item_name || '',
+ name: "#{item_name}",
+ alt_name: "#{item_name}",
price: price,
promotion_price: 0,
is_on_promotion: 0,
diff --git a/app/models/sale.rb b/app/models/sale.rb
index 720c815a..7ce2f5ad 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
@@ -858,11 +788,15 @@ def self.daily_sales_list(from,to)
daily_total = connection.select_all("SELECT
IFNULL(SUM(case when (sale_status='completed') then grand_total else 0 end),0) as grand_total,
+ IFNULL(SUM(case when (sale_status='completed') then grand_total else 0 end),0) - (IFNULL(SUM(case when (sale_status='completed') then total_discount else 0 end),0)) as total_sale,
IFNULL(SUM(case when (sale_status='completed') then old_grand_total else 0 end),0) as old_grand_total,
IFNULL(SUM(case when (sale_status='completed') then total_discount else 0 end),0) as total_discount,
IFNULL(SUM(case when (sale_status='completed') then amount_changed else 0 end),0) as total_change_amount,
IFNULL(SUM(case when (sale_status='void') then grand_total else 0 end),0) as void_amount,
IFNULL(SUM(case when (sale_status='completed') then rounding_adjustment else 0 end),0) as rounding_adj,
+ IFNULL(SUM(case when (sale_status='completed') then grand_total else 0 end),0) / 21 as tax,
+ (IFNULL(SUM(case when (sale_status='completed') then grand_total else 0 end),0))-(IFNULL(SUM(case when (sale_status='completed') then grand_total else 0 end),0) / 21) as net_sale,
+ SUM(grand_total + total_discount) as gross_sale,
CAST((CONVERT_TZ(receipt_date,'+00:00','+06:30')) AS DATE) as sale_date,
SUM(kbzpay_amount) as kbzpay_amount,
SUM(mpu_amount) as mpu_amount,
@@ -1126,7 +1060,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 = ''
@@ -1138,8 +1072,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()
@@ -1296,7 +1228,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)
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 631ede89..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)
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,32 +757,16 @@ class SalePayment < ApplicationRecord
end
def table_update_status(sale_obj)
- status = true
- sale_count = 0
- if booking = sale_obj.bookings[0]
- if booking.dining_facility_id.to_i > 0
+ 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 Booking.left_joins(:sale).where(dining_facility_id: booking.dining_facility_id).where.not(booking_status: 'moved').where("sales.sale_status NOT IN ('completed', 'void', 'spoile', 'waste') OR sales.sale_status IS NULL").exists?
- status = false
+ if !table.current_bookings.exists?
+ puts "Update staus 3"
+ table.update_attributes(status: "available")
end
-
- if status
- 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
diff --git a/app/models/seed_generator.rb b/app/models/seed_generator.rb
index b8224377..6717eabd 100755
--- a/app/models/seed_generator.rb
+++ b/app/models/seed_generator.rb
@@ -3,28 +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 shop = Shop.current_shop
+ prefix << shop.shop_code
+ end
- padding_len = 15 - prefix.length
- saleOrderId = prefix +"-"+ cur_val.to_s.to_s.rjust(padding_len,'0')
- return saleOrderId
+ seed = self.update_seed(model_name)
+ length = 15 - prefix.length
+ prefix + seed.to_s.rjust(length, '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#{prefix}"
+ 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')}" }
+ (start..stop).map { |c| prefix + c.to_s.rjust(length, '0') }
end
def self.sync_seed_generator_records(seed_generators)
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/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/views/api/restaurant/menu/_menu_item.json.jbuilder b/app/views/api/restaurant/menu/_menu_item.json.jbuilder
index 4f283e2c..1ac16ebc 100755
--- a/app/views/api/restaurant/menu/_menu_item.json.jbuilder
+++ b/app/views/api/restaurant/menu/_menu_item.json.jbuilder
@@ -6,21 +6,21 @@ if item.is_available
attr_format = []
# Format for attributes json
if item.item_attributes.count > 0
- item_attributes = @item_attributes.select{ |x| item.item_attributes.include?(x.id.to_s) }
- attr_format = item_attributes.group_by {|att| att.attribute_type }.map { |type, values| {type: type, values: values.map(&:name)} }
+ 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_options = @item_options.select{ |x| item.item_options.include?(x.id.to_s) }
- opt_format = item_options.group_by {|opt| opt.option_type }.map { |type, values| {type: type, values: values.map(&:name)} }
+ 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?
@@ -44,7 +44,7 @@ if item.is_available
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.map { |i| {id: i.id} }
+ json.instances its.menu_item_instances.map { |i| {id: i.id} }
end
json.attributes attr_format
@@ -64,7 +64,8 @@ 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.select{ |x| item.item_attributes.include?(x.id) }.pluck(:name)
+ item_attributes = is.item_attributes.map(&:to_s)
+ instance_attr = @item_attributes.select{ |x| item_attributes.include?(x.id.to_s) }.pluck(:name)
json.id is.id
json.code is.item_instance_code
diff --git a/app/views/origami/addorders/_menu_item.json.jbuilder b/app/views/origami/addorders/_menu_item.json.jbuilder
index 2768fa9c..d6b72535 100755
--- a/app/views/origami/addorders/_menu_item.json.jbuilder
+++ b/app/views/origami/addorders/_menu_item.json.jbuilder
@@ -31,15 +31,13 @@ json.is_sub_item item.is_sub_item
json.unit item.unit
# Item Sets of Menu Item
-json.item_sets item.item_sets.includes(:menu_item_instances) do |its|
+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
+ json.instances its.menu_item_instances.map { |i| {id: i.id} }
end
json.attributes attr_format
diff --git a/app/views/origami/addorders/detail.html.erb b/app/views/origami/addorders/detail.html.erb
index daa12b33..27d13860 100644
--- a/app/views/origami/addorders/detail.html.erb
+++ b/app/views/origami/addorders/detail.html.erb
@@ -10,6 +10,8 @@
+
+
@@ -259,19 +261,28 @@
+
-
diff --git a/app/views/settings/tables/_form.html.erb b/app/views/settings/tables/_form.html.erb
index 7bbd318e..44218560 100755
--- a/app/views/settings/tables/_form.html.erb
+++ b/app/views/settings/tables/_form.html.erb
@@ -11,14 +11,14 @@
<%= f.input :seater %>
<%= f.input :order_by %>
<%= f.input :is_active %>
- <% if @settings_table.dining_charges.length == 0 %>
+ <% if @settings_table.dining_charge.nil? %>
<% if @settings_table.id != nil %>
<%= link_to 'Add For Extra Charges', new_settings_zone_table_dining_charge_path(@zone,@settings_table),:class => 'btn bg-deep-purple' %>
<% end %>
<% else %>
- <% @settings_table.dining_charges.each do |dc| %>
+ <% dc = @settings_table.dining_charge %>
Dining Charge
@@ -48,7 +48,6 @@
- <% end %>
<% end %>
@@ -64,7 +63,7 @@
view_headline <%= t("views.right_panel.header.page_detail") %>
- 1) <%= t("views.right_panel.detail.name") %> - <%= t("views.right_panel.detail.write_txt") %> <%= t("views.right_panel.detail.table_txt") %> <%= t("views.right_panel.detail.name_txt2") %>
+ 1) <%= t("views.right_panel.detail.name") %> - <%= t("views.right_panel.detail.write_txt") %> <%= t("views.right_panel.detail.table_txt") %> <%= t("views.right_panel.detail.name_txt2") %>
2) <%= t("views.right_panel.detail.status") %> - <%= t("views.right_panel.detail.write_txt") %> <%= t("views.right_panel.detail.status_txt") %>
3) <%= t("views.right_panel.detail.seater") %> - <%= t("views.right_panel.detail.write_txt") %> <%= t("views.right_panel.detail.seat_txt") %> <%= t("views.right_panel.detail.for") %> <%= t("views.right_panel.detail.table_txt") %>
4) <%= t("views.right_panel.detail.order_by") %> - <%= t("views.right_panel.detail.write_txt") %> <%= t("views.right_panel.detail.order_txt") %> <%= t("views.right_panel.detail.for") %> <%= t("views.right_panel.detail.table_txt") %>
@@ -81,8 +80,6 @@
2) <%= t("views.right_panel.button.back") %> - <%= t("views.right_panel.detail.back_txt") %> <%= t("views.right_panel.detail.zone_txt") %>
-
+
-
-
diff --git a/app/views/settings/tables/show.html.erb b/app/views/settings/tables/show.html.erb
index 47f896bd..a7b2a474 100755
--- a/app/views/settings/tables/show.html.erb
+++ b/app/views/settings/tables/show.html.erb
@@ -53,43 +53,42 @@
Are you sure you want to delete this row ?
- This action can't be undo.
-
+ This action can't be undo.
+
- <% @table.dining_charges.each do |dc| %>
-
-
-
Dining Charge
-
-
- | Item Code |
- Unit Price |
- Charge Type |
- Free Time |
- Charges Block |
- Time Rounding |
- Actions |
-
-
-
- | <%= dc.item_code %> |
- <%= dc.unit_price %> |
- <%= dc.charge_type %> |
- <%= (dc.minimum_free_time).utc.strftime("%H:%M") %> |
- <%= (dc.charge_block).utc.strftime("%H:%M") %> |
- <%= dc.time_rounding %> |
- <%= link_to 'Edit Charges', edit_settings_zone_table_dining_charge_path(@zone,@settings_table,dc),:class => 'btn bg-deep-purple' %>
-
- |
-
-
-
-
+ <% dc = @table.dining_charge %>
+
+
+
Dining Charge
+
+
+ | Item Code |
+ Unit Price |
+ Charge Type |
+ Free Time |
+ Charges Block |
+ Time Rounding |
+ Actions |
+
+
+
+ | <%= dc.item_code %> |
+ <%= dc.unit_price %> |
+ <%= dc.charge_type %> |
+ <%= (dc.minimum_free_time).utc.strftime("%H:%M") %> |
+ <%= (dc.charge_block).utc.strftime("%H:%M") %> |
+ <%= dc.time_rounding %> |
+ <%= link_to 'Edit Charges', edit_settings_zone_table_dining_charge_path(@zone,@settings_table,dc),:class => 'btn bg-deep-purple' %>
+
+ |
+
+
+
- <% end %>
+
@@ -98,7 +97,7 @@
view_headline <%= t("views.right_panel.header.page_detail") %>
- 1) <%= t("views.right_panel.detail.name") %> - <%= t("views.right_panel.detail.table_txt") %> <%= t("views.right_panel.detail.name_txt") %> <%= t("views.right_panel.detail.table_txt") %>
+ 1) <%= t("views.right_panel.detail.name") %> - <%= t("views.right_panel.detail.table_txt") %> <%= t("views.right_panel.detail.name_txt") %> <%= t("views.right_panel.detail.table_txt") %>
2) <%= t("views.right_panel.detail.status") %> - <%= t("views.right_panel.detail.table_txt") %> <%= t("views.right_panel.detail.status_txt") %>
3) <%= t("views.right_panel.detail.seater") %> - <%= t("views.right_panel.detail.seat_txt") %> <%= t("views.right_panel.detail.for") %> <%= t("views.right_panel.detail.table_txt") %>
4) <%= t("views.right_panel.detail.order_by") %> - <%= t("views.right_panel.detail.order_txt") %> <%= t("views.right_panel.detail.for") %> <%= t("views.right_panel.detail.table_txt") %>
@@ -118,8 +117,6 @@
2) <%= t("views.right_panel.button.back") %> - <%= t("views.right_panel.detail.back_txt") %> <%= t("views.right_panel.detail.zone_txt") %>
-
+
-
-
diff --git a/config/deploy.rb b/config/deploy.rb
index 05bba77d..851b4551 100644
--- a/config/deploy.rb
+++ b/config/deploy.rb
@@ -28,9 +28,24 @@ set :linked_dirs, %w{log tmp/pids tmp/puma tmp/cache tmp/sockets vendor/bundle p
set :tests, []
set :pty, true
-set :puma_jungle_conf, '/etc/puma.conf'
-set :puma_run_path, '/usr/local/bin/run-puma'
+#set :puma_state, "#{shared_path}/tmp/pids/puma.state"
+#set :puma_pid, "#{shared_path}/tmp/pids/puma.pid"
set :puma_bind, %w(tcp://0.0.0.0:9393)
+#set :puma_conf, "#{shared_path}/puma.rb"
+#set :puma_access_log, "#{shared_path}/log/puma_access.log"
+#set :puma_error_log, "#{shared_path}/log/puma_error.log"
+#set :puma_role, :app
+set :puma_env, fetch(:rack_env, fetch(:rails_env, 'production'))
+set :puma_threads, [0, 16]
+set :puma_workers, 2
+#set :puma_worker_timeout, nil
+#set :puma_init_active_record, false
+#set :puma_preload_app, false
+#set :puma_daemonize, false
+#set :puma_plugins, [] #accept array of plugins
+#set :puma_tag, fetch(:application)
+#set :puma_restart_command, 'bundle exec puma'
+
#set :enable_ssl, true
diff --git a/config/deploy/production.rb b/config/deploy/production.rb
index bcca8f23..4a159049 100644
--- a/config/deploy/production.rb
+++ b/config/deploy/production.rb
@@ -9,11 +9,11 @@
# set :rails_env, :production
set :stage, :production
-set :server_name, "a.c2l.shop"
+set :server_name, "doemal.app"
set :branch, "r-1902001-01"
set :full_app_name, "#{fetch(:application)}_#{fetch(:stage)}"
-server '167.71.194.57', user: 'deploy', roles: %w{web app db}, primary: true
+server '178.128.58.251', user: 'deploy', roles: %w{web app db}, primary: true
set :deploy_to, "/home/#{fetch(:deploy_user)}/apps/#{fetch(:full_app_name)}"
set :rbenv_ruby, '2.6.5'
diff --git a/config/deploy/shared/.rbenv-vars b/config/deploy/shared/.rbenv-vars
new file mode 100644
index 00000000..4589226b
--- /dev/null
+++ b/config/deploy/shared/.rbenv-vars
@@ -0,0 +1 @@
+SECRET_KEY_BASE=33c956cc0e41623bf4e0aedbb16061fa7460a993452b58311d07009782dc242925a52dbb79b506c35308e65cda7cb07b014f78daea0a7ea883a535dc14b33a09
\ No newline at end of file
diff --git a/config/deploy/shared/database.yml.erb b/config/deploy/shared/database.yml.erb
new file mode 100644
index 00000000..7303b1cd
--- /dev/null
+++ b/config/deploy/shared/database.yml.erb
@@ -0,0 +1,6 @@
+production:
+ adapter: postgresql
+ host: localhost
+ database: iticket
+ username: wathon
+ password: root
diff --git a/config/deploy/shared/log_rotation.erb b/config/deploy/shared/log_rotation.erb
new file mode 100644
index 00000000..7507de18
--- /dev/null
+++ b/config/deploy/shared/log_rotation.erb
@@ -0,0 +1,11 @@
+<%= fetch(:deploy_to) %>/shared/log/*.log {
+ daily
+ missingok
+ rotate 52
+ compress
+ delaycompress
+ notifempty
+ sharedscripts
+ endscript
+ copytruncate
+}
diff --git a/config/deploy/shared/monit.conf.erb b/config/deploy/shared/monit.conf.erb
new file mode 100644
index 00000000..1689f9e0
--- /dev/null
+++ b/config/deploy/shared/monit.conf.erb
@@ -0,0 +1,2 @@
+<% application = fetch(:application) %>
+set mail-format { subject: <%= "#{fetch(:full_app_name)} - #{fetch(:rails_env)}" %> $SERVICE $EVENT at $DATE }
diff --git a/config/deploy/shared/nginx.conf.erb b/config/deploy/shared/nginx.conf.erb
new file mode 100644
index 00000000..c888b6ae
--- /dev/null
+++ b/config/deploy/shared/nginx.conf.erb
@@ -0,0 +1,40 @@
+server {
+ server_name <%= fetch(:server_name) %>;
+ listen 80;
+ passenger_enabled on;
+ rails_env production;
+ root <%= fetch(:deploy_to) %>/current/public;
+
+ location ^~ /assets/ {
+ gzip_static on;
+ expires max;
+ add_header Cache-Control public;
+ }
+
+ error_page 500 502 503 504 /500.html;
+ client_max_body_size 4G;
+ keepalive_timeout 10;
+}
+
+<% if fetch(:enable_ssl) %>
+server {
+ server_name <%= fetch(:server_name) %>;
+ listen 443;
+ passenger_enabled on;
+ rails_env production;
+ root <%= fetch(:deploy_to) %>/current/public;
+
+ location ^~ /assets/ {
+ gzip_static on;
+ expires max;
+ add_header Cache-Control public;
+ }
+
+ error_page 500 502 503 504 /500.html;
+ client_max_body_size 4G;
+ keepalive_timeout 10;
+ ssl on;
+ ssl_certificate <%= fetch(:deploy_to) %>/shared/ssl_cert.crt;
+ ssl_certificate_key <%= fetch(:deploy_to) %>/shared/ssl_private_key.key;
+}
+<% end %>
diff --git a/config/deploy/shared/redis.yml.erb b/config/deploy/shared/redis.yml.erb
new file mode 100644
index 00000000..8a1f2d4a
--- /dev/null
+++ b/config/deploy/shared/redis.yml.erb
@@ -0,0 +1,4 @@
+<%= fetch(:rails_env) %>:
+ host: data.myapp.com
+ port: 6379
+ db: 0
\ No newline at end of file
diff --git a/config/deploy/shared/sidekiq.yml.erb b/config/deploy/shared/sidekiq.yml.erb
new file mode 100644
index 00000000..707ebb27
--- /dev/null
+++ b/config/deploy/shared/sidekiq.yml.erb
@@ -0,0 +1,2 @@
+<%= fetch(:rails_env) %>:
+ :concurrency: <%= fetch(:sidekiq_concurrency, 5) %>
\ No newline at end of file
diff --git a/config/deploy/shared/sidekiq_init.sh.erb b/config/deploy/shared/sidekiq_init.sh.erb
new file mode 100644
index 00000000..1f667f90
--- /dev/null
+++ b/config/deploy/shared/sidekiq_init.sh.erb
@@ -0,0 +1,48 @@
+#!/bin/sh
+set -e
+
+APP_ROOT=<%= current_path %>
+PID=$APP_ROOT/tmp/pids/sidekiq.pid
+CMD="cd $APP_ROOT; RAILS_ENV=<%= "#{fetch(:rails_env)}" %> nohup bundle exec sidekiq -e <%= "#{fetch(:rails_env)}" %> -C $APP_ROOT/config/sidekiq.yml -i 0 -P $PID >> $APP_ROOT/log/sidekiq.log 2>&1 &"
+STOP_CMD="cd $APP_ROOT; RAILS_ENV=<%= "#{fetch(:rails_env)}" %> bundle exec sidekiqctl stop $APP_ROOT/tmp/pids/sidekiq.pid 10"
+AS_USER=<%= fetch(:deploy_user) %>
+
+run () {
+ if [ "$(id -un)" = "$AS_USER" ]; then
+ eval $1
+ else
+ su -c "$1" - $AS_USER
+ fi
+}
+
+sig () {
+ test -s "$PID" && kill -$1 `cat $PID`
+}
+
+case "$1" in
+ start)
+ sig 0 && echo >&2 "Already Running" && exit 0
+ run "$CMD"
+ ;;
+ stop)
+ if test -s "$PID" && kill -0 `cat $PID`
+ then
+ echo "stopping...."
+ run "$STOP_CMD"
+ else
+ echo "not running"
+ fi
+ ;;
+ restart|reload)
+ if test -s "$PID" && kill -0 `cat $PID`
+ then
+ echo "stopping...."
+ run "$STOP_CMD"
+ fi
+ run "$CMD"
+ ;;
+ *)
+ echo >&2 "Usage: $0 "
+ exit 1
+ ;;
+esac
diff --git a/config/puma.rb b/config/puma_backup.rb
similarity index 100%
rename from config/puma.rb
rename to config/puma_backup.rb
diff --git a/nweni.crt b/nweni.crt
deleted file mode 100755
index a6e4d152..00000000
--- a/nweni.crt
+++ /dev/null
@@ -1,24 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIEBzCCAu+gAwIBAgIJAOMNKpr3UCfFMA0GCSqGSIb3DQEBCwUAMIGiMQswCQYD
-VQQGEwJNTTEPMA0GA1UECAwGWWFuZ29uMQ8wDQYDVQQHDAZZYW5nb24xGTAXBgNV
-BAoMEENvZGUyTEFCIFB0ZSBMdGQxFDASBgNVBAsMC0RldmVsb3BtZW50MR0wGwYD
-VQQDDBRDb2RlMkxBQiBDZXJ0aWZpY2F0ZTEhMB8GCSqGSIb3DQEJARYSaGVsbG9A
-Y29kZTJsYWIuY29tMB4XDTE5MTIwNDA1NTgwMFoXDTIxMDQxNzA1NTgwMFowgZQx
-CzAJBgNVBAYTAk1NMQ8wDQYDVQQIDAZZYW5nb24xDzANBgNVBAcMBllhbmdvbjEZ
-MBcGA1UECgwQQ29kZTJMQUIgUHRlIEx0ZDEUMBIGA1UECwwLRGV2ZWxvcG1lbnQx
-ITAfBgkqhkiG9w0BCQEWEmhlbGxvQGNvZGUybGFiLmNvbTEPMA0GA1UEAwwGTndl
-IE5pMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlzBofZOWVWCDRJ3Y
-8NSR+FJg1/KMcVXhJbF5xuEz5K4+b8/VJG6CPE6O9qnqMhFd+Fp/f8GReCiP3Xb9
-dp8E5k6p/sTU18rDgurWm/DAhOXjq85EiNHitsLrGmLxYxHq2nxXFYuhYcM6lP0L
-SXfgUuwMNs3HpNFo7Fk21M7XKzdZdJPB35s3wZVWmHPon8i/oX8PHB8/IrhPGU7P
-Q33WZburEXK78jFbTGfavGSd5of17wIeI4saOpcAt7yz3rxa3tMb+FEZdJ1gxMrJ
-EX8A/qUJ7MYyc4JV+ssKcom8iQcLzdBlNkEWDZpAglmCe6jF7v7QrzPZDDFDLc3A
-L4W/NwIDAQABo0wwSjAfBgNVHSMEGDAWgBQkFPQitKTJkB0Xw/L/CbmtGTFv5TAJ
-BgNVHRMEAjAAMAsGA1UdDwQEAwIE8DAPBgNVHREECDAGhwTAqAHyMA0GCSqGSIb3
-DQEBCwUAA4IBAQCIFcpDdcIFxBnrOYjuadtL4X+iUT2UK1UMox/X2kz+agdpOVET
-VRTMcGOFta/iecEAmI2BPl+TP+qNO2xAfXKbU6vrD0lsshB6PlUxGSxnlFTDW5Df
-SZuiMb3J6AT9vdp/U1CwLGthrvmWyjXvYYKbEb9LIqKOVm0WVj8drhnGxAq0Ie6k
-OrT76+8gjzYkR8HJ8v3bXijkeSMMTQxD+9K/wikoyaXtKV7QPjwjnKnYfOHpgvql
-+lIF5S16FIGTxedX8qsvrF/P7/Z657riqZGaW9Nfm7j0kDS9tEWKBk+fW0zw/sYw
-BRC3M+delv19ae//Ia0sIL2vNEB43HaXxNbK
------END CERTIFICATE-----
diff --git a/nweni.key b/nweni.key
deleted file mode 100755
index 610d33cf..00000000
--- a/nweni.key
+++ /dev/null
@@ -1,28 +0,0 @@
------BEGIN PRIVATE KEY-----
-MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCXMGh9k5ZVYINE
-ndjw1JH4UmDX8oxxVeElsXnG4TPkrj5vz9UkboI8To72qeoyEV34Wn9/wZF4KI/d
-dv12nwTmTqn+xNTXysOC6tab8MCE5eOrzkSI0eK2wusaYvFjEerafFcVi6FhwzqU
-/QtJd+BS7Aw2zcek0WjsWTbUztcrN1l0k8HfmzfBlVaYc+ifyL+hfw8cHz8iuE8Z
-Ts9DfdZlu6sRcrvyMVtMZ9q8ZJ3mh/XvAh4jixo6lwC3vLPevFre0xv4URl0nWDE
-yskRfwD+pQnsxjJzglX6ywpyibyJBwvN0GU2QRYNmkCCWYJ7qMXu/tCvM9kMMUMt
-zcAvhb83AgMBAAECggEAN3cn7mH1tg65ObQbAYdKoeo+4xp1kaKq/bQVc/PsoMmX
-2FdL35i3KL69ThrZ81JRwioZOlpeLtHaranYpOsD1iYn0XKOjzgw79eNshnp1xer
-pbz/gZ5WaSwrKjwASJMrMMqK/DmElCQWWtBWkrZq0qEMfhKSWpIExyiXqAzV/WE5
-jc+CllMGWY4vmTscWyKKBvqjaLJ7A1z+cRZzrPwmQKcZ2DQ/DVzjcTmh+W0CGPE9
-gVL+mZ5rWbCbL43RWHKt/ewwrNs+io8zPWaOBAobUfGYa/IhCSLktmDSyjK/tUY3
-CqW2Lqc+07I/cb4kQkBfIAUg4mZCTBwh80puTPGY4QKBgQDINGD2Yn6CpY1viQiR
-rEWKfyYBEchI+um68Vz3l7d7nEOeO+OmPivBL1UCewf/ux3YqKu4HTrYd5VUVbxN
-141k5Hv9XCf6Fn/wcSptJLK9bSkWh08+LcLS2/K7rnF57T2v1YIsn1zr0E6rKIEE
-XRuodMjQvkex/KVrbXjK83JpJwKBgQDBUwMUK8IOrnYiq/EkRB2roCyLNbrUEEaU
-QvrlOztOI8ctf236i51q2708aqSGrnjbQ6uXOHwX5O4i6Psjw+llPSF1wpE9tyGw
-dhsBFYYMxnetXIPLnfxE2bnKNsN5dDtI/JwcKA5TB+3BXkIYbkCbs0z0/WDtjJZE
-IOw40lMjcQKBgGvhpbo+2vMlqLBIhGCTFyoJV/5NicKhyp8c/r7Ad3PZgapblVF4
-wPUpv0JF78qDFxMv2NCul44b6lD2njDIDX4njRS6uyQNScXUBUuo8dQXZYOpSC82
-U3xyXzt5Rdaw24PLpojLGzRLHIkom1UxovzEaY3qaxHjFXRtGiEqzCUTAoGAT4ip
-UZkXAxc/PtBiKrtjQYJqEPOP40K25rQPqFMP+Pu7K7qrMlJR9u5kEgEFousQiZRz
-eYkhdGsYlYAoIfSthpr5swrS2gMHdyN/xJhoR8U24zmWdySN7n1sdAbHsKXi5goW
-53aLPhma9NykcIybQ/MmC/xZ7iDSiUDKLi5JSeECgYBf5aSPelr/ShEKlxz4BgcD
-XcMNzTZXNJTNgMHvLorlUG0Ev6C95SlwzJd0aiTLpm2WtO9Uy/AtueVQc02En3+1
-E2eX+cTuYD+eAFjxdvAaOKwkPbtk8xAlcQ34iRdcXvLM+f6UpXk+8ytVvPc5dmF7
-kM3zuXJ66D8u1IV6G0asyA==
------END PRIVATE KEY-----