This commit is contained in:
Myat Zin Wai Maw
2020-01-14 13:31:54 +06:30
226 changed files with 3427 additions and 3740 deletions

View File

@@ -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

View File

@@ -36,7 +36,6 @@ class AssignedOrderItem < ApplicationRecord
assigned_order_item.order_queue_station = order_queue_station
assigned_order_item.print_status = false
assigned_order_item.delivery_status = false
assigned_order_item.shop_code =order.shop_code
assigned_order_item.save!
end
@@ -63,6 +62,11 @@ class AssignedOrderItem < ApplicationRecord
return order_item
end
protected
def self.generate_ids(count = 1)
SeedGenerator.generate_ids(self.name, "AOI", count)
end
private
def generate_custom_id
if self.assigned_order_item_id.nil?

View File

@@ -6,13 +6,62 @@ class Booking < ApplicationRecord
belongs_to :dining_facility, :optional => true
belongs_to :sale, :optional => true
has_one :cashier_terminal_by_dining_facility, through: :dining_facility, source: :cashier_terminal
has_one :current_shift_by_dining_facility, through: :dining_facility, source: :current_shift
has_many :booking_orders
has_many :orders, :through => :booking_orders
has_many :order_items, :through => :orders
has_many :order_items, :through => :orders do
def to_sale_items
sale_items = []
proxy_association.load_target.select(&:order_items_id).each do |order_item|
menu_category = order_item.menu_category || OpenStruct.new(name: 'Product', code: '') #get menu category for menu items
sale_items << SaleItem.new({
menu_category_name: menu_category.name,
menu_category_code: menu_category.code,
product_name: order_item.item_name,
product_code: order_item.item_code,
product_alt_name: order_item.alt_name,
account_id: order_item.account_id,
is_taxable: order_item.taxable,
item_instance_code: order_item.item_instance_code,
qty: order_item.qty,
unit_price: order_item.price,
price: order_item.qty * order_item.price,
taxable_price: order_item.qty * order_item.price,
status: order_item.remark
})
if order_item.set_menu_items
JSON.parse(order_item.set_menu_items).each do |item|
instance = MenuItemInstance.find_by_item_instance_code(item["item_instance_code"])
menu_item = instance.menu_item
menu_category = menu_item.menu_category #get menu category for menu items
sale_items << SaleItem.new({
menu_category_name: menu_category.name,
menu_category_code: menu_category.code,
product_name: instance.item_instance_name,
product_code: menu_item.item_code,
product_alt_name: menu_item.alt_name,
account_id: menu_item.account_id,
is_taxable: menu_item.taxable,
item_instance_code: item["item_instance_code"],
qty: item["quantity"],
unit_price: item["price"],
price: item["quantity"].to_f * item["price"].to_f,
taxable_price: item["quantity"].to_f * item["price"].to_f
})
end
end
end
sale_items
end
end
scope :active, -> {where("booking_status != 'moved'")}
scope :today, -> {where("created_at >= #{Time.now.utc}")}
scope :shop, -> { where("bookings.shop_code=?",Shop.current_shop.shop_code) }
scope :assign, -> { where(booking_status: 'assign')}
scope :within_time_limit, -> { where(checkin_at: Lookup.get_checkin_time_limit.hours.ago..DateTime::Infinity.new) }
def self.sync_booking_records(bookings)
if !bookings.nil?
@@ -86,7 +135,7 @@ class Booking < ApplicationRecord
joins(" LEFT JOIN dining_facilities df ON df.id=bookings.dining_facility_id")
.where("booking_id LIKE ? OR checkin_by LIKE ? OR booking_status LIKE? OR checkout_by LIKE? OR sale_id ='#{filter}' OR df.name LIKE ?","%#{filter}%","%#{filter}%","%#{filter}%","%#{filter}%","%#{filter}%")
end
.shop.order("sale_id DESC")
.order("sale_id DESC")
end
def self.get_sync_data(sale_id)

View File

@@ -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

View File

@@ -39,6 +39,14 @@ class Customer < ApplicationRecord
end
end
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")

View File

@@ -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
Rails.logger.info "Params not enough"
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

View File

@@ -1,13 +1,25 @@
class DiningFacility < ApplicationRecord
belongs_to :zone
has_many :dining_charges
has_many :in_juties
has_one :dining_charge
has_one :cashier_terminal_by_zone, foreign_key: "zone_id", primary_key: "zone_id"
has_one :cashier_terminal, through: :cashier_terminal_by_zone
has_one :current_shift, through: :cashier_terminal
has_many :order_queue_process_by_zones, foreign_key: "zone_id", primary_key: "zone_id"
has_many :order_queue_stations, -> { where(is_active: true) }, through: :order_queue_process_by_zones
has_many :bookings
has_many :current_bookings, -> { left_joins(:sale).assign.within_time_limit.merge(Booking.where(checkout_at: nil).or(Booking.merge(Sale.where(sale_status: ['new', nil])))) }, class_name: "Booking"
has_one :current_checkin_booking, -> { left_joins(:sale).assign.within_time_limit.merge(Sale.where(sale_status: nil)) }, class_name: "Booking"
has_one :current_checkout_booking, -> { left_joins(:sale).assign.within_time_limit.where.not(checkout_at: nil).merge(Sale.where(sale_status: 'new')) }, class_name: "Booking"
has_one :current_reserved_booking, -> { left_joins(:sale).assign.within_time_limit.where.not(reserved_at: nil).merge(Sale.where(sale_status: nil)) }, class_name: "Booking"
has_many :current_sales, -> { where(sale_status: 'new').merge(Booking.assign.within_time_limit) }, through: :bookings, class_name: "Sale", source: "sale"
TABLE_TYPE = "Table"
ROOM_TYPE = "Room"
default_scope { order('order_by asc') }
scope :shop, -> { where("shop_code=?",Shop.current_shop.shop_code) }
scope :active, -> {where(is_active: true)}
@@ -22,7 +34,7 @@ class DiningFacility < ApplicationRecord
end
def get_booking
booking = self.get_current_booking
booking = self.current_checkin_booking
if booking
if booking.dining_facility_id.to_i == self.id
if booking.booking_status == 'assign'
@@ -38,28 +50,10 @@ class DiningFacility < ApplicationRecord
Booking.where(dining_facility_id: self.id, booking_status: 'assign', checkout_at: nil).where("checkin_at > ?", checkin_time_lookup.hours.ago).first #and checkout_at is null
end
def get_moved_booking
checkin_time_lookup = Lookup.get_checkin_time_limit
Booking.where(dining_facility_id: self.id, booking_status: 'moved', checkout_at: nil).where("checkin_at > ?", checkin_time_lookup.hours.ago).first
end
def get_new_booking
# query for new
Booking.where(dining_facility_id: self.id, booking_status: 'assign', sale_id: nil, checkout_at: nil).first
end
def get_current_checkout_booking
checkin_time_lookup = Lookup.get_checkin_time_limit
Booking.where(dining_facility_id: self.id, booking_status: 'assign', checkout_at: nil).where.not(reserved_at: nil).where("checkin_at > ?", checkin_time_lookup.hours.ago).first
end
def get_checkout_booking
booking = self.get_current_checkout_booking
booking = self.current_reserved_booking
if booking
lookup_checkout_time = Lookup.where("shop_code='#{self.shop_code}'").collection_of("checkout_alert_time")
lookup_checkout_time = Lookup.collection_of("checkout_alert_time")
free_time_min = 0
if !lookup_checkout_time.empty?
now = Time.now.utc
@@ -97,11 +91,10 @@ class DiningFacility < ApplicationRecord
def self.get_checkin_booking
checkin_time_lookup = Lookup.get_checkin_time_limit
bookings = Booking.where(booking_status: 'assign', checkout_at: nil).where.not(reserved_at: nil).where("checkin_at > ?", checkin_time_lookup.hours.ago)
bookings = self.current_checkin_booking
arr_booking = Array.new
if bookings
lookup_checkout_time = Lookup.where("shop_code='#{self.shop_code}'").collection_of("checkout_alert_time")
lookup_checkout_time = Lookup.collection_of("checkout_alert_time")
free_time_min = 0
if !lookup_checkout_time.empty?
now = Time.now.utc

View File

@@ -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
@@ -41,7 +43,7 @@ class Employee < ApplicationRecord
if (session_token)
user = Employee.find_by_token_session(session_token)
expiry_time = login_expiry_time
if !user.session_expiry.nil?
if user && !user.session_expiry.nil?
if user && user.session_expiry.utc > DateTime.now.utc
#Extend the login time each time authenticatation take place
user.session_expiry = user.session_expiry.utc + expiry_time.minutes

View File

@@ -8,7 +8,7 @@ class InventoryDefinition < ApplicationRecord
logger.debug saleObj.sale_items.to_json
if !saleObj.nil?
saleObj.sale_items.each do |item|
found, inventory_definition = find_product_in_inventory(item,saleObj.shop_code)
found, inventory_definition = find_product_in_inventory(item)
if found
check_balance(item,inventory_definition)
end
@@ -25,8 +25,8 @@ class InventoryDefinition < ApplicationRecord
def self.find_product_in_inventory(item)
if product = InventoryDefinition.find_by_item_code_and_shop_code(item.item_instance_code,Shop.current_shop.shop_code)
if stock_check_item = StockCheckItem.find_by_item_code_and_shop_code(item.item_instance_code,Shop.current_shop.shop_code)
if product = InventoryDefinition.find_by_item_code(item.item_instance_code)
if stock_check_item = StockCheckItem.find_by_item_code(item.item_instance_code)
return true, product
end
end
@@ -34,7 +34,7 @@ class InventoryDefinition < ApplicationRecord
def self.check_balance(item, inventory_definition) # item => saleItemOBj
stock = StockJournal.where("shop_code='#{inventory_definition.shop_code}' and item_code=?", item.item_instance_code).order("id DESC").first
stock = StockJournal.where("item_code=?", item.item_instance_code).order("id DESC").first
unless stock.nil?
modify_balance(item, stock, inventory_definition)
else
@@ -83,21 +83,8 @@ class InventoryDefinition < ApplicationRecord
.order("mi.menu_category_id desc")
end
def self.get_by_category(shop,filter)
# THEN (SELECT min(balance) FROM stock_journals
# least_stock = "SELECT (CASE WHEN stock_journals.remark != 'out of stock'
# THEN (SELECT balance FROM stock_journals
# WHERE item_code = inventory_definitions.item_code AND remark != 'out of stock'
# ORDER BY created_at DESC LIMIT 1) ELSE 0 END)
# FROM stock_journals
# WHERE stock_journals.item_code = inventory_definitions.item_code
# ORDER BY stock_journals.created_at DESC LIMIT 1"
least_stock = "(SELECT
(SELECT balance FROM stock_journals WHERE item_code = inventory_definitions.item_code
ORDER BY id DESC LIMIT 1)
FROM stock_journals
WHERE stock_journals.item_code = inventory_definitions.item_code
ORDER BY stock_journals.created_at DESC LIMIT 1)"
def self.get_by_category(filter)
least_stock = StockJournal.select(:balance).joins("JOIN inventory_definitions ON stock_journals.item_code = inventory_definitions.item_code").order(:id => :desc).limit(1).to_sql
@inventory_definitions = InventoryDefinition.select("inventory_definitions.*,
(CASE WHEN sj.credit IS NULL THEN 0 ELSE sj.credit END) as credit,
@@ -112,7 +99,7 @@ class InventoryDefinition < ApplicationRecord
" JOIN menu_items mi ON mi.id = mii.menu_item_id" +
" JOIN menu_categories mc ON mc.id = mi.menu_category_id ")
.joins(" JOIN accounts acc ON acc.id = mi.account_id")
.where("inventory_definitions.shop_code='#{shop.shop_code}' and (inventory_definitions.item_code LIKE ? OR inventory_definitions.min_order_level LIKE ?
.where("(inventory_definitions.item_code LIKE ? OR inventory_definitions.min_order_level LIKE ?
OR inventory_definitions.max_stock_level LIKE ? OR sj.balance LIKE ? OR mi.name LIKE ?
OR mii.item_instance_name LIKE ? OR mc.name LIKE ?)","%#{filter}%","%#{filter}%","%#{filter}%",
"%#{filter}%","%#{filter}%","%#{filter}%","%#{filter}%")

View File

@@ -1,7 +1,6 @@
class Lookup < ApplicationRecord
has_many :accounts
belongs_to :shop
scope :number_formats, -> { where(lookup_type: 'number_format')}
@@ -26,12 +25,10 @@ class Lookup < ApplicationRecord
# Lookup.select("value, name").where("lookup_type = ?", lookup_type ).order("name asc").map { |r| [r.name, r.value] }
# end
def self.time_limit
TIME_LIMIT
end
def self.get_checkin_time_limit
return RequestStore[:checkin_time_limit] if RequestStore[:checkin_time_limit]
RequestStore[:checkin_time_limit] = Lookup.find_by_lookup_type('checkin_time_limit').value.to_i rescue time_limit
@@ -60,44 +57,42 @@ class Lookup < ApplicationRecord
end
def self.collection_of(type)
Lookup.select("name, value").where("lookup_type" => type ).map { |l| [l.name, l.value] }
Lookup.where("lookup_type" => type ).pluck("name, value")
end
def self.create_shift_sale_lookup(shop_code)
def self.create_shift_sale_lookup
@lookup = Lookup.new
@lookup.lookup_type = 'shift_sale_items'
@lookup.name = 'Shift Sale Items'
@lookup.value = 0
@lookup.shop_code = shop_code
@lookup.save
return @lookup
end
def self.create_reprint_receipt_lookup(shop_code)
def self.create_reprint_receipt_lookup
@lookup = Lookup.new
@lookup.lookup_type = 'reprint_receipt'
@lookup.name = 'Reprint Receipt in Report'
@lookup.value = 0
@lookup.shop_code = shop_code
@lookup.save
return @lookup
end
def self.save_shift_sale_items_settings(val,shop_code)
@lookup = Lookup.where("shop_code='#{shop_code}' and lookup_type=?", 'shift_sale_items').last
def self.save_shift_sale_items_settings(val)
@lookup = Lookup.where("lookup_type=?", 'shift_sale_items').last
if @lookup.nil?
@lookup = Lookup.create_shift_sale_lookup(shop_code)
@lookup = Lookup.create_shift_sale_lookup
end
@lookup.value = val
@lookup.save
end
def self.shift_sale_items_lookup_value(shop_code)
@lookup = Lookup.where("shop_code='#{shop_code}' and lookup_type=?", 'shift_sale_items').last
def self.shift_sale_items_lookup_value
@lookup = Lookup.where("lookup_type=?", 'shift_sale_items').last
if @lookup.nil?
@lookup = Lookup.create_shift_sale_lookup(shop_code)
@lookup = Lookup.create_shift_sale_lookup
end
return @lookup.value
end

View File

@@ -1,5 +1,5 @@
class MembershipSetting < ApplicationRecord
scope :active, -> { where(is_active: true) }
# MembershipSetting = MembershipSetting.find_by_id(1)
MembershipSetting = MembershipSetting.first
end

View File

@@ -8,7 +8,6 @@ class Menu < ApplicationRecord
#Default Scope to pull the active version only
default_scope { order("created_at asc") }
scope :active, -> {where("is_active = true")}
scope :shop, -> { where("menus.shop_code=?",Shop.current_shop.shop_code) }
def self.current_menu
today = DateTime.now
@@ -47,7 +46,7 @@ class Menu < ApplicationRecord
end
end
def self.import(file, created_by,shop)
def self.import(file, created_by)
status = ""
spreadsheet = open_spreadsheet(file)
if spreadsheet.sheets.count > 1
@@ -62,9 +61,9 @@ class Menu < ApplicationRecord
# Account.create(id:row["id"], title: row["title"],account_type: row["account_type"],discount: row["discount"],point: row["point"],bonus: row["bonus"],rebate: row["rebate"])
account = Account.find_by_id(row["id"])
if account
Account.create(title: row["title"],account_type: row["account_type"],discount: row["discount"],point: row["point"],bonus: row["bonus"],rebate: row["rebate"],shop_code: shop.shop_code)
Account.create(title: row["title"],account_type: row["account_type"],discount: row["discount"],point: row["point"],bonus: row["bonus"],rebate: row["rebate"])
else
Account.create(id:row["id"], title: row["title"],account_type: row["account_type"],discount: row["discount"],point: row["point"],bonus: row["bonus"],rebate: row["rebate"],shop_code: shop.shop_code)
Account.create(id:row["id"], title: row["title"],account_type: row["account_type"],discount: row["discount"],point: row["point"],bonus: row["bonus"],rebate: row["rebate"])
end
elsif sheet_name == "Item Set"
# ItemSet.create(id:row["id"], name: row[name], alt_name: row[alt_name], min_selectable_qty: row[min_selectable_qty], max_selectable_qty: row[max_selectable_qty])
@@ -93,9 +92,9 @@ class Menu < ApplicationRecord
elsif sheet_name == "Menu"
menu = Menu.find_by_id(row["id"])
if menu
Menu.create(name: row["name"], is_active: row["is_active"], is_ordering: row["is_ordering"], valid_days: row["valid_days"],valid_time_from: row["valid_time_from"], valid_time_to: row["valid_time_to"], created_by: row["created_by"],shop_code: shop.shop_code)
Menu.create(name: row["name"], is_active: row["is_active"], is_ordering: row["is_ordering"], valid_days: row["valid_days"],valid_time_from: row["valid_time_from"], valid_time_to: row["valid_time_to"], created_by: row["created_by"])
else
Menu.create(id:row["id"], name: row["name"], is_active: row["is_active"], is_ordering: row["is_ordering"], valid_days: row["valid_days"],valid_time_from: row["valid_time_from"], valid_time_to: row["valid_time_to"], created_by: row["created_by"],shop_code: shop.shop_code)
Menu.create(id:row["id"], name: row["name"], is_active: row["is_active"], is_ordering: row["is_ordering"], valid_days: row["valid_days"],valid_time_from: row["valid_time_from"], valid_time_to: row["valid_time_to"], created_by: row["created_by"])
end
elsif sheet_name == "Menu Category"
# MenuCategory.create(id:row["id"], menu_id: row["menu_id"], code: row["code"], name: row["name"], alt_name: row["alt_name"], order_by: row["order_by"], created_by: row["created_by"], menu_category_id: row["menu_category_id"], is_available: row["is_available"])
@@ -155,7 +154,7 @@ class Menu < ApplicationRecord
menu = sheet.row(1)[1]
is_ordering = sheet.row(1)[3]?sheet.row(1)[3]:0
imported_menu = Menu.create({name: menu, is_active: true, is_ordering: is_ordering, valid_days: "1,2,3,4,5,6,7",valid_time_from: "00:00:00", valid_time_to: "23:59:59", created_by: created_by,shop_code: shop.shop_code})
imported_menu = Menu.create({name: menu, is_active: true, is_ordering: is_ordering, valid_days: "1,2,3,4,5,6,7",valid_time_from: "00:00:00", valid_time_to: "23:59:59", created_by: created_by})
(4..sheet.last_row).each do |ii|
row = Hash[[sheet.row(3),sheet.row(ii)].transpose]
@@ -194,7 +193,7 @@ class Menu < ApplicationRecord
if !menu_itm
account = Account.find_by_title(row["Account"])
if account.nil?
account = Account.create({title: row["Account"], account_type: "0",shop_code: shop.shop_code})
account = Account.create({title: row["Account"], account_type: "0"})
end
image_path = ""

View File

@@ -31,26 +31,26 @@ class MenuItem < ApplicationRecord
# Work with item_code = item_instance_code
def self.search_by_item_code(item_code)
menu_item_hash = Hash.new
mt_instance = MenuItemInstance.find_by_item_instance_code(item_code)
if (!mt_instance.nil?)
menu_item = MenuItem.find(mt_instance.menu_item_id)
menu_item_hash[:type] = menu_item.type
menu_item_hash[:account_id] = menu_item.account_id
menu_item_hash[:item_code] = menu_item.item_code
menu_item_hash[:item_instance_code] = mt_instance.item_instance_code
menu_item_hash[:name] = menu_item.name.to_s + " - " + mt_instance.item_instance_name.to_s
menu_item_hash[:alt_name] = menu_item.alt_name.to_s # + " - " + mt_instance.item_instance_name.to_s
menu_item_hash[:price] = mt_instance.price
menu_item_hash[:promotion_price] = mt_instance.promotion_price
menu_item_hash[:is_on_promotion] = mt_instance.is_on_promotion
menu_item_hash[:is_available] = mt_instance.is_available
menu_item_hash[:taxable] = menu_item.taxable
return menu_item_hash
end
return nil
MenuItem.left_joins(:menu_item_instances => :menu_instance_item_sets)
.where(menu_item_instances: {item_instance_code: item_code})
.pluck(:type, :account_id, :item_code, :item_instance_code, :name, :alt_name, :item_instance_name, :price, :promotion_price, :is_on_promotion, "menu_item_instances.is_available", :taxable, :item_set_id)
.map { |type, account_id, item_code, item_instance_code, item_name, item_alt_name, item_instance_name, price, promotion_price, is_on_promotion, is_available, taxable, item_set_id|
name = item_instance_name if item_set_id
name ||= "#{item_name}#{' - ' + item_instance_name if item_instance_name.present?}"
{
type: type,
account_id: account_id,
item_code: item_code,
item_instance_code: item_instance_code,
name: "#{name}",
alt_name: "#{item_alt_name}",
price: price,
promotion_price: promotion_price,
is_on_promotion: is_on_promotion,
is_available: is_available,
taxable: taxable
}
}
end
def self.deleteRecursive(menu_item)

View File

@@ -26,25 +26,16 @@ class Order < ApplicationRecord
def generate
booking = nil
if self.new_booking
if self.table_id.to_i > 0
table_id = self.table_id
else
table_id = nil
end
#add extra time
if self.is_extra_time && self.extra_time
booking = Booking.create({:dining_facility_id => table_id,:type => "TableBooking",
:checkin_at => Time.now.utc,:checkout_at => Time.now.utc + self.extra_time.to_i,
:checkin_at => Time.now.utc, :checkout_at => Time.now.utc + self.extra_time.to_i,
:checkin_by => self.employee_name,
:booking_status => "assign",
:customer_id => self.customer_id,
:shop_code=>self.shop_code})
:booking_status => "assign" })
else
booking = Booking.create({:dining_facility_id => table_id,:type => "TableBooking",
:checkin_at => Time.now.utc, :checkin_by => self.employee_name,
:booking_status => "assign",
:customer_id => self.customer_id,
:shop_code=>self.shop_code })
:booking_status => "assign" })
end
#end extra time
@@ -54,7 +45,6 @@ class Order < ApplicationRecord
# table.status = "occupied"
# table.save
end
else
booking = Booking.find(self.booking_id)
#add extra time
@@ -74,7 +64,7 @@ class Order < ApplicationRecord
self.adding_line_items
#Add Order Table and Room relation afrer order creation
BookingOrder.create({:booking_id => booking.booking_id, :order => self})
booking.orders << self
#Send order to queue one it done!
# if self.source != "quick_service"
@@ -111,7 +101,7 @@ class Order < ApplicationRecord
self.adding_line_items
#Add Order Table and Room relation afrer order creation
BookingOrder.create({:booking_id => booking.booking_id, :order => self})
booking.orders << self
#Send order to queue one it done!
# if self.source != "quick_service"
@@ -122,7 +112,6 @@ class Order < ApplicationRecord
send_order_broadcast(booking)
return true, booking
end
return false
@@ -137,49 +126,36 @@ class Order < ApplicationRecord
def adding_line_items
if self.items
#re-order to
ordered_list = re_order_items(self.items)
items = re_order_items(self.items)
#loop to add all items to order
ordered_list.each do |item|
item_instance_codes = items.map { |i| i[:item_instance_code] }
menu_items = MenuItem.search_by_item_code(item_instance_codes)
menu_items += Product.search_by_product_code(item_instance_codes) if menu_items.length < item_instance_codes.length
menu_item = MenuItem.search_by_item_code(item[:item_instance_code])
# For Product while item code not in menu item
if menu_item.nil?
menu_item = Product.search_by_product_code(item[:item_instance_code])
end
#if (!menu_item.nil?)
# Rails.logger.debug menu_item
set_order_items = Array.new
##If menu Item set item - must add child items to order as well, where price is only take from menu_item
if (menu_item[:type] == "SetMenuItem")
if (item.include? 'sub_items') || (item.include? :sub_items)
item[:sub_items].each do |si|
# Retrive instance's Price
set_item = MenuItem.search_by_item_code(si[:item_instance_code])
set_order_items.push({"item_instance_code"=>si[:item_instance_code], "item_instance_name"=>set_item[:name], "quantity"=>si[:quantity], "price"=>set_item[:price], "options"=>si[:options]})
end
end
set_order_items = set_order_items.to_json
else
set_order_items = nil
items.each do |order_item|
menu_item = menu_items.find { |i| i[:item_instance_code].downcase == order_item[:item_instance_code].downcase }
sub_order_items = []
if order_item[:sub_items].length > 0
sub_menu_items = MenuItem.search_by_item_code(order_item[:sub_items].map { |i| i[:item_instance_code] })
order_item[:sub_items].each do |sub_order_item|
sub_menu_item = sub_menu_items.find { |i| i[:item_instance_code] == sub_order_item[:item_instance_code] }
sub_order_items << { item_instance_code: sub_order_item[:item_instance_code], item_instance_name: sub_menu_item[:name], quantity: sub_order_item[:quantity], price: sub_menu_item[:price], options: sub_order_item[:options] }
end
# not insert with price 0
# puts item[:price]
# puts item
# if(item[:price] != 0 )
# OrderItem.processs_item(menu_item[:item_code], menu_item[:name], menu_item[:account_id],
# item[:quantity],menu_item[:price], item[:options], set_order_items, self.id,
# self.employee_name)
# end
OrderItem.processs_item(menu_item[:item_code], item[:item_instance_code], menu_item[:name], menu_item[:alt_name], menu_item[:account_id],
item[:quantity],menu_item[:price], item[:options], set_order_items, self.id,
self.employee_name, menu_item[:taxable])
#end
end
sub_order_items = sub_order_items.to_json
self.order_items.build({
item_code: menu_item[:item_code],
item_instance_code: order_item[:item_instance_code],
item_name: menu_item[:name],
alt_name: menu_item[:alt_name],
account_id: menu_item[:account_id],
qty: order_item[:quantity],
price: menu_item[:price],
options: order_item[:options],
set_menu_items: sub_order_items,
item_order_by: employee_name,
taxable: menu_item[:taxable]
})
end
self.item_count = self.order_items.count
@@ -190,7 +166,6 @@ class Order < ApplicationRecord
self.errors.add(:order_items, :blank, message: "Order items cannot be blank")
return false
end
end
def update_items_status_to_billed(items)
@@ -211,72 +186,14 @@ class Order < ApplicationRecord
end
def default_values
self.customer = Customer.find(1) if self.customer_id.nil?
self.customer = Customer.walkin if self.customer_id.nil?
self.source = "emenu" if self.source.nil?
self.order_type = "dine-in" if self.order_type.nil?
end
protected
def re_order_items(form_items) #reorder inputs items as parents and child
parent_id = Array.new
parents = Array.new
parents_and_children_items = Array.new
new_items_list = Array.new
form_items.each do |parent|
if !parent[:parent_order_item_id].nil?
if (!parent_id.include?(parent[:parent_order_item_id]))
parent_id.push(parent[:parent_order_item_id])
end
end
end
Rails.logger.debug "Parent Id count -> " + parent_id.count.to_s
parent_id.each do |pid|
form_items.each do |item|
Rails.logger.debug "Adding - Parents -> " + pid.to_s + " - " + item[:order_item_id].to_s
if (pid == item[:order_item_id])
parents.push(item)
end
end
end
Rails.logger.debug "Parents count -> " + parents.count.to_s
parents.each do |parent|
children = Array.new
form_items.each do |item|
if (parent[:order_item_id] == item[:parent_order_item_id] )
children.push(item)
#Items to remove for new list
parents_and_children_items.push(item)
end
end
parent[:sub_items] = children
end
Rails.logger.debug "Parent/children Items to remove -> " + parents_and_children_items.count.to_s
#Remove process items
#c = a.reject{ |e| b.include? e }
new_items_list = form_items - parents_and_children_items
Rails.logger.debug "New list count -> " + new_items_list.count.to_s
#Add parent to the list
#new_items_list = new_items_list + parents
Rails.logger.debug "Re-Order List (Parent)-"
Rails.logger.debug parents
Rails.logger.debug "Re-Order List -"
Rails.logger.debug new_items_list
return new_items_list
def re_order_items(items) #reorder inputs items as parents and child
new_items = items.select { |i| i[:parent_order_item_id].blank? }.map { |x| x[:sub_items] = items.select { |y| x[:order_item_id] == y[:parent_order_item_id] }; x }
end
@@ -295,7 +212,7 @@ class Order < ApplicationRecord
def self.pay_process_order_queue(id,table_id)
# if ENV["SERVER_MODE"] != 'cloud'
order = Order.find(id)
sidekiq = Lookup.find_by_lookup_type_and_shop_code("sidekiq",order.shop_code)
sidekiq = Lookup.find_by_lookup_type("sidekiq")
if !sidekiq.nil?
OrderQueueProcessorJob.perform_later(id, table_id)
else
@@ -485,66 +402,31 @@ class Order < ApplicationRecord
end
#Process order items and send to order queue
def self.process_order_queue(order_id,table_id,source)
def self.process_order_queue(order_id, table_id, source)
print_status = nil
cup_status = nil
#Send to background job for processing
order = Order.find(order_id)
sidekiq = Lookup.find_by_lookup_type("sidekiq")
#Send to background job for processing
order = Order.find(order_id)
sidekiq = Lookup.find_by_lookup_type("sidekiq")
if ENV["SERVER_MODE"] != 'cloud'
cup_status = `#{"sudo service cups status"}`
print_status = check_cup_status(cup_status)
if ENV["SERVER_MODE"] != 'cloud'
if Printer::PrinterWorker.printers.blank?
msg = 'Print Error ! Please contact to service'
ActionCable.server.broadcast "call_waiter_channel", table: msg, time:'print_error', from: ''
end
end
if print_status
if !sidekiq.nil?
OrderQueueProcessorJob.perform_later(order_id, table_id)
else
if order
oqs = OrderQueueStation.new
oqs.process_order(order, table_id, 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, source)
end
assign_order = AssignedOrderItem.assigned_order_item_by_job(order_id)
ActionCable.server.broadcast "order_queue_station_channel", order: assign_order
end
end
def self.check_cup_status(status)

View File

@@ -5,8 +5,10 @@ class OrderItem < ApplicationRecord
before_create :generate_custom_id
#Associations
belongs_to :order, autosave: true
# belongs_to :order, counter_cache: true
belongs_to :order, autosave: true
has_one :menu_item, foreign_key: "item_code", primary_key: "item_code"
has_one :menu_category, through: :menu_item
# belongs_to :order, counter_cache: true
#Validation
validates_presence_of :item_code, :item_name, :qty
@@ -102,7 +104,13 @@ class OrderItem < ApplicationRecord
end
end
protected
def self.generate_ids(count = 1)
SeedGenerator.generate_ids(self.name, "ODI", count)
end
private
def generate_custom_id
if self.order_items_id.nil?
self.order_items_id = SeedGenerator.generate_id(self.class.name, "ODI")

View File

@@ -14,104 +14,39 @@ class OrderQueueStation < ApplicationRecord
# validations
validates_presence_of :station_name, :printer_name
def process_order (order, table_id, order_source = nil, pdf_status = nil ,change_to=nil,current_user=nil)
oqs_stations = OrderQueueStation.active.where("shop_code='#{order.shop_code}'")
def process_order(order, table_id, order_source = nil, pdf_status = nil ,change_to=nil, current_user=nil)
order_items = order.order_items
if table_id.to_i > 0
# get dining
dining = DiningFacility.find(table_id)
oqs_by_zones = OrderQueueProcessByZone.where("zone_id=#{dining.zone_id}")
booking = Booking.find_by_dining_facility_id(dining.id)
# ToDo per item per printer
oqs_by_zones.each do |oqpbz|
oqs = OrderQueueStation.find(oqpbz.order_queue_station_id)
is_auto_printed = false
oqs_order_items = []
if oqs.is_active
#Get List of items -
pq_items = JSON.parse(oqs.processing_items)
#Loop through the processing items
pq_items.each do |pq_item|
#Processing through the looping items
order_items.each do |order_item|
if (pq_item == order_item.item_code)
# if oqs.id == oqpbz.order_queue_station_id
# #Same Order_items can appear in two location.
# AssignedOrderItem.assigned_order_item(order, order_item.item_code, oqs)
# else
if (order_item.qty > 0)
if pdf_status.nil?
AssignedOrderItem.assigned_order_item(order, order_item.item_code, order_item.item_instance_code, oqs)
end
oqs_order_items.push(order_item)
end
# end
end
end
end
if oqs.auto_print && order_source != "quick_service"
if oqs_order_items.length > 0
if oqs.cut_per_item
print_slip_item(oqs, order, oqs_order_items,pdf_status,change_to,current_user,table_id)
else
print_slip(oqs, order, oqs_order_items,pdf_status,change_to,current_user,table_id)
end
is_auto_printed = true
end
end
end
end
oqs_stations = dining.order_queue_stations
else
oqs_stations.each do |oqs|
is_auto_printed = false
oqs_order_items = []
oqs_stations = OrderQueueStation.active
end
if oqs.is_active
#Get List of items -
pq_items = JSON.parse(oqs.processing_items)
#Loop through the processing items
pq_items.each do |pq_item|
#Processing through the looping items
order_items.each do |order_item|
if (pq_item == order_item.item_code)
# if oqs.id == oqpbz.order_queue_station_id
# #Same Order_items can appear in two location.
# AssignedOrderItem.assigned_order_item(order, order_item.item_code, oqs)
# else
assigned_order_items = []
oqs_order_items_by_zones = []
if (order_item.qty > 0)
if pdf_status.nil?
AssignedOrderItem.assigned_order_item(order, order_item.item_code, order_item.item_instance_code, oqs)
end
oqs_order_items.push(order_item)
end
# end
end
end
end
# ToDo per item per printer
oqs_stations.each do |oqs|
oqs_order_items = order_items.select { |i| JSON.parse(oqs.processing_items).include? i.item_code }
oqs_order_items_by_zones << { oqs: oqs, oqs_order_items: oqs_order_items }
if oqs.auto_print && order_source != "quick_service"
if oqs_order_items.length > 0
if oqs.cut_per_item
print_slip_item(oqs, order, oqs_order_items,pdf_status,change_to,current_user,table_id)
else
print_slip(oqs, order, oqs_order_items,pdf_status,change_to,current_user,table_id)
end
is_auto_printed = true
end
print_status = false
if oqs.auto_print && order_source != "quick_service"
print_status = true
if oqs_order_items.length > 0
if oqs.cut_per_item
print_slip_item(oqs, order, oqs_order_items, pdf_status, change_to, current_user, table_id)
else
print_slip(oqs, order, oqs_order_items, pdf_status, change_to, current_user, table_id)
end
end
end
end #end else
oqs_order_items.each { |i| AssignedOrderItem.create({ order: order, item_code: i.item_code, instance_code: i.item_instance_code, order_queue_station: oqs, print_status: print_status, delivery_status: false }) }
end
end
def pay_process_order_queue (order_id, table_id)
@@ -213,80 +148,31 @@ class OrderQueueStation < ApplicationRecord
#Print order_items in 1 slip
def print_slip(oqs, order, order_items ,pdf_status=nil,change_to=nil,current_user=nil,table_id=nil)
if pdf_status.nil?
printer = PrintSetting.where("shop_code='#{oqs.shop_code}'").order("id ASC")
unique_code="OrderSummaryPdf"
if !printer.empty?
printer.each do |printer_setting|
if printer_setting.unique_code == 'OrderSummaryPdf'
unique_code="OrderSummaryPdf"
elsif printer_setting.unique_code == 'OrderSummarySlimPdf'
unique_code="OrderSummarySlimPdf"
elsif printer_setting.unique_code == 'OrderSummarySetPdf'
unique_code="OrderSummarySetPdf"
elsif printer_setting.unique_code == 'OrderSummaryCustomisePdf'
unique_code="OrderSummaryCustomisePdf"
elsif printer_setting.unique_code == 'OrderSummarySetCustomisePdf'
unique_code="OrderSummarySetCustomisePdf"
elsif printer_setting.unique_code == 'OrderSummarySlimCustomisePdf'
unique_code="OrderSummarySlimCustomisePdf"
end
end
if print_settings = PrintSetting.where("unique_code REGEXP ?", "order.*summary.*pdf").first
order_queue_printer = Printer::OrderQueuePrinter.new(print_settings)
order_queue_printer.print_order_summary(print_settings, oqs, order.order_id, order_items, print_status="")
end
print_settings=PrintSetting.find_by_unique_code_and_shop_code(unique_code,oqs.shop_code)
order_queue_printer= Printer::OrderQueuePrinter.new(print_settings)
order_queue_printer.print_order_summary(print_settings, oqs,order.order_id, order_items, print_status="")
else
move_print_pdf(change_to,current_user,table_id,order_items,oqs)
end
assigned =AssignedOrderItem.where("order_id = '#{ order.order_id }'").pluck(:assigned_order_item_id)
AssignedOrderItem.where('assigned_order_item_id IN (?)', assigned).update_all(print_status: true)
end
#Print order_item in 1 slip per item
def print_slip_item(oqs, order, assigned_items,pdf_status=nil,change_to=nil,current_user=nil,table_id=nil)
if pdf_status.nil?
printer = PrintSetting.where("shop_code='#{oqs.shop_code}'").order("id ASC")
unique_code="OrderItemPdf"
if !printer.empty?
printer.each do |printer_setting|
if printer_setting.unique_code == 'OrderItemPdf'
unique_code="OrderItemPdf"
elsif printer_setting.unique_code == 'OrderItemStarPdf'
unique_code="OrderItemStarPdf"
elsif printer_setting.unique_code == 'OrderItemSlimPdf'
unique_code="OrderItemSlimPdf"
elsif printer_setting.unique_code == 'OrderSetItemPdf'
unique_code="OrderSetItemPdf"
elsif printer_setting.unique_code == 'OrderItemCustomisePdf'
unique_code="OrderItemCustomisePdf"
elsif printer_setting.unique_code == 'OrderSetItemCustomisePdf'
unique_code="OrderSetItemCustomisePdf"
elsif printer_setting.unique_code == 'OrderItemSlimCustomisePdf'
unique_code="OrderItemSlimCustomisePdf"
end
end
end
# order_item = OrderItem.where("order_id='#{assigned_item.order_id}' AND item_instance_code='#{assigned_item.instance_code}'").first()
# print when complete click
print_settings=PrintSetting.find_by_unique_code_and_shop_code(unique_code,oqs.shop_code)
order_queue_printer= Printer::OrderQueuePrinter.new(print_settings)
if !assigned_items.nil?
assigned_items.each do |order_item|
order_queue_printer.print_order_item(print_settings, oqs,order_item.order_id, order_item.order_items_id, print_status="" )
if print_settings = PrintSetting.where("unique_code REGEXP ?", "order.*item.*pdf").first
order_queue_printer = Printer::OrderQueuePrinter.new(print_settings)
if !assigned_items.nil?
assigned_items.each do |order_item|
order_queue_printer.print_order_item(print_settings, oqs,order_item.order_id, order_item.order_items_id, print_status="" )
end
end
end
else
move_print_pdf(change_to,current_user,table_id,assigned_items,oqs)
end
assigned =AssignedOrderItem.where("order_id = '#{ order.order_id }'").pluck(:assigned_order_item_id)
AssignedOrderItem.where('assigned_order_item_id IN (?)', assigned).update_all(print_status: true)
end
def move_print_pdf(change_to,current_user,change_from,order_items,oqs)
@@ -299,7 +185,7 @@ class OrderQueueStation < ApplicationRecord
@date = DateTime.now
@shop = Shop.current_shop
unique_code = "MoveTablePdf"
unique_code = "MoveTablePdf"
# pdf_no = PrintSetting.where(:unique_code => unique_code).count
print_settings = PrintSetting.find_by_unique_code(unique_code)
# printer_array = []

View File

@@ -8,7 +8,6 @@ class PaymentJournal < ApplicationRecord
self.payment_status = 'paid'
self.payment_method_references = payment_method_reference
self.created_by = current_user.id
self.shop_code = current_user.shop_code
self.save
end
@@ -18,7 +17,6 @@ class PaymentJournal < ApplicationRecord
self.debit_amount = amount
self.payment_status = 'paid'
self.created_by = current_user.id
self.shop_code = current_user.shop_code
self.save
end

View File

@@ -1,41 +1,18 @@
class Printer::OrderQueuePrinter < Printer::PrinterWorker
def print_order_item(print_settings,oqs, order_id, order_item_id, print_status, before_updated_qty="", options="")
def print_order_item(print_settings, oqs, order_id, order_item_id, print_status, before_updated_qty="", options="")
# Must be one print
if print_settings.print_copies == 0
print_settings.print_copies = 1
print_settings.save!
end
order_item = print_query('order_item', order_item_id) #OrderItem.find_by_item_code(item_code)
order_item = print_query('order_item', order_item_id) #OrderItem.find_by_item_code(item_code)
options = order_item[0].options
# filename = "tmp/order_item_#{order_id}_#{order_item_id}" + ".pdf"
# pdf = OrderItemPdf.new(print_settings,order_item[0], print_status, options, oqs.use_alternate_name, before_updated_qty)
print_setting = PrintSetting.all
# check for item not to show
pdf = ''
# if order_item[0].price != 0
if !print_setting.empty?
print_setting.each do |print_settings|
if print_settings.unique_code == 'OrderItemPdf'
pdf = OrderItemPdf.new(print_settings,order_item[0], print_status, options, oqs.use_alternate_name, before_updated_qty)
elsif print_settings.unique_code == 'OrderItemStarPdf'
pdf = OrderItemStarPdf.new(print_settings,order_item[0], print_status, options, oqs.use_alternate_name, before_updated_qty)
elsif print_settings.unique_code == 'OrderItemSlimPdf'
pdf = OrderItemSlimPdf.new(print_settings,order_item[0], print_status, options, oqs.use_alternate_name, before_updated_qty)
elsif print_settings.unique_code == 'OrderSetItemPdf'
pdf = OrderSetItemPdf.new(print_settings,order_item[0], print_status, options, oqs.use_alternate_name, before_updated_qty)
elsif print_settings.unique_code == 'OrderItemCustomisePdf'
pdf = OrderItemCustomisePdf.new(print_settings,order_item[0], print_status, options, oqs.use_alternate_name, before_updated_qty)
elsif print_settings.unique_code == 'OrderSetItemCustomisePdf'
pdf = OrderSetItemCustomisePdf.new(print_settings,order_item[0], print_status, options, oqs.use_alternate_name, before_updated_qty)
elsif print_settings.unique_code == 'OrderItemSlimCustomisePdf'
pdf = OrderItemSlimCustomisePdf.new(print_settings,order_item[0], print_status, options, oqs.use_alternate_name, before_updated_qty)
end
end
end
pdf = print_settings.unique_code.constantize.new(print_settings,order_item[0], print_status, options, oqs.use_alternate_name, before_updated_qty)
# end
@@ -47,28 +24,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
@@ -78,113 +45,56 @@ class Printer::OrderQueuePrinter < Printer::PrinterWorker
print_settings.save!
end
print_setting = PrintSetting.all.order("id ASC")
order=print_query('order_summary', order_id)
# shop = Shop.current_shop
directory_name = 'public/orders_'+ oqs.shop_code
shop = Shop.current_shop
directory_name = "public/orders_#{shop.shop_code}"
Dir.mkdir(directory_name) unless File.exists?(directory_name)
# For Print Per Item
if oqs.cut_per_item
order_items.each do|odi|
odi_item=print_query('order_item', odi.order_items_id)
order_items.each do |odi|
odi_item = print_query('order_item', odi.order_items_id)
filename = directory_name + "/order_item_#{order_id}" + ".pdf"
filename = directory_name + "/order_item_#{order_id}.pdf"
# filename = "tmp/order_item_#{order_id}" + ".pdf"
# For Item Options
options = odi.options == "[]"? "" : odi.options
options = odi.options == "[]" ? "" : odi.options
# check for item not to show
#if odi.price != 0
pdf = OrderItemPdf.new(print_settings,odi_item[0], print_status, options, oqs.use_alternate_name,before_updated_qty)
if !print_setting.empty?
print_setting.each do |print_settings|
if print_settings.unique_code == 'OrderItemPdf'
pdf = OrderItemPdf.new(print_settings,odi_item[0], print_status, options, oqs.use_alternate_name,before_updated_qty)
elsif print_settings.unique_code == 'OrderItemStarPdf'
pdf = OrderItemStarPdf.new(print_settings,order_item[0], print_status, options, oqs.use_alternate_name, before_updated_qty)
elsif print_settings.unique_code == 'OrderItemSlimPdf'
pdf = OrderItemSlimPdf.new(print_settings,odi_item[0], print_status, options, oqs.use_alternate_name,before_updated_qty)
elsif print_settings.unique_code == 'OrderSetItemPdf'
pdf = OrderSetItemPdf.new(print_settings,odi_item[0], print_status, options, oqs.use_alternate_name,before_updated_qty)
elsif print_settings.unique_code == 'OrderItemCustomisePdf'
pdf = OrderItemCustomisePdf.new(print_settings,odi_item[0], print_status, options, oqs.use_alternate_name,before_updated_qty)
elsif print_settings.unique_code == 'OrderSetItemCustomisePdf'
pdf = OrderSetItemCustomisePdf.new(print_settings,odi_item[0], print_status, options, oqs.use_alternate_name,before_updated_qty)
elsif print_settings.unique_code == 'OrderItemSlimCustomisePdf'
pdf = OrderItemSlimCustomisePdf.new(print_settings,odi_item[0], print_status, options, oqs.use_alternate_name,before_updated_qty)
end
end
end
pdf = print_settings.unique_code.constantize.new(print_settings, odi_item[0], print_status, options, oqs.use_alternate_name, before_updated_qty)
# pdf.render_file "tmp/order_item.pdf"
pdf.render_file filename
if oqs.print_copy
#no print in cloud server
if ENV["SERVER_MODE"] != "cloud"
self.print(filename, oqs.printer_name)
# self.print(filename.gsub(".","-copy."), oqs.printer_name)
end
else
print_settings.print_copies = 1
print_settings.save!
#no print in cloud server
if ENV["SERVER_MODE"] != "cloud"
self.print(filename, oqs.printer_name)
end
end
# pdf.render_file "tmp/order_item.pdf"
pdf.render_file filename
#no print in cloud server
if ENV["SERVER_MODE"] != "cloud"
self.print(filename, oqs.printer_name)
# self.print(filename.gsub(".","-copy."), oqs.printer_name)
end
#end
end
# For Print Order Summary
else
filename = directory_name + "/order_summary_#{order_id}" + ".pdf"
order = print_query('order_summary', order_id)
filename = directory_name + "/order_summary_#{order_id}.pdf"
# filename = "tmp/order_summary_#{order_id}" + ".pdf"
pdf = OrderSummaryPdf.new(print_settings,order, print_status, order_items, oqs.use_alternate_name,before_updated_qty)
if !print_setting.empty?
print_setting.each do |print_settings|
if print_settings.unique_code == 'OrderSummaryPdf'
pdf = OrderSummaryPdf.new(print_settings,order, print_status, order_items, oqs.use_alternate_name,before_updated_qty)
elsif print_settings.unique_code == 'OrderSummarySlimPdf'
pdf = OrderSummarySlimPdf.new(print_settings,order, print_status, order_items, oqs.use_alternate_name,before_updated_qty)
elsif print_settings.unique_code == 'OrderSummarySetPdf'
pdf = OrderSummarySetPdf.new(print_settings,order, print_status, order_items, oqs.use_alternate_name,before_updated_qty)
elsif print_settings.unique_code == 'OrderSummaryCustomisePdf'
pdf = OrderSummaryCustomisePdf.new(print_settings,order, print_status, order_items, oqs.use_alternate_name,before_updated_qty)
elsif print_settings.unique_code == 'OrderSummarySetCustomisePdf'
pdf = OrderSummarySetCustomisePdf.new(print_settings,order, print_status, order_items, oqs.use_alternate_name,before_updated_qty)
elsif print_settings.unique_code == 'OrderSummarySlimCustomisePdf'
pdf = OrderSummarySlimCustomisePdf.new(print_settings,order, print_status, order_items, oqs.use_alternate_name,before_updated_qty)
end
end
end
pdf = print_settings.unique_code.constantize.new(print_settings, order, print_status, order_items, oqs.use_alternate_name, before_updated_qty)
pdf.render_file filename
if oqs.print_copy
#no print in cloud server
if ENV["SERVER_MODE"] != "cloud"
self.print(filename, oqs.printer_name)
end
#For print copy
# pdf.render_file filename.gsub(".","-copy.")
# self.print(filename.gsub(".","-copy."), oqs.printer_name)
else
print_settings.print_copies = 1
print_settings.save!
#no print in cloud server
if ENV["SERVER_MODE"] != "cloud"
self.print(filename, oqs.printer_name)
end
#no print in cloud server
if ENV["SERVER_MODE"] != "cloud"
self.print(filename, oqs.printer_name)
end
#For print copy
# pdf.render_file filename.gsub(".","-copy.")
# self.print(filename.gsub(".","-copy."), oqs.printer_name)
end
return filename, order_id, oqs.printer_name
end
# Print for orders in booking
def print_booking_summary(print_settings,oqs, booking_id, print_status,before_updated_qty="")
def print_booking_summary(print_settings, oqs, booking_id, print_status,before_updated_qty="")
# Must be one print
if print_settings.print_copies == 0
print_settings.print_copies = 1
@@ -193,7 +103,7 @@ class Printer::OrderQueuePrinter < Printer::PrinterWorker
print_setting = PrintSetting.all.order("id ASC")
order=print_query('booking_summary', booking_id)
order = print_query('booking_summary', booking_id)
# shop = Shop.current_shop
@@ -210,72 +120,10 @@ class Printer::OrderQueuePrinter < Printer::PrinterWorker
# check for item not to show
#if odi.price != 0
pdf = OrderItemPdf.new(print_settings,odi, print_status, options,oqs.use_alternate_name,before_updated_qty)
if !print_setting.empty?
print_setting.each do |print_settings|
if print_settings.unique_code == 'OrderItemPdf'
pdf = OrderItemPdf.new(print_settings,odi, print_status, options,oqs.use_alternate_name,before_updated_qty)
elsif print_settings.unique_code == 'OrderItemStarPdf'
pdf = OrderItemStarPdf.new(print_settings,odi, print_status, options,oqs.use_alternate_name,before_updated_qty)
elsif print_settings.unique_code == 'OrderItemSlimPdf'
pdf = OrderItemSlimPdf.new(print_settings,odi, print_status, options,oqs.use_alternate_name,before_updated_qty)
elsif print_settings.unique_code == 'OrderSetItemPdf'
pdf = OrderSetItemPdf.new(print_settings,odi, print_status, options,oqs.use_alternate_name,before_updated_qty)
elsif print_settings.unique_code == 'OrderItemCustomisePdf'
pdf = OrderItemCustomisePdf.new(print_settings,odi, print_status, options,oqs.use_alternate_name,before_updated_qty)
elsif print_settings.unique_code == 'OrderSetItemCustomisePdf'
pdf = OrderSetItemCustomisePdf.new(print_settings,odi, print_status, options,oqs.use_alternate_name,before_updated_qty)
elsif print_settings.unique_code == 'OrderItemSlimCustomisePdf'
pdf = OrderItemSlimCustomisePdf.new(print_settings,odi, print_status, options,oqs.use_alternate_name,before_updated_qty)
end
end
end
pdf.render_file filename
pdf = print_settings.unique_code.constantize.new(print_settings, odi, print_status, options, oqs.use_alternate_name, before_updated_qty)
if oqs.print_copy
#no print in cloud server
if ENV["SERVER_MODE"] != "cloud"
self.print(filename, oqs.printer_name)
end
#For print copy
# pdf.render_file filename.gsub(".","-copy.")
# self.print(filename.gsub(".","-copy."), oqs.printer_name)
else
print_settings.print_copies = 1
print_settings.save!
#no print in cloud server
if ENV["SERVER_MODE"] != "cloud"
self.print(filename, oqs.printer_name)
end
end
#end
end
# For Print Order Summary
else
# filename = "tmp/booking_summary_#{booking_id}" + ".pdf"
filename = directory_name + "/booking_summary_#{booking_id}" + ".pdf"
pdf = OrderSummaryPdf.new(print_settings,order, print_status,oqs.use_alternate_name,before_updated_qty)
pdf.render_file filename
if !print_setting.empty?
print_setting.each do |print_settings|
if print_settings.unique_code == 'OrderSummaryPdf'
pdf = OrderSummaryPdf.new(print_settings,order, print_status,oqs.use_alternate_name,before_updated_qty)
elsif print_settings.unique_code == 'OrderSummarySlimPdf'
pdf = OrderSummarySlimPdf.new(print_settings,order, print_status,oqs.use_alternate_name,before_updated_qty)
elsif print_settings.unique_code == 'OrderSummarySetPdf'
pdf = OrderSummarySetPdf.new(print_settings,order, print_status,oqs.use_alternate_name,before_updated_qty)
elsif print_settings.unique_code == 'OrderSummaryCustomisePdf'
pdf = OrderSummaryCustomisePdf.new(print_settings,order, print_status,oqs.use_alternate_name,before_updated_qty)
elsif print_settings.unique_code == 'OrderSummarySetCustomisePdf'
pdf = OrderSummarySetCustomisePdf.new(print_settings,order, print_status,oqs.use_alternate_name,before_updated_qty)
elsif print_settings.unique_code == 'OrderSummarySlimCustomisePdf'
pdf = OrderSummarySlimCustomisePdf.new(print_settings,order, print_status,oqs.use_alternate_name,before_updated_qty)
end
end
end
pdf.render_file filename
if oqs.print_copy
#no print in cloud server
if ENV["SERVER_MODE"] != "cloud"
self.print(filename, oqs.printer_name)
@@ -283,14 +131,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
@@ -298,35 +154,35 @@ class Printer::OrderQueuePrinter < Printer::PrinterWorker
# Query for OQS with status
def print_query(type, id)
if type == "order_item"
OrderItem.select("orders.source,cus.contact_no,rder_items.order_id, order_items.item_code, order_items.item_name, order_items.qty, order_items.price, order_items.options, order_items.item_order_by as order_by, order_items.created_at as order_at, order_items.set_menu_items, cus.name as customer, df.type, df.name as dining,item.alt_name as alt_name")
.joins("left join orders ON orders.order_id = order_items.order_id
left join booking_orders AS bo ON bo.order_id=order_items.order_id
left join bookings AS b ON b.booking_id = bo.booking_id
left join dining_facilities AS df ON df.id = b.dining_facility_id
left join customers as cus ON cus.customer_id = orders.customer_id
left join menu_items as item ON item.item_code = order_items.item_code")
.where("order_items.order_items_id = '#{ id }'")
.group("order_items.item_code")
OrderItem.select("orders.source,cus.contact_no,order_items.order_id, order_items.item_code, order_items.item_name, order_items.qty, order_items.price, order_items.options, order_items.item_order_by as order_by, order_items.created_at as order_at, order_items.set_menu_items, cus.name as customer, df.type, df.name as dining, item.alt_name as alt_name")
.joins("left join orders ON orders.order_id = order_items.order_id
left join booking_orders AS bo ON bo.order_id=order_items.order_id
left join bookings AS b ON b.booking_id = bo.booking_id
left join dining_facilities AS df ON df.id = b.dining_facility_id
left join customers as cus ON cus.customer_id = orders.customer_id
left join menu_items as item ON item.item_code = order_items.item_code")
.where("order_items.order_items_id = '#{ id }'")
.group("order_items.item_code")
elsif type == "order_summary"
OrderItem.select("orders.source,cus.contact_no,order_items.order_id, order_items.item_code, order_items.item_name, order_items.qty, order_items.price, order_items.options, order_items.item_order_by as order_by, order_items.created_at as order_at, order_items.set_menu_items, cus.name as customer, df.type, df.name as dining,item.alt_name as alt_name")
.joins("left join orders ON orders.order_id = order_items.order_id
left join booking_orders AS bo ON bo.order_id=order_items.order_id
left join bookings AS b ON b.booking_id = bo.booking_id
left join dining_facilities AS df ON df.id = b.dining_facility_id
left join customers as cus ON cus.customer_id = orders.customer_id
left join menu_items as item ON item.item_code = order_items.item_code")
.where("orders.order_id = '#{ id }'")
.group("order_items.order_items_id")
OrderItem.select("orders.source,cus.contact_no,order_items.order_id, order_items.item_code, order_items.item_name, order_items.qty, order_items.price, order_items.options, order_items.item_order_by as order_by, order_items.created_at as order_at, order_items.set_menu_items, cus.name as customer, df.type, df.name as dining, item.alt_name as alt_name")
.joins("left join orders ON orders.order_id = order_items.order_id
left join booking_orders AS bo ON bo.order_id=order_items.order_id
left join bookings AS b ON b.booking_id = bo.booking_id
left join dining_facilities AS df ON df.id = b.dining_facility_id
left join customers as cus ON cus.customer_id = orders.customer_id
left join menu_items as item ON item.item_code = order_items.item_code")
.where("orders.order_id = '#{ id }'")
.group("order_items.order_items_id")
else
# order summary for booking
OrderItem.select("orders.source,cus.contact_no,order_items.order_id, order_items.item_code, order_items.item_name, order_items.qty, order_items.price, order_items.options, order_items.item_order_by as order_by, order_items.created_at as order_at, order_items.set_menu_items, cus.name as customer, df.type, df.name as dining,item.alt_name as alt_name")
.joins("left join orders ON orders.order_id = order_items.order_id
left join booking_orders AS bo ON bo.order_id=order_items.order_id
left join bookings AS b ON b.booking_id = bo.booking_id
left join dining_facilities AS df ON df.id = b.dining_facility_id
left join customers as cus ON cus.customer_id = orders.customer_id
left join menu_items as item ON item.item_code = order_items.item_code")
.where("b.booking_id = '#{ id }'")
# order summary for booking
OrderItem.select("orders.source,cus.contact_no,order_items.order_id, order_items.item_code, order_items.item_name, order_items.qty, order_items.price, order_items.options, order_items.item_order_by as order_by, order_items.created_at as order_at, order_items.set_menu_items, cus.name as customer, df.type, df.name as dining, item.alt_name as alt_name")
.joins("left join orders ON orders.order_id = order_items.order_id
left join booking_orders AS bo ON bo.order_id=order_items.order_id
left join bookings AS b ON b.booking_id = bo.booking_id
left join dining_facilities AS df ON df.id = b.dining_facility_id
left join customers as cus ON cus.customer_id = orders.customer_id
left join menu_items as item ON item.item_code = order_items.item_code")
.where("b.booking_id = '#{ id }'")
end
end

View File

@@ -37,14 +37,15 @@ class Printer::PrinterWorker
Cups.default_printer
end
def print(file_path,printer_destination = nil )
def self.printer_exists?(printer)
Cups.show_destinations.include? printer
end
def print(file_path, printer_destination = nil )
# if printer_destination.nil?
# printer_destination = self.printer_destination
# end
#
# puts printer_destination
# puts '........Printer Destination..........'
#
# copy = self.print_copies
# #Print only when printer information is not null
# if !self.printer_destination.nil?

View File

@@ -4,26 +4,9 @@ class Printer::ReceiptPrinter < Printer::PrinterWorker
#Use CUPS service
#Generate PDF
#Print
printer = PrintSetting.all
pdf = OrderItemPdf.new
printer = PrintSetting.where("unique_code REGEXP ?", "order.*item.*pdf").first
pdf = printer.unique_code.constantize.new
if !printer.empty?
printer.each do |printer_setting|
if printer_setting.unique_code == 'OrderItemPdf'
pdf = OrderItemPdf.new
elsif printer_setting.unique_code == 'OrderItemSlimPdf'
pdf = OrderItemSlimPdf.new
elsif printer_setting.unique_code == 'OrderSetItemPdf'
pdf = OrderSetItemPdf.new
elsif printer_setting.unique_code == 'OrderItemCustomisePdf'
pdf = OrderItemCustomisePdf.new
elsif printer_setting.unique_code == 'OrderSetItemCustomisePdf'
pdf = OrderSetItemCustomisePdf.new
elsif printer_setting.unique_code == 'OrderItemSlimCustomisePdf'
pdf = OrderItemSlimCustomisePdf.new
end
end
end
pdf.render_file "tmp/order_item_queue_#{order_id}_#{order_item_id}" + ".pdf"
#no print in cloud server
if ENV["SERVER_MODE"] != "cloud"
@@ -36,26 +19,9 @@ class Printer::ReceiptPrinter < Printer::PrinterWorker
#Generate PDF
#Print
filename = "tmp/order_summary_#{booking_id}" + ".pdf"
printer = PrintSetting.all
pdf = OrderSummaryPdf.new
printer = PrintSetting.where("unique_code REGEXP ?", "order.*summary.*pdf").first
pdf = printer.unique_code.constantize.new
if !printer.empty?
printer.each do |printer_setting|
if printer_setting.unique_code == 'OrderSummaryPdf'
pdf = OrderSummaryPdf.new
elsif printer_setting.unique_code == 'OrderSummarySlimPdf'
pdf = OrderSummarySlimPdf.new
elsif printer_setting.unique_code == 'OrderSummarySetPdf'
pdf = OrderSummarySetPdf.new
elsif printer_setting.unique_code == 'OrderSummaryCustomisePdf'
pdf = OrderSummaryCustomisePdf.new
elsif printer_setting.unique_code == 'OrderSummarySetCustomisePdf'
pdf = OrderSummarySetCustomisePdf.new
elsif printer_setting.unique_code == 'OrderSummarySlimCustomisePdf'
pdf = OrderSummarySlimCustomisePdf.new
end
end
end
pdf.render_file filename
#no print in cloud server
if ENV["SERVER_MODE"] != "cloud"
@@ -67,26 +33,10 @@ class Printer::ReceiptPrinter < Printer::PrinterWorker
#Use CUPS service
#Generate PDF
#Print
printer = PrintSetting.all
printer = PrintSetting.where("unique_code REGEXP ?", "order.*summary.*pdf").first
filename = "tmp/order_summary_#{booking_id}" + ".pdf"
pdf = OrderSummaryPdf.new
if !printer.empty?
printer.each do |printer_setting|
if printer_setting.unique_code == 'OrderSummaryPdf'
pdf = OrderSummaryPdf.new
elsif printer_setting.unique_code == 'OrderSummarySlimPdf'
pdf = OrderSummarySlimPdf.new
elsif printer_setting.unique_code == 'OrderSummarySetPdf'
pdf = OrderSummarySetPdf.new
elsif printer_setting.unique_code == 'OrderSummaryCustomisePdf'
pdf = OrderSummaryCustomisePdf.new
elsif printer_setting.unique_code == 'OrderSummarySetCustomisePdf'
pdf = OrderSummarySetCustomisePdf.new
elsif printer_setting.unique_code == 'OrderSummarySlimCustomisePdf'
pdf = OrderSummarySlimCustomisePdf.new
end
end
end
pdf = printer.unique_code.constantize.new
pdf.render_file filename
#no print in cloud server
if ENV["SERVER_MODE"] != "cloud"
@@ -98,26 +48,10 @@ class Printer::ReceiptPrinter < Printer::PrinterWorker
#Use CUPS service
#Generate PDF
#Print
printer = PrintSetting.all
printer = PrintSetting.where("unique_code REGEXP ?", "order.*summary.*pdf").first
filename = "tmp/order_summary_#{booking_id}" + ".pdf"
pdf = OrderSummaryPdf.new
if !printer.empty?
printer.each do |printer_setting|
if printer_setting.unique_code == 'OrderSummaryPdf'
pdf = OrderSummaryPdf.new
elsif printer_setting.unique_code == 'OrderSummarySlimPdf'
pdf = OrderSummarySlimPdf.new
elsif printer_setting.unique_code == 'OrderSummarySetPdf'
pdf = OrderSummarySetPdf.new
elsif printer_setting.unique_code == 'OrderSummaryCustomisePdf'
pdf = OrderSummaryCustomisePdf.new
elsif printer_setting.unique_code == 'OrderSummarySetCustomisePdf'
pdf = OrderSummarySetCustomisePdf.new
elsif printer_setting.unique_code == 'OrderSummarySlimCustomisePdf'
pdf = OrderSummarySlimCustomisePdf.new
end
end
end
pdf = printer.unique_code.constantize.new
pdf.render_file filename
#no print in cloud server
if ENV["SERVER_MODE"] != "cloud"
@@ -129,26 +63,10 @@ class Printer::ReceiptPrinter < Printer::PrinterWorker
#Use CUPS service
#Generate PDF
#Print
printer = PrintSetting.all
printer = PrintSetting.where("unique_code REGEXP ?", "order.*summary.*pdf").first
filename = "tmp/order_summary_#{booking_id}" + ".pdf"
pdf = OrderSummaryPdf.new
if !printer.empty?
printer.each do |printer_setting|
if printer_setting.unique_code == 'OrderSummaryPdf'
pdf = OrderSummaryPdf.new
elsif printer_setting.unique_code == 'OrderSummarySlimPdf'
pdf = OrderSummarySlimPdf.new
elsif printer_setting.unique_code == 'OrderSummarySetPdf'
pdf = OrderSummarySetPdf.new
elsif printer_setting.unique_code == 'OrderSummaryCustomisePdf'
pdf = OrderSummaryCustomisePdf.new
elsif printer_setting.unique_code == 'OrderSummarySetCustomisePdf'
pdf = OrderSummarySetCustomisePdf.new
elsif printer_setting.unique_code == 'OrderSummarySlimCustomisePdf'
pdf = OrderSummarySlimCustomisePdf.new
end
end
end
pdf = printer.unique_code.constantize.new
pdf.render_file filename
#no print in cloud server
if ENV["SERVER_MODE"] != "cloud"
@@ -160,26 +78,10 @@ class Printer::ReceiptPrinter < Printer::PrinterWorker
#Use CUPS service
#Generate PDF
#Print
printer = PrintSetting.all
printer = PrintSetting.where("unique_code REGEXP ?", "order.*summary.*pdf").first
filename = "tmp/order_summary_#{booking_id}" + ".pdf"
pdf = OrderSummaryPdf.new
if !printer.empty?
printer.each do |printer_setting|
if printer_setting.unique_code == 'OrderSummaryPdf'
pdf = OrderSummaryPdf.new
elsif printer_setting.unique_code == 'OrderSummarySlimPdf'
pdf = OrderSummarySlimPdf.new
elsif printer_setting.unique_code == 'OrderSummarySetPdf'
pdf = OrderSummarySetPdf.new
elsif printer_setting.unique_code == 'OrderSummaryCustomisePdf'
pdf = OrderSummaryCustomisePdf.new
elsif printer_setting.unique_code == 'OrderSummarySetCustomisePdf'
pdf = OrderSummarySetCustomisePdf.new
elsif printer_setting.unique_code == 'OrderSummarySlimCustomisePdf'
pdf = OrderSummarySlimCustomisePdf.new
end
end
end
pdf = printer.unique_code.constantize.new
pdf.render_file filename
#no print in cloud server
if ENV["SERVER_MODE"] != "cloud"
@@ -188,40 +90,20 @@ class Printer::ReceiptPrinter < Printer::PrinterWorker
end
#Bill Receipt Print
def print_receipt_bill(printer_settings, kbz_pay_status, qr_code, cashier_terminal,sale_items,sale_data, customer_name, item_price_by_accounts, discount_price_by_accounts, member_info = nil,rebate_amount=nil,shop_details, printed_status,balance,card_data,other_amount,latest_order_no,card_balance_amount,order_reservation,transaction_ref)
def print_receipt_bill(printer_settings, kbz_pay_status, qr_code, cashier_terminal, sale_items, sale_data, customer_name, item_price_by_accounts, discount_price_by_accounts, member_info, rebate_amount, shop_details, printed_status, balance, card_data, other_amount, latest_order_no, card_balance_amount, order_reservation = nil, transaction_ref = nil)
#Use CUPS service
#Generate PDF
#Print
puts printer_settings.to_json
if !printer_settings.nil?
if !printer_settings.unique_code.strip.downcase.include? ("receiptbillorder")
pdf = ReceiptBillPdf.new(printer_settings, kbz_pay_status, qr_code, sale_items, sale_data, customer_name, item_price_by_accounts, discount_price_by_accounts, member_info,rebate_amount,shop_details,printed_status,balance,card_data,other_amount,latest_order_no,card_balance_amount,transaction_ref)
settings = PrintSetting.where("shop_code='#{shop_details.shop_code}'")
if !settings.nil?
settings.each do |setting|
if setting.unique_code == 'ReceiptBillPdf'
pdf = ReceiptBillPdf.new(printer_settings, kbz_pay_status, qr_code, sale_items, sale_data, customer_name, item_price_by_accounts, discount_price_by_accounts, member_info,rebate_amount,shop_details,printed_status,balance,card_data,other_amount,latest_order_no,card_balance_amount,transaction_ref)
elsif setting.unique_code == 'ReceiptBillStarPdf'
pdf = ReceiptBillStarPdf.new(printer_settings, kbz_pay_status, qr_code, sale_items, sale_data, customer_name, item_price_by_accounts, discount_price_by_accounts, member_info,rebate_amount,shop_details,printed_status,balance,card_data,other_amount,latest_order_no,card_balance_amount,transaction_ref)
end
end
end
receipt_bill_a5_pdf = Lookup.where("shop_code='#{shop_details.shop_code}'").collection_of("print_settings") #print_settings with name:ReceiptBillA5Pdf
if !receipt_bill_a5_pdf.empty?
receipt_bill_a5_pdf.each do |receipt_bilA5|
if receipt_bilA5[0] == 'ReceiptBillA5Pdf'
if receipt_bilA5[1] == '1'
pdf = ReceiptBillA5Pdf.new(printer_settings, sale_items, sale_data, customer_name, item_price_by_accounts, discount_price_by_accounts, member_info,rebate_amount,shop_details,printed_status,balance,card_data,other_amount,latest_order_no,card_balance_amount,transaction_ref)
# else
# pdf = ReceiptBillPdf.new(printer_settings, sale_items, sale_data, customer_name, item_price_by_accounts, discount_price_by_accounts, member_info,rebate_amount,shop_details,printed_status,balance,card_data,other_amount,latest_order_no,card_balance_amount)
end
end
end
if printer_settings
if !printer_settings.unique_code.match?(/receiptbillorder/i)
if Lookup.collection_of("print_settings").any? { |x| x == ["ReceiptBillA5Pdf", "1"] } #print_settings with name:ReceiptBillA5Pdf
pdf = ReceiptBillA5Pdf.new(printer_settings, sale_items, sale_data, customer_name, item_price_by_accounts, discount_price_by_accounts, member_info, rebate_amount, shop_details, printed_status, balance, card_data, other_amount, latest_order_no, card_balance_amount)
else
pdf = PrintSetting.where("unique_code REGEXP ?", "receipt.*bill.*pdf").first.unique_code.constantize.new(printer_settings, kbz_pay_status, qr_code, sale_items, sale_data, customer_name, item_price_by_accounts, discount_price_by_accounts, member_info, rebate_amount, shop_details, printed_status, balance, card_data, other_amount, latest_order_no, card_balance_amount, transaction_ref)
end
else
#doemal online order pdf template
pdf = ReceiptBillOrderPdf.new(printer_settings, sale_items, sale_data, customer_name, item_price_by_accounts, discount_price_by_accounts, member_info,rebate_amount,shop_details,printed_status,balance,card_data,other_amount,latest_order_no,card_balance_amount,order_reservation)
pdf = ReceiptBillOrderPdf.new(printer_settings, sale_items, sale_data, customer_name, item_price_by_accounts, discount_price_by_accounts, member_info, rebate_amount, shop_details,printed_status,balance,card_data,other_amount,latest_order_no,card_balance_amount,order_reservation)
end
# print as print copies in printer setting

View File

@@ -5,29 +5,23 @@ class Product < ApplicationRecord
mount_uploader :image_path, ProductImageUploader
def self.search_by_product_code(item_code)
account = Account.find_by_title('Product')
if !account.nil?
account_id = account.id
else
account_id = 1
end
menu_item_hash = Hash.new
mt_instance = Product.find_by_item_code(item_code)
if (!mt_instance.nil?)
menu_item_hash[:type] = 'Product'
menu_item_hash[:account_id] = account_id
menu_item_hash[:item_code] = mt_instance.item_code
menu_item_hash[:item_instance_code] = mt_instance.item_code
menu_item_hash[:name] = mt_instance.name.to_s
menu_item_hash[:alt_name] = mt_instance.alt_name.to_s
menu_item_hash[:price] = mt_instance.unit_price
menu_item_hash[:promotion_price] = 0
menu_item_hash[:is_on_promotion] = 0
menu_item_hash[:is_available] = 0
menu_item_hash[:taxable] = mt_instance.taxable
return menu_item_hash
end
end
Product.joins("JOIN accounts ON accounts.title = 'Product'")
.where(item_code: item_code)
.pluck("accounts.id AS account_id", :item_code, :name, :alt_name, :unit_price, :taxable)
.map { |account_id, item_code, item_name, item_alt_name, price, taxable|
{
type: 'Product',
account_id: account_id,
item_code: item_code,
item_instance_code: item_code,
name: "#{item_name}",
alt_name: "#{item_name}",
price: price,
promotion_price: 0,
is_on_promotion: 0,
is_available: 0,
taxable: taxable
}
}
end
end

View File

@@ -33,9 +33,9 @@ class ProductCommission < ApplicationRecord
product_commission.save
end
def self.edit_product_commission(saleItemObj,shop_code)
def self.edit_product_commission(saleItemObj)
menu_item = MenuItem.find_by_item_code(saleItemObj.product_code)
commission = Commission.where("shop_code='#{shop_code}' and product_code = ? AND is_active = ?", menu_item.id, true).take
commission = Commission.where("product_code = ? AND is_active = ?", menu_item.id, true).take
product_commission = ProductCommission.where('sale_item_id = ?', saleItemObj.id).take
if !product_commission.nil?

View File

@@ -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
@@ -31,9 +35,7 @@ class Sale < ApplicationRecord
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 :shop, -> { where("sales.shop_code=?",Shop.current_shop.shop_code) }
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
@@ -82,186 +84,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)
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])
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
self.shop_code = Shop.current_shop.shop_code
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
@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
@@ -532,6 +462,19 @@ class Sale < ApplicationRecord
end
tax_profiles = unique_tax_profiles(order_source, self.customer_id)
if tax_type.nil?
if tax_profiles.count == 2
tax_type = "all"
elsif tax_profiles.count == 1
if tax_profiles.name.downcase == "service charges"
tax_type = "Service Charges"
else
tax_type = "Commercial Tax"
end
elsif tax_profiles.count < 1
tax_type = "no_tax"
end
end
# #Creat new tax records
if self.payment_status != 'foc' && tax_type.to_s == "all"
@@ -692,14 +635,6 @@ class Sale < ApplicationRecord
self.total_tax = total_tax_amount
end
def product_get_unit_price(item_code)
menu_item_hash =MenuItem.search_by_item_code(item_code)
if (menu_instance_code)
return menu_ item_hash[:item_instance_code], menu_item_hash[:price]
end
return nil,nil
end
def link_order_sale(order_id)
#create if it doesn't exist
saleOrder = SaleOrder.where("sale_id=? and order_id=?", self.id, order_id).take
@@ -858,16 +793,20 @@ def self.daily_sales_list(from,to)
SUM(case when (sale_payments.payment_method='giftvoucher') then sale_payments.payment_amount else 0 end) as giftvoucher_amount,
SUM(case when (sale_payments.payment_method='foc') then sale_payments.payment_amount else 0 end) as foc_amount")
.along_with_sale_payments_except_void_between(from, to)
.where("(sale_status = ? OR sale_status = ?) AND sales.receipt_date between ? AND ? ", 'completed', 'void', from, to).shop
.where("(sale_status = ? OR sale_status = ?) AND sales.receipt_date between ? AND ? ", 'completed', 'void', from, to)
.group("sale_id").to_sql
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) 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,
(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 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,
@@ -910,11 +849,11 @@ def self.get_by_range_by_saleitems(from,to,status,report_type)
query = query.where("(receipt_date between ? and ? and sale_status=?) AND i.unit_price <> 0",from,to,status)
end
def self.get_by_shiftsales(from,to,shift,shop_code)
def self.get_by_shiftsales(from,to,shift)
if !shift.blank?
query = ShiftSale.where("shift_sales.id =? and shop_code='#{shop_code}'",shift.id)
query = ShiftSale.where("shift_sales.id =?",shift.id)
else
query = ShiftSale.where("(shift_started_at between ? and ? OR shift_closed_at between ? and ? ) and shop_code='#{shop_code}'", from, to, from, to)
query = ShiftSale.where("(shift_started_at between ? and ? OR shift_closed_at between ? and ? )", from, to, from, to)
end
shift_sale_data = Hash.new
@@ -1035,7 +974,7 @@ def self.get_other_charges()
query = query.group("i.sale_item_id")
end
def self.get_by_shift_items(shift_sale_range, shift, from, to, status,type,account_type,shop_code)
def self.get_by_shift_items(shift_sale_range, shift, from, to, status,type,account_type)
# date_type_selection = get_sql_function_for_report_type(report_type)
if account_type.blank?
account_type = ''
@@ -1131,7 +1070,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,shop_code)
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 = ''
@@ -1143,8 +1082,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()
@@ -1192,13 +1129,13 @@ def self.get_staff_meal_items(shift_sale_range, shift, from, to, status,account_
# end
product = product.where("sales.shift_sale_id IN (?) and sale_status='completed'",shift_sale_range.to_a)
discount_query = Sale.where("sales.shift_sale_id IN (?) and sale_status ='completed'", shift_sale_range.to_a).sum(:total_discount)
change_amount = Sale.where("sales.shop_code='#{shop_code}' and sales.shift_sale_id IN (?) and sale_status ='completed'", shift_sale_range.to_a).sum(:amount_changed)
change_amount = Sale.where("sales.shift_sale_id IN (?) and sale_status ='completed'", shift_sale_range.to_a).sum(:amount_changed)
sale_cash = Sale.select("SUM(case when (sale_payments.payment_method = 'mpu' or sale_payments.payment_method = 'visa' or sale_payments.payment_method = 'master' or sale_payments.payment_method = 'jcb' or sale_payments.payment_method = 'paypar' or sale_payments.payment_method = 'unionpay' or sale_payments.payment_method = 'alipay' sale_payments.payment_method = 'paymal' or sale_payments.payment_method = 'dinga' or sale_payments.payment_method = 'JunctionPay' or sale_payments.payment_method = 'giftvoucher') then (sale_payments.payment_amount) else 0 end) as card_amount,
SUM(case when (sale_payments.payment_method='cash') then (sale_payments.payment_amount) else 0 end) as cash_amount,
SUM(case when (sale_payments.payment_method='creditnote') then (sale_payments.payment_amount) else 0 end) as credit_amount,
SUM(case when (sale_payments.payment_method='foc') then (sale_payments.payment_amount) else 0 end) as foc_amount")
.joins("join sale_payments on sale_payments.sale_id = sales.sale_id")
.where("sales.shop_code='#{shop_code}' and sales.shift_sale_id in (?) and sale_status = 'completed' and sale_payments.payment_amount != 0 ", shift_sale_range.to_a)
.where("sales.shift_sale_id in (?) and sale_status = 'completed' and sale_payments.payment_amount != 0 ", shift_sale_range.to_a)
sale_cash.each do |s_c|
total_cash_amount += s_c.cash_amount.to_f
total_card_amount += s_c.card_amount.to_f
@@ -1209,20 +1146,20 @@ def self.get_staff_meal_items(shift_sale_range, shift, from, to, status,account_
total_grand_total = total_cash_amount.to_f + total_card_amount.to_f + total_credit_amount.to_f
else
query = query.where("sales.shop_code='#{shop_code}' and sales.receipt_date between ? and ? #{account_type} and sale_status='completed' and sales.customer_id IN(#{customer_id})",from,to)
query = query.where("sales.receipt_date between ? and ? #{account_type} and sale_status='completed' and sales.customer_id IN(#{customer_id})",from,to)
# if type.nil? || type == 'all' || type == "other"
# other_charges = other_charges.where("sales.receipt_date between ? and ? and sale_status='completed'",from,to)
# end
product = product.where("sales.shop_code='#{shop_code}' and sales.receipt_date between ? and ? and sale_status='completed'",from,to)
product = product.where("sales.receipt_date between ? and ? and sale_status='completed'",from,to)
discount_query = Sale.where("sales.shop_code='#{shop_code}' and sales.receipt_date between ? and ? and sale_status ='completed'", from,to).sum(:total_discount)
change_amount = Sale.where("sales.shop_code='#{shop_code}' and sales.receipt_date between ? and ? and sale_status ='completed'", from,to).sum(:amount_changed)
discount_query = Sale.where("sales.receipt_date between ? and ? and sale_status ='completed'", from,to).sum(:total_discount)
change_amount = Sale.where("sales.receipt_date between ? and ? and sale_status ='completed'", from,to).sum(:amount_changed)
sale_cash = Sale.select("SUM(case when (sale_payments.payment_method = 'mpu' or sale_payments.payment_method = 'visa' or sale_payments.payment_method = 'master' or sale_payments.payment_method = 'jcb' or sale_payments.payment_method = 'paypar' or sale_payments.payment_method = 'unionpay' or sale_payments.payment_method = 'alipay' or sale_payments.payment_method = 'paymal' or sale_payments.payment_method = 'dinga' or sale_payments.payment_method = 'JunctionPay' or sale_payments.payment_method = 'giftvoucher') then (sale_payments.payment_amount) else 0 end) as card_amount,
SUM(case when (sale_payments.payment_method='cash') then (sale_payments.payment_amount) else 0 end) as cash_amount,
SUM(case when (sale_payments.payment_method='creditnote') then (sale_payments.payment_amount) else 0 end) as credit_amount,
SUM(case when (sale_payments.payment_method='foc') then (sale_payments.payment_amount) else 0 end) as foc_amount")
.joins("join sale_payments on sale_payments.sale_id = sales.sale_id")
.where("sales.shop_code='#{shop_code}' and sales.receipt_date between ? and ? and sale_status = 'completed' and sale_payments.payment_amount != 0 ", from,to)
.where("sales.receipt_date between ? and ? and sale_status = 'completed' and sale_payments.payment_amount != 0 ", from,to)
sale_cash.each do |s_c|
total_cash_amount += s_c.cash_amount.to_f
total_card_amount += s_c.card_amount.to_f
@@ -1301,7 +1238,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)
@@ -1319,7 +1256,7 @@ def self.get_shift_sales_by_receipt_no_detail(shift_sale_range,shift,from,to,pay
return query
end
def self.get_by_shift_sale_credit_payment(shift_sale_range,shift,from,to,filter,order_source,shop_code)
def self.get_by_shift_sale_credit_payment(shift_sale_range,shift,from,to,filter,order_source)
payments_for_credits = SalePayment.select("
sales.sale_id,
DATE_FORMAT(CONVERT_TZ(sale_payments.created_at,'+00:00','+06:30'),'%d %b %y %h:%i%p') as credit_payment_receipt_date,
@@ -1328,8 +1265,7 @@ def self.get_by_shift_sale_credit_payment(shift_sale_range,shift,from,to,filter,
CONCAT(DATE_FORMAT(CONVERT_TZ(shift_sales.shift_started_at,'+00:00','+06:30'),'%d %b %y %h:%i%p'),' - ',DATE_FORMAT(CONVERT_TZ(shift_sales.shift_closed_at,'+00:00','+06:30'),'%d %b %y %h:%i%p')) as credit_payment_shift_name")
.joins(:sale_audit)
.joins(:sale => :shift_sale)
.joins(:sale => :cashier)
.where("sales.shop_code='#{shop_code}'").to_sql
.joins(:sale => :cashier).to_sql
credits = SalePayment.select("
sale_payments.sale_payment_id,
@@ -1354,16 +1290,16 @@ def self.get_by_shift_sale_credit_payment(shift_sale_range,shift,from,to,filter,
if order_source.present?
if order_source == "cashier"
credits = credits.where("order_sources.source IN (?)", ['cashier', 'emenu'])
credits = credits.where("orders.source IN (?)", ['cashier', 'emenu'])
else
credits = credits.where("order_sources.source = ?", order_source)
credits = credits.where("orders.source = ?", order_source)
end
end
if filter == 'paid'
credits = credits.where("payments_for_credits IS NOT NULL")
credits = credits.where("payments_for_credits.sale_id IS NOT NULL")
elsif filter == 'unpaid'
credits = credits.where("payments_for_credits IS NULL")
credits = credits.where("payments_for_credits.sale_id IS NULL")
end
if shift.present?
@@ -1376,11 +1312,10 @@ def self.get_by_shift_sale_credit_payment(shift_sale_range,shift,from,to,filter,
credits = credits.group("sale_payments.sale_payment_id, sales_sale_payments.sale_id")
end
def self.get_void_sale(shift,from,to,shop_code)
def self.get_void_sale(shift,from,to)
sale_arr = Array.new
query = Sale.select("sales.receipt_no,sales.receipt_date, sales.payment_status, sales.sale_status,sales.total_amount,sales.grand_total, sales.rounding_adjustment")
.where("sales.shop_code='#{shop_code}'")
# .joins("INNER JOIN shift_sales sh ON sh.id = sales.shift_sale_id")
# .where("sales.sale_status = 'void' and (sh.shift_started_at between ? and ?
# OR sh.shift_closed_at between ? and ? )", from ,to, from, to)
@@ -1430,96 +1365,57 @@ def self.get_separate_tax(shift_sale_range=nil,shift,from,to,payment_type)
end
end
def self.get_payment_method_by_shift(shift_sale_range,shift,from,to,payment_type,shop_code)
sub_query = "SELECT (CASE WHEN SUM(sale_payments.payment_amount) > 0 THEN SUM(sale_payments.payment_amount) ELSE 0 END)
FROM sale_payments
INNER JOIN sale_audits sa
ON SUBSTRING_INDEX(sa.remark,'||',1)=sale_payments.sale_payment_id
INNER JOIN sales ON sa.sale_id = sales.sale_id
WHERE sales.sale_status='completed' and sales.shop_code='#{shop_code}'"
def self.get_payment_method_by_shift(shift_sale_range,shift,from,to,payment_type)
payments_total = SalePayment.select("
sales.receipt_date as sale_date,
SUM(case when (sale_payments.payment_method='mpu') then sale_payments.payment_amount else 0 end) as mpu_amount,
SUM(case when (sale_payments.payment_method='master') then sale_payments.payment_amount else 0 end) as master_amount,
SUM(case when (sale_payments.payment_method='visa') then sale_payments.payment_amount else 0 end) as visa_amount,
SUM(case when (sale_payments.payment_method='jcb') then sale_payments.payment_amount else 0 end) as jcb_amount,
SUM(case when (sale_payments.payment_method='paypar') then sale_payments.payment_amount else 0 end) as paypar_amount,
SUM(case when (sale_payments.payment_method='unionpay') then sale_payments.payment_amount else 0 end) as unionpay_amount,
SUM(case when (sale_payments.payment_method='alipay') then sale_payments.payment_amount else 0 end) as alipay_amount,
SUM(case when (sale_payments.payment_method='KBZPay') then sale_payments.payment_amount else 0 end) as kbzpay_amount,
SUM(case when (sale_payments.payment_method='paymal') then sale_payments.payment_amount else 0 end) as paymal_amount,
SUM(case when (sale_payments.payment_method='dinga') then sale_payments.payment_amount else 0 end) as dinga_amount,
SUM(case when (sale_payments.payment_method='JunctionPay') then sale_payments.payment_amount else 0 end) as junctionpay_amount,
SUM(case when (sale_payments.payment_method='cash') then sale_payments.payment_amount else 0 end) as cash_amount,
SUM(case when (sale_payments.payment_method='cash') then
sales.amount_changed else 0 end) as total_change_amount,
SUM(case when (sale_payments.payment_method='creditnote') then
sale_payments.payment_amount else 0 end) -
SUM(case when (sale_audits.sale_audit_id IS NOT NULL) then
sale_payments.payment_amount else 0 end) as credit_amount,
SUM(case when (sale_payments.payment_method='giftvoucher') then sale_payments.payment_amount else 0 end) as giftvoucher_amount,
SUM(case when (sale_payments.payment_method='foc') then sale_payments.payment_amount else 0 end) as foc_amount")
.joins(:sale).left_joins(:sale_audit)
.merge(Sale.completed.receipt_date_between(from, to))
sales = Sale.select(Sale.column_names)
.select("SUM(sale_payments.payment_amount) as payment_for_credits_amount")
.left_joins(:payments_for_credits)
.group(:sale_id)
sale_payment = SalePayment.select("sales.amount_changed as change_amount,sales.receipt_no, sale_payments.*, sales.receipt_date as sale_date,
sales.cashier_name as cashier_name")
.joins("JOIN (#{sales.to_sql}) as sales ON sales.sale_id = sale_payments.sale_id")
.where("sale_payments.payment_method != 'creditnote' OR payment_for_credits_amount - sale_payments.payment_amount <= 0")
.where.not(payment_amount: 0)
.merge(Sale.completed.receipt_date_between(from, to))
if shift.present?
shift_ids = shift.map(&:id).join(",")
sub_query += " AND sales.shift_sale_id in (#{shift_ids})"
payments_total = payments_total.where(sales: {shift_sale_id: shift.to_a})
sale_payment = sale_payment.merge(Sale.where(sales: {shift_sale_id: shift.to_a}))
elsif shift_sale_range.present?
shift_ids = shift_sale_range.map(&:id).join(",")
sub_query += " AND sales.shift_sale_id in (#{shift_ids})"
else
sub_query += " AND sales.receipt_date between '#{from}' and '#{to}'"
payments_total = payments_total.where(sales: {shift_sale_id: shift_sale_range.to_a})
sale_payment = sale_payment.merge(Sale.where(sales: {shift_sale_id: shift_sale_range.to_a}))
end
sub_query1 = "CASE WHEN (SELECT SUM(sale_payments.payment_amount)
FROM sale_payments
WHERE sale_payments.payment_method = 'creditnote'
AND sale_payments.sale_id = s.sale_id
) - (SELECT SUM(sale_payments.payment_amount)
FROM sale_payments
INNER JOIN sale_audits ON SUBSTRING_INDEX(sale_audits.remark,'||',1)=sale_payments.sale_payment_id
WHERE sale_payments.sale_id = s.sale_id) = 0
THEN sale_payments.sale_id = s.sale_id
AND sale_payments.payment_method!='creditnote' ELSE 1 END"
sale_payment = SalePayment.select("s.amount_changed as change_amount,s.receipt_no, sale_payments.*,s.receipt_date as sale_date,
s.cashier_name as cashier_name")
.joins("INNER JOIN sales s ON s.sale_id = sale_payments.sale_id")
.where("(#{sub_query1}) and s.shop_code='#{shop_code}'")
.order('s.receipt_no DESC')
payments_total = SalePayment.select("CAST((CONVERT_TZ(sales.receipt_date,'+00:00','+06:30')) AS DATE) as sale_date,
SUM(case when (sale_payments.payment_method='mpu') then sale_payments.payment_amount else 0 end) as mpu_amount,
SUM(case when (sale_payments.payment_method='master') then sale_payments.payment_amount else 0 end) as master_amount,
SUM(case when (sale_payments.payment_method='visa') then sale_payments.payment_amount else 0 end) as visa_amount,
SUM(case when (sale_payments.payment_method='jcb') then sale_payments.payment_amount else 0 end) as jcb_amount,
SUM(case when (sale_payments.payment_method='paypar') then sale_payments.payment_amount else 0 end) as paypar_amount,
SUM(case when (sale_payments.payment_method='unionpay') then sale_payments.payment_amount else 0 end) as unionpay_amount,
SUM(case when (sale_payments.payment_method='alipay') then sale_payments.payment_amount else 0 end) as alipay_amount,
SUM(case when (sale_payments.payment_method='KBZPay') then sale_payments.payment_amount else 0 end) as kbzpay_amount,
SUM(case when (sale_payments.payment_method='paymal') then sale_payments.payment_amount else 0 end) as paymal_amount,
SUM(case when (sale_payments.payment_method='dinga') then sale_payments.payment_amount else 0 end) as dinga_amount,
SUM(case when (sale_payments.payment_method='JunctionPay') then sale_payments.payment_amount else 0 end) as junctionpay_amount,
SUM(case when (sale_payments.payment_method='cash') then sale_payments.payment_amount else 0 end) as cash_amount,
SUM(case when (sale_payments.payment_method='cash') then sales.amount_changed else 0 end) as total_change_amount,
(CASE WHEN (SUM(case when (sale_payments.payment_method='creditnote') then sale_payments.payment_amount else 0 end)) > 0 THEN (SUM(case when (sale_payments.payment_method='creditnote') then sale_payments.payment_amount else 0 end) - (#{sub_query})) ELSE 0 END) as credit_amount,
SUM(case when (sale_payments.payment_method='giftvoucher') then sale_payments.payment_amount else 0 end) as giftvoucher_amount,
SUM(case when (sale_payments.payment_method='foc') then sale_payments.payment_amount else 0 end) as foc_amount")
.joins("join sales on sales.sale_id = sale_payments.sale_id")
.where("sales.shop_code='#{shop_code}'")
if shift.present?
all_total = payments_total.where("sales.shift_sale_id in (?) and sale_status= 'completed' and sale_payments.payment_amount != 0", shift.to_a)
# .group("DATE_FORMAT((CONVERT_TZ(sales.receipt_date,'+00:00','+06:30')),'%Y-%m-%d')")
if payment_type.blank?
sale_type = sale_payment.where(" s.sale_status = 'completed' and payment_amount != 0 and s.shift_sale_id in (?)",shift.to_a)
.order("payment_method")
else
sale_type = sale_payment.where(" payment_method= '#{payment_type}' and payment_amount != 0 and s.sale_status = 'completed' and s.shift_sale_id in (?)",shift.to_a)
end
elsif shift_sale_range.present?
all_total = payments_total.where("sales.shift_sale_id in (?) and sale_status= 'completed' and sale_payments.payment_amount != 0", shift_sale_range.to_a)
# .group("DATE_FORMAT((CONVERT_TZ(sales.receipt_date,'+00:00','+06:30')),'%Y-%m-%d')")
if payment_type.blank?
sale_type = sale_payment.where(" s.sale_status = 'completed' and payment_amount != 0 and s.shift_sale_id in (?)",shift_sale_range.to_a)
.order("payment_method")
else
sale_type = sale_payment.where(" payment_method='#{payment_type}' and payment_amount != 0 and s.sale_status = 'completed' and s.shift_sale_id in (?)",shift_sale_range.to_a)
end
else
all_total = payments_total.where("sales.receipt_date between ? and ? and sales.sale_status= 'completed' and sale_payments.payment_amount != 0", from,to)
# .group("DATE_FORMAT((CONVERT_TZ(sales.receipt_date,'+00:00','+06:30')),'%Y-%m-%d')")
if payment_type.blank?
sale_type = sale_payment.where(" s.sale_status = 'completed' and payment_amount != 0 and s.receipt_date between ? and ? ",from,to)
.order("payment_method")
else
sale_type = sale_payment.where(" payment_method='#{payment_type}' and payment_amount != 0 and s.sale_status = 'completed' and s.receipt_date between ? and ? ",from,to)
end
if payment_type.present?
sale_payment = sale_payment.where(payment_method: payment_type)
end
return all_total,sale_type
return payments_total, sale_payment
end
def self.get_wastes_and_spoilages(from,to,status)
@@ -1552,10 +1448,10 @@ end
cash = 0.0
self.sale_payments.each do |pay|
if pay.payment_method == 'cash'
cash = pay.payment_amount-self.amount_changed
cash += pay.payment_amount
end
end
return cash
return cash - self.amount_changed
end
def get_credit_amount
@@ -1592,7 +1488,7 @@ end
def self.top_bottom_products(current_user,from,to,type,current_shop)
query = Sale.joins("JOIN sale_items ON sale_items.sale_id = sales.sale_id")
.completed
.where("qty > 0 AND price > 0 AND shop_code='#{current_shop.shop_code}'")
.where("qty > 0 AND price > 0")
.group("SUBSTRING_INDEX(product_name, ' - ', 1)")
if !from.nil? && !to.nil?
@@ -1704,7 +1600,7 @@ end
query = SalePayment.credits
.joins(:sale)
.joins("LEFT JOIN (#{payments_for_credits}) payments_for_credits ON payments_for_credits.sale_id = sale_payments.sale_id")
.where("sale_payments.payment_method= ? AND sales.sale_status = ? AND sales.shop_code=?", 'creditnote', 'completed',current_shop.shop_code)
.where("sale_payments.payment_method= ? AND sales.sale_status = ?", 'creditnote', 'completed')
if (!from.nil? && !to.nil?)
query = query.merge(Sale.receipt_date_between(from, to))
@@ -1922,7 +1818,6 @@ end
query = Sale.select("count(distinct sale_orders.order_id) as total_order")
.joins(:sale_orders)
.where("shop_code='#{current_shop.shop_code}'")
.completed
if (!from.nil? && !to.nil?)
@@ -2133,6 +2028,7 @@ end
def unique_tax_profiles(order_source, customer_id)
puts "unique_tax_profiles unique_tax_profiles"
tax_data = TaxProfile.where(group_type: order_source)
customer_tax_profiles = Customer.select(:tax_profiles).where(customer_id: customer_id).first
if customer_tax_profiles.present?
tax_data = tax_data.where(id: customer_tax_profiles.tax_profiles)
@@ -2162,7 +2058,7 @@ def self.employee_sale(shift=nil,from=nil,to=nil,from_time=nil,to_time=nil, curr
end
# Start hourly sale item report
def self.get_by_hourly_items(shift_sale_range, shift, from, to, status,type,account_type,shop_code)
def self.get_by_hourly_items(shift_sale_range, shift, from, to, status,type,account_type,filter,start_time,end_time)
# date_type_selection = get_sql_function_for_report_type(report_type)
if account_type.blank?
account_type = ''
@@ -2170,7 +2066,26 @@ def self.get_by_hourly_items(shift_sale_range, shift, from, to, status,type,acco
account_type = " and acc.title = '#{account_type}'"
end
query = self.get_hourly_item_query(type)
if start_time.blank? || end_time.blank?
receipt_date = "sales.receipt_date between '#{from}' and '#{to}'"
query = self.get_hourly_item_query(type,filter,true)
else
start_time = Time.parse(start_time).utc
end_time = Time.parse(end_time).utc
receipt_date = "sales.receipt_date between '#{start_time}' and '#{end_time}'"
query = self.get_hourly_item_query(type,filter,false)
end
unless start_time.blank? && end_time.blank?
from_date = from.to_date
to_date = to.to_date
from_date_time = DateTime.new(from_date.year, from_date.month, from_date.day, start_time.hour, start_time.min, start_time.sec, start_time.zone)
to_date_time = DateTime.new(to_date.year, to_date.month, to_date.day, end_time.hour, end_time.min, end_time.sec, end_time.zone)
receipt_date = "sales.receipt_date between '#{from_date_time}' and '#{to_date_time}'"
query = self.get_hourly_item_query(type,filter,false)
end
# query = self.get_hourly_item_query(type,filter)
discount_query = 0
total_card_amount = 0
@@ -2231,7 +2146,7 @@ def self.get_by_hourly_items(shift_sale_range, shift, from, to, status,type,acco
total_grand_total = total_cash_amount.to_f + total_card_amount.to_f + total_credit_amount.to_f
else
query = query.where("sales.receipt_date between ? and ? #{account_type} and sale_status='completed'",from,to)
query = query.where("#{receipt_date} #{account_type} and sale_status='completed'")
if type.nil? || type == 'all' || type == "other"
other_charges = other_charges.where("sales.receipt_date between ? and ? and sale_status='completed'",from,to)
end
@@ -2258,11 +2173,16 @@ def self.get_by_hourly_items(shift_sale_range, shift, from, to, status,type,acco
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_hourly_item_query(type)
def self.get_hourly_item_query(type,filter,status)
if status
group_by = "acc.title,i.account_id,i.menu_category_code,i.item_instance_code,i.product_name,i.unit_price,hour"
else
group_by = "acc.title,i.account_id,i.menu_category_code,i.item_instance_code,i.product_name,i.unit_price"
end
check_product = "i.menu_category_name != 'product'"
if type == "revenue"
sale_type = "i.qty > 0 and status IS NULL"
elsif type == "all" || type.nil?
elsif type == "all" || type.nil? || type.empty?
sale_type = "#{check_product}"
elsif type == "discount"
sale_type = "#{check_product} and i.status = 'Discount'"
@@ -2290,8 +2210,8 @@ def self.get_hourly_item_query(type)
" JOIN shift_sales sh ON sh.`id` = sales.shift_sale_id")
# "JOIN employee_accesses ea ON ea.`employee_id` = sales.cashier_id ")
query = query.joins(" JOIN accounts acc ON acc.id = i.account_id")
query = query.where("#{sale_type}")
query = query.group("acc.title,i.account_id,i.menu_category_code,i.item_instance_code,i.product_name,i.unit_price,hour")
query = query.where("#{sale_type} and i.product_name LIKE '%#{filter}%'" )
query = query.group("#{group_by}")
.order("hour asc")
# query = query.order("i.menu_category_name asc, SUM(i.qty) desc")
end
@@ -2437,8 +2357,8 @@ def self.get_check_sale_data(transaction_date)
.group("sales.receipt_no,sales.sale_status")
end
def paymal_payment_void
membership_setting = MembershipSetting.find_by_membership_type_and_shop_code("paypar_url",self.shop_code)
membership_actions_data = MembershipAction.find_by_membership_type_and_shop_code("void",self.shop_code)
membership_setting = MembershipSetting.find_by_membership_type("paypar_url")
membership_actions_data = MembershipAction.find_by_membership_type("void")
if !membership_actions_data.nil?
sale_payments =self.sale_payments.where("payment_reference is not null")
if !sale_payments.empty?

View File

@@ -6,7 +6,7 @@ class SaleAudit < ApplicationRecord
belongs_to :sale
belongs_to :sale_payments_for_credit, -> { where "SUBSTRING_INDEX(sale_audits.remark,'||',1) = sale_payments.sale_payment_id" }, foreign_key: "sale_id", primary_key: "sale_id", class_name: "SalePayment"
belongs_to :payments_for_credit, -> { where "SUBSTRING_INDEX(sale_audits.remark,'||',1) = sale_payments.sale_payment_id" }, foreign_key: "sale_id", primary_key: "sale_id", class_name: "SalePayment"
def self.sync_sale_audit_records(sale_audits)
if !sale_audits.nil?
@@ -124,6 +124,17 @@ class SaleAudit < ApplicationRecord
sale_audit.save!
end
def self.record_audit_change_tax(sale_id, remark, action_by)
sale_audit = SaleAudit.new()
sale_audit.sale_id = sale_id
sale_audit.action = "CHANGE_TAX"
sale_audit.action_at = DateTime.now.utc
sale_audit.action_by = action_by
sale_audit.remark = remark
sale_audit.approved_by = action_by
sale_audit.save!
end
def self.paymal_search(sale_id)
amount = nil
paymal = SaleAudit.where("sale_id =? and action = 'PAYMAL'",sale_id)

View File

@@ -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?

View File

@@ -34,9 +34,9 @@ class SalePayment < ApplicationRecord
end
end
def self.get_kbz_pay_amount(sale_id, current_user,shop)
def self.get_kbz_pay_amount(sale_id, current_user)
amount = 0
kbz_pay_method = PaymentMethodSetting.where(:payment_method => KbzPay::KBZ_PAY,:shop_code => shop.shop_code).last
kbz_pay_method = PaymentMethodSetting.where(:payment_method => KbzPay::KBZ_PAY).last
sale_payment = SalePayment.where('sale_id=? and payment_method=? and payment_status!=?', sale_id, KbzPay::KBZ_PAY, 'dead').last
if !sale_payment.nil? and !kbz_pay_method.nil?
if sale_payment.payment_status == 'pending'
@@ -66,32 +66,26 @@ 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
self.action_by = action_by
#get all payment for this invoices
if payment_for
invoice_sale_payments = SalePayment.get_sale_payment_for_credit(invoice)
amount_due = SalePayment.get_credit_amount_due_left(self.sale_id)[0] ? SalePayment.get_credit_amount_due_left(self.sale_id)[0].payment_amount.to_f : 0
amount_due = SalePayment.get_credit_amount_due_left(self.sale_id).first.payment_amount
else
invoice_sale_payments = invoice.sale_payments
amount_due = invoice.grand_total
amount_due = invoice.sale_payments
.map(&:payment_amount).reduce(invoice.grand_total, :-)
end
invoice_sale_payments.each do |payment|
if (payment.payment_status == "paid" )
amount_due = amount_due - payment.payment_amount
end
end
if (amount_due > 0)
if amount_due > 0
payment_status = false
membership_data = nil
#route to payment type
case payment_method
when "cash"
payment_status ,outstanding_amount ,balance_amount = cash_payment(payment_for)
payment_status, outstanding_amount, balance_amount = cash_payment(payment_for)
when "creditnote"
if !self.sale.customer_id.nil?
payment_status = creditnote_payment(self.customer_id)
@@ -156,7 +150,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
@@ -164,7 +158,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 +167,7 @@ class SalePayment < ApplicationRecord
return false, self.save,membership_data
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)
@@ -300,7 +295,7 @@ class SalePayment < ApplicationRecord
def self.create_payment(paypar_url,payment_type,membership_id,received_amount,sale_id)
# membership_actions_data = MembershipAction.find_by_membership_type("create_payment");
sale_data = Sale.find_by_sale_id(sale_id)
membership_actions_data = PaymentMethodSetting.find_by_payment_method_and_shop_code(payment_type,sale_data.shop_code)
membership_actions_data = PaymentMethodSetting.find_by_payment_method(payment_type)
customer_data = Customer.find_by_customer_id(sale_data.customer_id)
if !membership_actions_data.nil?
@@ -412,19 +407,19 @@ class SalePayment < ApplicationRecord
def foc_payment
payment_status = false
sale = self.sale
# add to sale item with foc
sale_items = SaleItem.where("sale_id='#{ self.sale.sale_id }'")
sale_items = sale.sale_items
sale_items.each do|item|
SaleItem.update_existing_item(item.qty, item, self.sale.sale_id, "foc", item.unit_price, item.price)
SaleItem.update_existing_item(item.qty, item, sale.sale_id, "foc", item.unit_price, item.price)
end
sale = Sale.find(self.sale.sale_id)
sale.compute_by_sale_items(sale.total_discount,'','','',"foc")
self.payment_method = "foc"
self.payment_amount = self.received_amount
# self.outstanding_amount = self.sale.grand_total.to_f - self.received_amount.to_f
self.outstanding_amount = 0.00
self.payment_status = "paid"
payment_status = self.save!
@@ -535,7 +530,7 @@ class SalePayment < ApplicationRecord
#Next time - validate if the vochure number is valid - within
account_no = self.payment_reference
# self.sale.customer.update_attributes(paypar_account_no: )
membership_setting = MembershipSetting.find_by_membership_type_and_shop_code("paypar_url",self.sale.shop_code)
membership_setting = MembershipSetting.find_by_membership_type("paypar_url")
membership_data = SalePayment.create_payment(membership_setting.gateway_url,"PAYMAL",account_no,self.received_amount,self.sale.sale_id)
#record an payment in sale-audit
@@ -633,85 +628,61 @@ 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 || spay.payment_method =="paymal"
method_status = true
end
end
if (self.sale.grand_total <= all_received_amount) && method_status
if is_credit == 0
self.sale.payment_status = "paid"
else
self.sale.payment_status = "outstanding"
sale = self.sale
total_payment_amount = sale.sale_payments.reload.sum(&:payment_amount)
sale.amount_received = sale.amount_received.to_f + paid_amount.to_f
sale.amount_changed = total_payment_amount - sale.grand_total.to_f
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 <= total_payment_amount && sale.sale_status == "new"
sale.payment_status = "paid"
if is_credit
sale.payment_status = "outstanding"
end
if is_foc
sale.payment_status = "foc"
end
if is_foc == 0
self.sale.payment_status = "paid"
else
self.sale.payment_status = "foc"
end
sale.sale_status = "completed"
if is_kbz_pay == 1
self.sale.payment_status = 'paid'
end
self.sale.sale_status = "completed"
if MembershipSetting.find_by_rebate_and_shop_code(1,self.sale.shop_code) && is_foc == 0 && is_credit == 0
response = rebat(sObj)
if MembershipSetting.find_by_rebate(1) && is_foc == 0 && is_credit == 0
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
@@ -734,7 +705,7 @@ class SalePayment < ApplicationRecord
self.sale.cashier_name = Employee.find(shift.employee_id).name
self.sale.save
else
shift = ShiftSale.current_shift(self.sale.shop_code)
shift = ShiftSale.current_shift
shift.update(self.sale)
self.sale.shift_sale_id = shift.id
self.sale.cashier_id = shift.employee_id
@@ -745,7 +716,8 @@ class SalePayment < ApplicationRecord
# update for shift with credit payment
def update_shift_for_credit_payment
shift = ShiftSale.find_by_id(self.sale.shift_sale_id)
shift_credit = ShiftSale.find_by_id(self.sale.shift_sale_id)
shift = ShiftSale.find_by_id(ShiftSale.current_shift)
if !shift.nil?
credit_payment_left = get_credit_payment_left[0].payment_amount.to_f
if self.payment_method == "cash"
@@ -763,41 +735,28 @@ class SalePayment < ApplicationRecord
shift.other_sales = shift.other_sales.to_f + self.received_amount.to_f
end
if credit_payment_left == 0 || credit_payment_left >= self.received_amount.to_f
shift.credit_sales = shift.credit_sales.to_f - self.received_amount.to_f
if shift.id == shift_credit.id
shift.credit_sales = shift_credit.credit_sales.to_f - self.received_amount.to_f
end
else
shift.credit_sales = shift.credit_sales.to_f - (self.received_amount.to_f + credit_payment_left)
shift.credit_sales = shift_credit.credit_sales.to_f - (self.received_amount.to_f + credit_payment_left)
end
shift.save
end
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
@@ -824,8 +783,8 @@ class SalePayment < ApplicationRecord
overall_dis = sObj.total_discount
if credit != 1
membership = MembershipSetting.find_by_membership_type_and_shop_code("paypar_url",sObj.shop_code)
memberaction = MembershipAction.find_by_membership_type_and_shop_code("get_member_campaign",sObj.shop_code)
membership = MembershipSetting.find_by_membership_type("paypar_url")
memberaction = MembershipAction.find_by_membership_type("get_member_campaign")
merchant_uid = memberaction.merchant_account_id.to_s
campaign_type_id = memberaction.additional_parameter["campaign_type_id"]
auth_token = memberaction.auth_token.to_s
@@ -909,8 +868,8 @@ class SalePayment < ApplicationRecord
if total_amount >= 0
receipt_no = sObj.receipt_no
membership = MembershipSetting.find_by_membership_type_and_shop_code("paypar_url",sObj.shop_code)
memberaction = MembershipAction.find_by_membership_type_and_shop_code("rebate",sObj.shop_code)
membership = MembershipSetting.find_by_membership_type("paypar_url")
memberaction = MembershipAction.find_by_membership_type("rebate")
merchant_uid = memberaction.merchant_account_id.to_s
campaign_type_id = memberaction.additional_parameter["campaign_type_id"]
auth_token = memberaction.auth_token.to_s
@@ -955,13 +914,16 @@ class SalePayment < ApplicationRecord
#credit payment query
def self.get_credit_sales(params)
total_payment_amounts = SalePayment.select("sale_payments.sale_id, SUM(sale_payments.payment_amount) as total_payment_amount").group(:sale_id)
payments = SalePayment.select("sale_payments.sale_id, sale_payments.sale_payment_id, sale_payments.payment_method, sale_payments.payment_amount")
.select("SUM(sale_payments.payment_amount) OVER (PARTITION BY sale_payments.sale_id) total_payment_amount")
.select("total_payment_amount")
.joins("JOIN (#{total_payment_amounts.to_sql}) AS total_payment_amounts ON total_payment_amounts.sale_id = sale_payments.sale_id")
credit_sales = Sale.select("sales.sale_id, sales.receipt_no, sales.receipt_date as sale_date, sales.cashier_name")
.select("sale_payments.sale_payment_id, sale_payments.payment_amount").select("customers.name as customer_name")
.joins("JOIN (#{payments.to_sql}) AS sale_payments ON sale_payments.sale_id = sales.sale_id").joins(:customer).joins(:orders)
.completed.paid.where("sale_payments.payment_method = 'creditnote' AND sales.grand_total > sale_payments.total_payment_amount - sale_payments.payment_amount").shop
.completed.where("sale_payments.payment_method = 'creditnote' AND sales.grand_total > sale_payments.total_payment_amount - sale_payments.payment_amount")
.group(:receipt_no)
.order(:receipt_date).order(:receipt_no)
@@ -984,64 +946,29 @@ class SalePayment < ApplicationRecord
end
def self.get_credit_amount_due_left(sale_id)
query = SalePayment.select("(SUM(sale_payments.payment_amount) -
(CASE WHEN SUBSTRING_INDEX(sa.remark,'||',1)=sale_payments.sale_payment_id
THEN SUM(sale_payments.payment_amount) ELSE 0 END)) as payment_amount")
.joins(" LEFT JOIN sale_audits sa on SUBSTRING_INDEX(sa.remark,'||',1)=sale_payments.sale_payment_id")
.where("sale_payments.payment_method = 'creditnote' AND sale_payments.sale_id = '#{sale_id}'")
return query
SalePayment.left_joins(:sale_audit).where(sale_id: sale_id)
.select("SUM(CASE WHEN sale_payments.payment_method = 'creditnote' THEN sale_payments.payment_amount ELSE 0 END) - SUM(CASE WHEN sale_audits.sale_audit_id IS NOT NULL THEN sale_payments.payment_amount ELSE 0 END) AS payment_amount")
end
def self.get_credit_total_left(sale_id)
query = SalePayment.select("(SUM(sale_payments.payment_amount) -
(SELECT (CASE WHEN SUM(sale_payments.payment_amount) > 0 THEN SUM(sale_payments.payment_amount) ELSE 0 END) AS payment_amount
FROM sale_payments
INNER JOIN sale_audits ON SUBSTRING_INDEX(sale_audits.remark,'||',1)=sale_payments.sale_payment_id
WHERE sale_payments.sale_id = '#{sale_id}')) as payment_amount")
.where("sale_payments.payment_method = 'creditnote' AND sale_payments.sale_id = '#{sale_id}'")
return query
SalePayment.left_joins(:sale_audit).where(sale_id: sale_id)
.select("SUM(CASE WHEN sale_payments.payment_method = 'creditnote' THEN sale_payments.payment_amount ELSE 0 END) - SUM(CASE WHEN sale_audits.sale_audit_id IS NOT NULL THEN sale_payments.payment_amount ELSE 0 END) AS payment_amount")
end
def self.get_sale_payment_for_credit(sale_data)
query = sale_data.sale_payments
.joins(" JOIN sale_audits sa on SUBSTRING_INDEX(sa.remark,'||',1)=sale_payments.sale_payment_id")
.where("sa.action='SALEPAYMENT' AND sa.remark IS NOT NULL
AND DATE_FORMAT(sale_payments.created_at,'%Y-%m-%d') = '#{DateTime.now.strftime('%Y-%m-%d')}' OR DATE_FORMAT(sale_payments.created_at,'%Y-%m-%d') = '#{Date.today.prev_day}'
") #AND sale_payments.payment_method!='cash'
.group("sale_payments.sale_payment_id")
return query
sale_data.sale_payments
.joins(:sale_audit)
end
def get_credit_payment_left
sql = "SELECT SUM(payment_amount)
from sale_payments
join sale_audits on SUBSTRING_INDEX(remark,'||',1)=sale_payment_id
where sale_payments.sale_id = '#{self.sale_id}'"
query = SalePayment.select("(SUM(payment_amount) - (#{sql})) as payment_amount")
.where("sale_payments.payment_method = 'creditnote' AND sale_payments.sale_id = '#{self.sale_id}'")
return query
SalePayment.left_joins(:sale_audit).where(sale_id: sale_id)
.select("SUM(CASE WHEN sale_payments.payment_method = 'creditnote' THEN sale_payments.payment_amount ELSE 0 END) - SUM(CASE WHEN sale_audits.sale_audit_id IS NOT NULL THEN sale_payments.payment_amount ELSE 0 END) AS payment_amount")
end
def self.get_sale_payments(sale_data)
sql = "SELECT SUM(payment_amount)
FROM sale_payments where payment_method='creditnote'
and sale_id='#{sale_data.sale_id}'"
sql1 = "SELECT CASE WHEN s.amount_changed > 0 and (s.amount_received - s.amount_changed) = s.grand_total THEN ( SELECT SUM(payment_amount)
FROM sale_payments where payment_method='creditnote'
and sale_id='#{sale_data.sale_id}'"
query = sale_data.sale_payments
.where("CASE WHEN ((#{sql}) - (#{sql1})
ELSE SUM(payment_amount) END
FROM sale_payments
JOIN sales s ON s.sale_id=sale_payments.sale_id
JOIN sale_audits sa
ON SUBSTRING_INDEX(sa.remark,'||',1)=sale_payment_id
where sa.sale_id='#{sale_data.sale_id}')) = 0
THEN payment_method!='creditnote' ELSE 1 END")
.group("sale_payments.sale_payment_id")
return query
sale_data.sale_payments
.merge(SalePayment.where.not(payment_method: 'creditnote')
.or(SalePayment.where.not(SalePayment.arel_table[:payment_amount].lteq(sale_data.sale_payments.joins(:sale_audit).sum(:payment_amount)))))
end
private
def generate_custom_id

View File

@@ -31,7 +31,7 @@ class SaleTax < ApplicationRecord
def self.get_tax(from,to)
query = SaleTax.select("sale_taxes.tax_name,SUM(sale_taxes.tax_payable_amount) as tax_amount")
.joins("join sales on sales.sale_id = sale_taxes.sale_id")
.where("sales.shop_code=? and sale_status = ? AND sales.receipt_date between ? and ? AND total_amount != 0 AND inclusive = 0",Shop.current_shop.shop_code, 'completed', from, to)
.where("sale_status = ? AND sales.receipt_date between ? and ? AND total_amount != 0 AND inclusive = 0", 'completed', from, to)
.group("sale_taxes.tax_name")
end

View File

@@ -3,19 +3,44 @@ class SeedGenerator < ApplicationRecord
def self.generate_id(model, prefix)
model_name = self.get_model_name(model)
prefix ||= ''
prefix << '-' if prefix.present?
if ENV["SERVER_MODE"] == 'cloud'
prefix = "C#{prefix}"
prefix << 'C'
else
prefix << 'L'
end
cur_val, next_val = self.update_seed(model_name)
if (cur_val == 0)
cur_val, next_val = self.execute_query(model_name)
if shop = Shop.current_shop
prefix << shop.shop_code
end
padding_len = 15 - prefix.length
saleOrderId = prefix +"-"+ cur_val.to_s.to_s.rjust((14-prefix.length)+1,'0')
return saleOrderId
seed = self.update_seed(model_name)
length = 16 - 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'
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 = 16 - prefix.length
(start..stop).map { |c| prefix + c.to_s.rjust(length, '0') }
end
def self.sync_seed_generator_records(seed_generators)
@@ -58,7 +83,7 @@ class SeedGenerator < ApplicationRecord
end
end
return new_receipt_no
return new_receipt_no
end
# Generate for 4 digit Code
@@ -85,7 +110,7 @@ class SeedGenerator < ApplicationRecord
# padding_len = 6 - prefix.length
# count = 5-prefix.length
# end
# next_code = prefix + seed.current.to_s.to_s.rjust((count)+1,'0')
# next_code = prefix + seed.current.to_s.to_s.rjust((count)+1,'0')
# return next_code
# end
@@ -100,41 +125,13 @@ class SeedGenerator < ApplicationRecord
return model_name
end
def self.execute_query(model)
current = 0
nex = 0
sql = "INSERT INTO seed_generators (model, created_at, updated_at)
VALUES('#{ model }', NOW(), NOW())
ON DUPLICATE KEY UPDATE current = current + 1, next = next + 1;"
select_sql = "select * from seed_generators where model='#{model}';"
ActiveRecord::Base.connection.execute(sql);
select_result = ActiveRecord::Base.connection.execute(select_sql);
select_result.each do |row|
current = row [3]
nex = row[4]
def self.update_seed(model, count = 1)
SeedGenerator.transaction do
seed = SeedGenerator.lock.find_by_model(model)
seed.next = seed.next + (count * seed.increase_by)
seed.current = seed.next - seed.increase_by
seed.save!
seed.next_before_last_save
end
return current, nex
end
def self.update_seed(model)
current = 0
nex = 0
update_sql = "UPDATE seed_generators set current = next, next = next + 1 WHERE model='#{model}';"
select_sql = "select * from seed_generators where model='#{model}';"
update_result = ActiveRecord::Base.connection.execute(update_sql);
select_result = ActiveRecord::Base.connection.execute(select_sql);
select_result.each do |row|
current = row [3]
nex = row[4]
end
return current, nex
end
end

View File

@@ -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
@@ -28,7 +28,7 @@ class ShiftSale < ApplicationRecord
#find open shift where is open today and is not closed and login by current cashier
#DATE(shift_started_at)=? and
today_date = DateTime.now.strftime("%Y-%m-%d")
shift = ShiftSale.where("shop_code='#{current_user.shop_code}' and shift_started_at is not null and shift_closed_at is null and employee_id = #{current_user.id}").take
shift = ShiftSale.where("shift_started_at is not null and shift_closed_at is null and employee_id = #{current_user.id}").take
return shift
#end
end
@@ -83,7 +83,6 @@ class ShiftSale < ApplicationRecord
self.shift_started_at = DateTime.now
self.employee_id = current_user.id
self.opening_balance = opening_balance
self.shop_code = current_user.shop_code
self.other_sales = 0
self.save
end

View File

@@ -2,9 +2,8 @@ class Shop < ApplicationRecord
#ShopDetail = Shop.current_shop
# Shop Image Uploader
mount_uploader :logo, ShopImageUploader
has_many :display_images
mount_uploader :logo, ShopImageUploader
has_many :display_images
accepts_nested_attributes_for :display_images

View File

@@ -1,12 +1,11 @@
class StockCheck < ApplicationRecord
has_many :stock_check_items
def create(user, reason, item_list,shop)
def create(user, reason, item_list)
self.reason = reason
self.check_by = user.id
self.check_start = Time.now
self.check_end = Time.now
self.shop_code = shop.shop_code
save
item_list.each do |item|
stockItem = StockCheckItem.new

View File

@@ -67,7 +67,7 @@ class StockCheckItem < ApplicationRecord
return query
end
def self.delete_stock_check_item(item_code,shop)
self.where("item_code=? and shop_code='#{shop.shop_code}'", item_code).delete_all
def self.delete_stock_check_item(item_code)
self.where("item_code=?", item_code).delete_all
end
end

View File

@@ -26,8 +26,7 @@ class StockJournal < ApplicationRecord
inventory_definition_id: inventory_definition.id,
remark: stock_message,
trans_ref: trans_ref,
trans_type: trans_type,
shop_code: inventory_definition.shop_code
trans_type: trans_type
)
end
@@ -35,11 +34,11 @@ class StockJournal < ApplicationRecord
return balance.to_i - qty.to_i
end
def self.from_stock_check(item,shop)
stock_journal = StockJournal.where("shop_code='#{shop.shop_code}' and item_code=?", item.item_code).order("id DESC").first
def self.from_stock_check(item)
stock_journal = StockJournal.where("item_code=?", item.item_code).order("id DESC").first
if stock_journal.nil?
old_blance = 0
inventory_definition_id = InventoryDefinition.find_by_item_code_and_shop_code(item.item_code,shop.shop_code).id
inventory_definition_id = InventoryDefinition.find_by_item_code(item.item_code).id
else
old_blance = stock_journal.balance
inventory_definition_id = stock_journal.inventory_definition_id
@@ -54,12 +53,11 @@ class StockJournal < ApplicationRecord
journal.remark = StockJournal::STOCK_CHECK_TRANS
journal.trans_ref = item.id
journal.trans_type = StockJournal::STOCK_CHECK_TRANS
journal.shop_code = shop.shop_code
journal.save
end
def self.inventory_balances(from,to, current_shop)
def self.inventory_balances(from,to)
query = StockJournal.select("mii.item_instance_name as item_instance_name,balance")
.joins("join menu_item_instances mii on mii.item_instance_code=stock_journals.item_code")
.group("mii.item_instance_name")
@@ -78,8 +76,8 @@ class StockJournal < ApplicationRecord
end
end
def self.delete_stock_journal(item_code,shop)
self.where("item_code=? and shop_code='#{shop.shop_code}'", item_code).delete_all
def self.delete_stock_journal(item_code)
self.where("item_code=?", item_code).delete_all
end
end

View File

@@ -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

View File

@@ -5,7 +5,6 @@ class Zone < ApplicationRecord
has_many :order_queue_stations
has_many :cashier_terminals
scope :shop, -> { where("shop_code=?",Shop.current_shop.shop_code) }
# validations
validates_presence_of :name, :created_by