Merge branch 'foodcourt' of gitlab.com:code2lab/SXRestaurant into foodcourt

This commit is contained in:
Myat Zin Wai Maw
2019-12-03 17:49:21 +06:30
200 changed files with 3397 additions and 2690 deletions

View File

@@ -1,3 +1,14 @@
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
def self.inherited(subclass)
super
return unless subclass.superclass == self
return unless subclass.column_names.include? 'shop_id'
subclass.class_eval do
acts_as_tenant(:shop)
end
end
end

View File

@@ -22,7 +22,7 @@ class DiningCharge < ApplicationRecord
end
return block_count, price
else
puts "<<<<<<<< NO"
Rails.logger.info "Params not enough"
end
end

View File

@@ -3,6 +3,7 @@ class Employee < ApplicationRecord
has_many :commissioners
has_many :shit_sales
belongs_to :order_queue_station
validates_presence_of :name, :role
validates_presence_of :password, :on => [:create]
validates :emp_id, uniqueness: true, numericality: true, length: {in: 1..4}, allow_blank: true
@@ -19,9 +20,9 @@ class Employee < ApplicationRecord
Employee.select("id, name").map { |e| [e.name, e.id] }
end
def self.login(shop,emp_id, password)
user = Employee.find_by_emp_id_and_shop_code(emp_id,shop.shop_code)
expiry_time = login_expiry_time(shop)
def self.login(emp_id, password)
user = Employee.find_by_emp_id(emp_id)
expiry_time = login_expiry_time
if (user)
#user.authenticate(password)
if (user.authenticate(password))
@@ -36,10 +37,10 @@ class Employee < ApplicationRecord
end
def self.authenticate_by_token(session_token,shop)
def self.authenticate_by_token(session_token)
if (session_token)
user = Employee.find_by_token_session_and_shop_code(session_token,shop.shop_code)
expiry_time = login_expiry_time(shop)
user = Employee.find_by_token_session(session_token)
expiry_time = login_expiry_time
if user && user.session_expiry.utc > DateTime.now.utc
#Extend the login time each time authenticatation take place
@@ -54,9 +55,9 @@ class Employee < ApplicationRecord
return false
end
def self.logout(shop,session_token)
def self.logout(session_token)
if (session_token)
user = Employee.find_by_token_session_and_shop_code(session_token,shop.shop_code)
user = Employee.find_by_token_session(session_token)
if user
user.token_session = nil
@@ -72,9 +73,9 @@ class Employee < ApplicationRecord
retry
end
def self.login_expiry_time(shop)
def self.login_expiry_time
expiry_time = 30
login_expiry = Lookup.where("shop_code='#{shop.shop_code}'").collection_of('expiry_time')
login_expiry = Lookup.collection_of('expiry_time')
if !login_expiry.empty?
login_expiry.each do |exp_time|
if exp_time[0].downcase == "login"

View File

@@ -23,34 +23,23 @@ class InventoryDefinition < ApplicationRecord
end
end
def self.find_product_in_inventory(item,shop_code=nil)
# unless instance_code.empty?
# instance_code = instance_code.to_s
# instance_code[0] = ""
# instance_code = instance_code.chomp("]")
# else
# instance_code = '"0"'
# end
#
# if prod = InventoryDefinition.where("item_code IN(#{instance_code})")
# puts "found prodcut+++++++++++++++++++++++++++++++++++==="
# puts prod.to_json
# end
if product = InventoryDefinition.find_by_item_code_and_shop_code(item.item_instance_code,shop_code)
if stock_check_item = StockCheckItem.find_by_item_code_and_shop_code(item.item_instance_code,shop_code)
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)
return true, product
end
end
end
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
unless stock.nil?
modify_balance(item, stock, inventory_definition)
else
puts "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< OUT OF STOCK >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
StockJournal.add_to_journal(item.item_instance_code, item.qty, 0, "out of stock", inventory_definition, item.id, StockJournal::SALES_TRANS)
end
stock = StockJournal.where("shop_code='#{inventory_definition.shop_code}' and item_code=?", item.item_instance_code).order("id DESC").first
unless stock.nil?
modify_balance(item, stock, inventory_definition)
else
StockJournal.add_to_journal(item.item_instance_code, item.qty, 0, "out of stock", inventory_definition, item.id, StockJournal::SALES_TRANS)
end
end
def self.modify_balance(item, stock, inventory_definition) #saleitemObj
@@ -75,6 +64,7 @@ class InventoryDefinition < ApplicationRecord
elsif item.is_a? SaleItem
trans_type = StockJournal::SALES_TRANS
end
# StockJournal.add_to_journal(instance_code, qty, stock.balance, remark, inventory_definition, item.id, trans_type)
StockJournal.add_to_journal(item.item_instance_code, qty, stock.balance, remark, inventory_definition, item.id, trans_type)
check_item.different = check_item.different - qty
check_item.save

View File

@@ -3,13 +3,13 @@ class KbzPay
KBZ_PAY = 'KBZPay'
def self.pay(amount, receipt_no, url, key, app_id, code)
shop = Shop.first
shop = Shop.current_shop
prefix = shop.shop_code
receipt_no = "#{prefix}#{receipt_no}"
datetime = DateTime.now.strftime("%d%m%Y%H%M")
kbz_app_id = app_id
kbz_merch_code = code
kbz_merch_code = code
kbz_api_key = key
kbz_provider_url = "#{url}/precreate"
@@ -58,17 +58,17 @@ class KbzPay
# Rails.logger.debug result['Response']
return false, result['Response']
end
end
def self.query(receipt_no, current_user, url, key, app_id, code)
shop = Shop.first
shop = Shop.current_shop
prefix = shop.shop_code
receipt_no = "#{prefix}#{receipt_no}"
amount = 0
datetime = DateTime.now.strftime("%d%m%Y%H%M")
kbz_app_id = app_id
kbz_merch_code = code
kbz_merch_code = code
kbz_api_key = key
kbz_provider_url = "#{url}/queryorder"
@@ -122,7 +122,7 @@ class KbzPay
# return true, "successfully paid by KBZ PAY"
elsif result['Response']['trade_status'] == "PAY_FAILED"
# return false, "pay failed by KBZ PAY"
elsif result['Response']['trade_status'] == "WAIT_PAY"
# return false , "Waiting to pay by KBZ PAY"
@@ -135,4 +135,4 @@ class KbzPay
return amount
end
end
end

View File

@@ -18,22 +18,22 @@ class License
if (server != "")
self.class.base_uri server
end
end
end
# For Cloud
def detail_with_local_cache(lookup)
def detail_with_local_cache(lookup)
aes = MyAesCrypt.new
aes_key, aes_iv = aes.export_to_file(lookup)
aes_key, aes_iv = aes.export_to_file(lookup)
##Check from local redis - if available load local otherwise get from remote
cache_key = "#{lookup}:license:#{aes_key}:hostname"
cache_key = "#{lookup}:license:#{aes_key}:hostname"
cache_license = nil
##Get redis connection from connection pool
redis = Redis.new
cache_license = redis.get(cache_key)
cache_license = redis.get(cache_key)
Rails.logger.info "Cache key - " + cache_key.to_s
if cache_license.nil?
##change the d/e key
@@ -41,12 +41,13 @@ class License
@params = { query: { lookup_type: self.server_mode, lookup: lookup, iv_key: aes_iv} }
response = self.class.get("/subdomain", @params)
@license = response.parsed_response
Rails.logger.info "License Response - " + response.parsed_response.to_s
if (@license["status"] == true)
assign(aes_key, aes_iv)
# Rails.logger.info "License - " + response.parsed_response.to_s
#Rails.logger.info "License - " + response.parsed_response.to_s
redis = Redis.new
redis.set(cache_key, Marshal.dump(@license))
# redis.sadd("License:cache:keys", cache_key)
@@ -59,36 +60,36 @@ class License
return true
end
else
else
@license = Marshal.load(cache_license)
assign(aes_key, aes_iv)
# Rails.logger.info 'API License'
# Rails.logger.info 'API License'
return true
end
end
# For Local System
def detail_with_local_file()
def detail_with_local_file()
renewal_date_str = read_license("renewable_date")
if check_expiring(renewal_date_str)
# return for all ok
if check_expiring(renewal_date_str)
# return for all ok
return 1
else
has_license = verify_license()
if has_license
# return for expiring
# return for expiring
return 2
else
return 0
end
end
# end
end
# end
end
# License Activation
def license_activate (shop, license_key, db_host, db_schema, db_user, db_password)
aes = MyAesCrypt.new
aes_key, aes_iv = aes.export_key(license_key)
aes = MyAesCrypt.new
aes_key, aes_iv = aes.export_key(license_key)
@params = { query: { lookup_type: self.server_mode, iv_key: aes_iv, license_key: license_key } }
response = self.class.get("/activate", @params)
@@ -96,21 +97,21 @@ class License
if (@activate["status"])
##Check from local redis - if available load local otherwise get from remote
cache_key = "shop:#{@activate["shop_name"]}"
cache_key = "shop:#{@activate["shop_name"]}"
cache_license = nil
cache_license = nil
##Get redis connection from connection pool
redis = Redis.new
cache_license = redis.get(cache_key)
cache_license = redis.get(cache_key)
Rails.logger.info "Cache key - " + cache_key.to_s
if cache_license.nil?
cache = {"shop" => @activate["shop_name"], "key" => aes_key, "iv" => @activate["iv_key"], "renewable_date" => @activate["renewable_date"] }
if cache_license.nil?
cache = {"shop" => @activate["shop_name"], "key" => aes_key, "iv" => @activate["iv_key"], "renewable_date" => @activate["renewable_date"] }
redis = Redis.new
redis.set(cache_key, Marshal.dump(cache))
end
end
Rails.logger.info "License - " + response.parsed_response.to_s
@@ -120,21 +121,21 @@ class License
sym_path = File.expand_path("~/symmetric/")
response = create_symmetric_config(sym_path, db_host, db_schema, db_user, db_password)
if(response[:status])
response = run_symmetric(sym_path)
end
end
else
response = { "status": false, "message": "Activation Failed! Please contact code2lab call center!"}
end
end
return response
end
def verify_license
api_token = read_license_no_decrypt("api_token")
def verify_license
api_token = read_license_no_decrypt("api_token")
@params = { query: {lookup_type: "application", api_token: api_token} }
begin
response = self.class.get("/verify", @params)
@varified = response.parsed_response
@@ -145,7 +146,7 @@ class License
end
else
delete_license_file
end
end
rescue SocketError => e
Rails.logger.debug "In SocketError No Internet connection ! "
@@ -159,21 +160,21 @@ class License
rescue OpenURI::HTTPError
Rails.logger.debug "Can't connect server"
return true
end
return false
end
return false
end
# Check Expired before 30 days
def check_expiring(renewal_date_str)
def check_expiring(renewal_date_str)
if !renewal_date_str.empty?
renewal_date = DateTime.parse(renewal_date_str)
renewal_date = DateTime.parse(renewal_date_str)
renewal_date > Date.today.advance(:days => 30)
end
end
# Check License expired date from PROVISION SERVER
def check_expired(renewal_date_str)
def check_expired(renewal_date_str)
expired_date_str = read_license("renewable_date")
renewal_date = DateTime.parse(renewal_date_str)
if(renewal_date_str != expired_date_str)
@@ -186,32 +187,32 @@ class License
return false
end
end
# Check License File exists
def self.check_license_file
return File.exist?("config/license.yml")
return File.exist?("config/license.yml")
end
# read line by key for license file
def read_license(key_name)
decrypted_line = ""
def read_license(key_name)
decrypted_line = ""
key, iv = get_redis_key()
if File.exist?("config/license.yml")
if File.exist?("config/license.yml")
File.open("config/license.yml").each do |line|
if line.include? (key_name)
decrypted_line_array = line.split(": ")
if line.include? (key_name)
decrypted_line_array = line.split(": ")
decrypted_line = AESCrypt.decrypt_data(decode_str(decrypted_line_array[1]), decode_str(key), decode_str(iv), ENV['CIPHER_TYPE'])
end
end
end
end
return decrypted_line
end
# read line by key for license file without decrypt
def read_license_no_decrypt(key)
decrypted_line = ""
if File.exist?("config/license.yml")
if File.exist?("config/license.yml")
File.open("config/license.yml").each do |line|
if line.include? (key)
decrypted_line_array = line.split(": ")
@@ -226,18 +227,18 @@ class License
def update_license(content, new_content)
key, iv = get_redis_key()
if !new_content.include? "=="
if !new_content.include? "=="
crypted_str = AESCrypt.encrypt_data(new_content, decode_str(key), decode_str(iv), ENV['CIPHER_TYPE'])
end
content_str = read_license_no_decrypt(content)
if File.exist?("config/license.yml")
if File.exist?("config/license.yml")
file_str = File.read("config/license.yml")
new_file_str = file_str.gsub(content_str, encode_str(crypted_str))
# To write changes to the file, use:
File.open("config/license.yml", "w") {|file| file.puts new_file_str }
# File.open("config/license.yml").each do |line|
# new_file_str = line.gsub(content, crypted_str)
# f.put
@@ -247,33 +248,33 @@ class License
# Re-get keys
def get_key
api_token = read_license_no_decrypt("api_token")
shop_name = read_license_no_decrypt("shop_name")
api_token = read_license_no_decrypt("api_token")
shop_name = read_license_no_decrypt("shop_name")
@params = { query: {lookup_type: "application", api_token: api_token } }
response = self.class.get("/get_key", @params)
@data = response.parsed_response
if (@data["status"])
##Check from local redis - if available load local otherwise get from remote
cache_key = "shop:#{shop_name.chomp}"
cache_key = "shop:#{shop_name.chomp}"
cache_license = nil
cache_license = nil
##Get redis connection from connection pool
redis = Redis.new
cache_license = redis.get(cache_key)
cache_license = redis.get(cache_key)
Rails.logger.info "Cache key - " + cache_key.to_s
if cache_license.nil?
cache = {"shop" => shop_name, "key" => @data["secret_key"], "iv" => @data["iv_key"], "renewable_date" => @data["renewable_date"] }
if cache_license.nil?
cache = {"shop" => shop_name, "key" => @data["secret_key"], "iv" => @data["iv_key"], "renewable_date" => @data["renewable_date"] }
redis = Redis.new
redis.set(cache_key, Marshal.dump(cache))
end
end
return true
end
end
return false
end
end
private
def get_redis_key
@@ -281,18 +282,18 @@ class License
key = ""
shop = read_license_no_decrypt("shop_name")
##Check from local redis - if available load local otherwise get from remote
cache_key = "shop:#{shop.chomp}"
cache_key = "shop:#{shop.chomp}"
cache_shop = nil
cache_shop = nil
##Get redis connection from connection pool
redis = Redis.new
cache_shop = redis.get(cache_key)
cache_shop = redis.get(cache_key)
if !cache_shop.nil?
@shop = Marshal.load(cache_shop)
key = @shop["key"]
iv = @shop["iv"]
if !cache_shop.nil?
@shop = Marshal.load(cache_shop)
key = @shop["key"]
iv = @shop["iv"]
end
return key, iv
end
@@ -307,13 +308,13 @@ class License
# License File Creation
def create_license_file(response_data)
if File.exist?("config/license.yml")
if File.exist?("config/license.yml")
delete_license_file
end
begin
# Licese File Creation
File.open("config/license.yml", "w") do |f|
File.open("config/license.yml", "w") do |f|
f.puts("iv_key: #{response_data['iv_key']}")
f.puts("shop_name: #{response_data['shop_name']}")
f.puts("email: #{response_data['email']}")
@@ -325,11 +326,11 @@ class License
f.puts("dbusername: #{response_data['dbusername']}")
f.puts("dbpassword: #{response_data['dbpassword']}")
f.puts("api_token: #{response_data['api_token']}")
f.puts("app_token: #{response_data['app_token']}")
f.puts("app_token: #{response_data['app_token']}")
f.puts("plan_sku: #{response_data['plan_sku']}")
f.puts("renewable_date: #{response_data['renewable_date']}")
f.puts("plan_name: #{response_data['plan_name']}")
end
end
rescue IOError
response = { "status": false, "message": "Activation is success but something is wrong. \n Please contact code2lab call center!"}
end
@@ -352,15 +353,15 @@ class License
f.write("group.id=sx\n")
f.write("external.id=000\n")
f.write("job.purge.period.time.ms=7200000\n")
f.write("job.routing.period.time.ms=5000\n")
f.write("job.push.period.time.ms=10000\n")
f.write("job.pull.period.time.ms=10000\n")
f.write("initial.load.create.first=true\n")
f.write("job.routing.period.time.ms=5000\n")
f.write("job.push.period.time.ms=10000\n")
f.write("job.pull.period.time.ms=10000\n")
f.write("initial.load.create.first=true\n")
f.write("initial.load.use.extract.job.enabled=true\n")
f.write("rest.api.enable=true\n")
f.close
f.close
# read from license file
# read from license file
# shop_name = read_license_no_decrypt("shop_name")
shop_name = "cloud"
dbhost = read_license("dbhost")
@@ -378,12 +379,12 @@ class License
f.write("registration.url=http://#{db_host}:31415/sync/sx\n")
f.write("group.id=cloud\n")
f.write("external.id=001\n")
f.write("job.routing.period.time.ms=5000\n")
f.write("job.push.period.time.ms=10000\n")
f.write("job.routing.period.time.ms=5000\n")
f.write("job.push.period.time.ms=10000\n")
f.write("job.pull.period.time.ms=10000\n")
f.write("rest.api.enable=true\n")
# f.write("initial.load.create.first=true\n")
# f.write("initial.load.use.extract.job.enabled=true\n")
# f.write("initial.load.create.first=true\n")
# f.write("initial.load.use.extract.job.enabled=true\n")
f.close
rescue IOError
response = { "status": false, "message": "Activation is success but something is wrong. \n Please contact code2lab call center!"}
@@ -392,12 +393,12 @@ class License
end
end
# Run Symmetric
# Run Symmetric
def run_symmetric(sym_path)
# check_sym_proc_str = `#{sym_path + "bin/sym_service status"}`
# check_sym_proc_str = check_sym_proc_str.split("\n")
# sym_install_status = check_sym_proc_str[0].split(": ")
check_sym_proc_str = `#{"sudo service SymmetricDS status"}`
# Check Sym Installed
@@ -412,7 +413,7 @@ class License
check_sym_table = system("sudo " + sym_path + "/bin/symadmin --engine sx create-sym-tables")
if check_sym_table
sym_sql = Rails.root + "db/sym_master.sql"
if File.exist? (sym_sql)
# Import Sym Sql to db and start sym
run_sym_sql = system("sudo " + sym_path + "/bin/dbimport --engine sx " + sym_sql.to_s)
@@ -427,7 +428,7 @@ class License
else
response = { "status": false, "message": "Activation is success but Cannot create Sym Tables. \n Please contact code2lab call center!"}
end
else
else
response = { "status": false, "message": "Activation is success but Symmetric not running. \n Please contact code2lab call center!"}
end
end
@@ -435,7 +436,7 @@ class License
# Check Symmetric Running
def check_sym_running(status, sym_path)
# Run Sym Service
# if status.include? "Server is already running"
# if status.include? "Server is already running"
# return true
# elsif status.include? "false"
# sym_start_str = `#{sym_path + "bin/sym_service start"}`
@@ -443,9 +444,9 @@ class License
# return true
# else
# check_sym_running(sym_start_status[0])
# end
# end
# else
# return true
# return true
# end
if status.include? "Active: active (running)" || "Active: active (exited)" #"Server is already running"
@@ -456,15 +457,15 @@ class License
# Delete License File
def delete_license_file
File.delete("config/license.yml") if File.exist?("config/license.yml")
File.delete("config/license.yml") if File.exist?("config/license.yml")
end
# Assign db info for Cloud
def assign(aes_key, aes_iv)
def assign(aes_key, aes_iv)
key = Base64.decode64(aes_key)
iv = Base64.decode64(aes_iv)
if (@license["dbhost"] || @license["dbschema"] || @license["dbusername"] || @license["dbpassword"] )
if (@license["dbhost"] || @license["dbschema"] || @license["dbusername"] || @license["dbpassword"] )
host = Base64.decode64(@license["dbhost"])
dbschema = Base64.decode64(@license["dbschema"])
dbusername = Base64.decode64(@license["dbusername"])
@@ -473,8 +474,8 @@ class License
self.dbhost = AESCrypt.decrypt_data(host, key, iv, ENV['CIPHER_TYPE'])
self.dbschema = AESCrypt.decrypt_data(dbschema, key, iv, ENV['CIPHER_TYPE'])
self.dbusername = AESCrypt.decrypt_data(dbusername, key, iv, ENV['CIPHER_TYPE'])
self.dbpassword = AESCrypt.decrypt_data(dbpassword, key, iv, ENV['CIPHER_TYPE'])
self.dbpassword = AESCrypt.decrypt_data(dbpassword, key, iv, ENV['CIPHER_TYPE'])
end
end
end

View File

@@ -3,6 +3,8 @@ class Lookup < ApplicationRecord
has_many :accounts
belongs_to :shop
scope :number_formats, -> { where(lookup_type: 'number_format')}
def available_types
{'Employee Roles' => 'employee_roles',
'Dining Facilities Status' => 'dining_facilities_status',

View File

@@ -141,7 +141,14 @@ class Menu < ApplicationRecord
end
else
# Menu by Menu Import
shop_code= shop.shop_code + "_"
@shop = Shop.current_shop
shop_code = ""
if !@shop.nil?
if @shop.shop_code
shop_code = @shop.shop_code + "_"
end
end
sheet = spreadsheet.sheet(0)
menu = sheet.row(1)[1]

View File

@@ -125,42 +125,14 @@ class OrderItem < ApplicationRecord
end
def update_stock_journal
if self.set_menu_items.present?
puts "set menu itemsssssssss???????????????????????????????"
puts items = JSON.parse(self.set_menu_items)
instance_code = Array.new
count = 0
items.each { |i|
instance_code.push(i["item_instance_code"])
}
print instance_code
end
if self.qty != self.qty_before_last_save
found, inventory_definition = InventoryDefinition.find_product_in_inventory(self,self.order.shop_code)
if found
InventoryDefinition.check_balance(self, inventory_definition)
unless MenuItemInstance.where("item_instance_name <> ''").pluck(:item_instance_code).include?(self.item_instance_code)
if self.qty != self.qty_before_last_save
found, inventory_definition = InventoryDefinition.find_product_in_inventory(self)
if found
InventoryDefinition.check_balance(self, inventory_definition)
end
end
end
# if self.qty > self.qty_was
# credit = 0
# debit = self.qty.to_i - self.qty_was.to_i
# else
# credit = self.qty_was.to_i - self.qty.to_i
# debit = 0
# end
# if credit != debit
# defination = InventoryDefinition.find_by_item_code(self.item_instance_code)
# stock = StockJournal.where('item_code = ?', self.item_instance_code).order("id DESC").first
# journal = StockJournal.create(
# item_code: self.item_instance_code,
# credit: credit,
# debit: debit,
# balance: stock.balance - debit + credit,
# inventory_definition_id: defination.id,
# remark: 'ok',
# trans_ref: self.order.id,
# trans_type: StockJournal::SALES_TRANS
# )
# end
end
end

View File

@@ -297,8 +297,9 @@ class OrderQueueStation < ApplicationRecord
@type = (DiningFacility.find(change_to)).type
@moved_by = current_user
@date = DateTime.now
@shop = Shop.find_by_shop_code(oqs.shop_code)
unique_code = "MoveTablePdf"
@shop = Shop.current_shop
unique_code = "MoveTablePdf"
# pdf_no = PrintSetting.where(:unique_code => unique_code).count
print_settings = PrintSetting.find_by_unique_code(unique_code)
# printer_array = []

View File

@@ -157,7 +157,8 @@ class OrderReservation < ApplicationRecord
def self.update_doemal_payment(order,current_user,receipt_bill)
if(Sale.exists?(order.sale_id))
saleObj = Sale.find(order.sale_id)
shop_details = Shop.find_by_shop_code(order.shop_code)
shop_details = Shop.current_shop
# rounding adjustment
if shop_details.is_rounding_adj
a = saleObj.grand_total % 25 # Modulus
@@ -194,7 +195,8 @@ class OrderReservation < ApplicationRecord
shift = ShiftSale.find(saleObj.shift_sale_id)
cashier_terminal = CashierTerminal.find(shift.cashier_terminal_id)
# shop_detail = Shop.first
shop_detail = Shop.current_shop
order_reservation = OrderReservation.get_order_reservation_info(saleObj.sale_id)
if !cashier_terminal.nil?
# Calculate Food and Beverage Total
@@ -400,7 +402,7 @@ class OrderReservation < ApplicationRecord
end
def self.check_new_order
shop = Shop.find_by_id(1)
shop = Shop.current_shop
if !shop.shop_code.nil?
shop_code = shop.shop_code
else
@@ -418,7 +420,7 @@ class OrderReservation < ApplicationRecord
end
def self.check_order_send_to_kitchen
shop = Shop.find_by_id(1)
shop = Shop.current_shop
if !shop.shop_code.nil?
shop_code = shop.shop_code
else
@@ -436,7 +438,7 @@ class OrderReservation < ApplicationRecord
end
def self.check_order_ready_to_delivery
shop = Shop.find_by_id(1)
shop = Shop.current_shop
if !shop.shop_code.nil?
shop_code = shop.shop_code
else

View File

@@ -38,8 +38,9 @@ class Printer::OrderQueuePrinter < Printer::PrinterWorker
end
# end
# shop = Shop.first
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)
filename = directory_name + "/order_item_#{order_id}_#{order_item_id}" + ".pdf"
@@ -80,8 +81,9 @@ class Printer::OrderQueuePrinter < Printer::PrinterWorker
print_setting = PrintSetting.all.order("id ASC")
order=print_query('order_summary', order_id)
# shop = Shop.first
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
@@ -192,8 +194,9 @@ class Printer::OrderQueuePrinter < Printer::PrinterWorker
order=print_query('booking_summary', booking_id)
# shop = Shop.first
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

View File

@@ -1,4 +1,3 @@
class Room < DiningFacility
has_many :bookings, :foreign_key => 'dining_facility_id'
end

View File

@@ -1,4 +1,5 @@
class Sale < ApplicationRecord
include NumberFormattable
self.primary_key = "sale_id"
#primary key - need to be unique generated for multiple shops
@@ -7,12 +8,15 @@ class Sale < ApplicationRecord
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_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 :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
@@ -25,10 +29,11 @@ class Sale < ApplicationRecord
scope :complete_sale, -> { where("sale_status = 'completed' and receipt_date BETWEEN '#{DateTime.now.utc.beginning_of_day}' AND '#{DateTime.now.utc.end_of_day}'") }
scope :paid, -> { where(payment_status: 'paid')}
scope :completed, -> { where(sale_status: 'completed') }
scope :date_on, -> (date) { where("DATE(CONVERT_TZ(receipt_date, '+00:00', ?)) = ?", Time.zone.formatted_offset, date) }
scope :date_between, -> (from, to) { where("DATE(CONVERT_TZ(receipt_date, '+00:00', ?)) BETWEEN ? AND ?", Time.zone.formatted_offset, from, to) }
scope :time_between, -> (from, to) { where("TIME(CONVERT_TZ(receipt_date, '+00:00', ?)) BETWEEN ? AND ?", Time.zone.formatted_offset, from, to) }
scope :along_with_sale_payments_except_void, -> { joins("LEFT JOIN sale_payments on sales.sale_status != 'void' AND sale_payments.sale_id = sales.sale_id AND DATE(CONVERT_TZ(sale_payments.created_at,'+00:00','+06:30')) = DATE(CONVERT_TZ(sales.receipt_date,'+00:00','+06:30'))") }
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])) }
def qty_of(item_instance_code)
order_items.select(:order_items_id, :item_instance_code, 'SUM(qty) as qty').where(item_instance_code: item_instance_code).group(:item_instance_code).first
end
@@ -435,7 +440,8 @@ class Sale < ApplicationRecord
#compute - invoice total
def compute_by_sale_items(total_discount, discount_type=nil, order_source=nil, tax_type=nil, type=nil)
# shop = Shop.first
shop = Shop.current_shop
#Computation Fields
subtotal_price = 0
@@ -502,7 +508,8 @@ class Sale < ApplicationRecord
# Tax Re-Calculte
def compute_tax(total_taxable, total_discount = 0, order_source = nil, tax_type=nil)
shop = Shop.find_by_shop_code(self.shop_code)
shop = Shop.current_shop
#if tax is not apply create new record
# SaleTax.where("sale_id='#{sale.sale_id}'").find_each do |existing_tax|
@@ -524,7 +531,7 @@ class Sale < ApplicationRecord
tax_profiles = unique_tax_profiles(order_source, self.customer_id)
# #Creat new tax records
if self.payment_status != 'foc'
if self.payment_status != 'foc' && tax_type.to_s == "all"
tax_profiles.each do |tax|
sale_tax = SaleTax.new(:sale => self)
sale_tax.tax_name = tax.name
@@ -539,16 +546,82 @@ class Sale < ApplicationRecord
divided_value = (100 + rate)/rate
sale_tax.tax_payable_amount = total_tax / divided_value
else
sale_tax.tax_payable_amount = total_tax * tax.rate / 100
sale_tax.tax_payable_amount = total_tax * tax.rate / 100
end
sale_tax.inclusive = tax.inclusive
sale_tax.save
if !tax.inclusive
total_tax_amount = total_tax_amount + sale_tax.tax_payable_amount
end
#new taxable amount is standard rule for step by step
if shop.calc_tax_order
total_taxable = total_taxable + sale_tax.tax_payable_amount
end
end
elsif tax_type.to_s == "no_tax"
tax_profiles.each do |tax|
sale_tax = SaleTax.new(:sale => self)
sale_tax.tax_name = tax.name
sale_tax.tax_rate = 0
sale_tax.tax_payable_amount = 0
sale_tax.inclusive = tax.inclusive
sale_tax.save
end
elsif tax_type.to_s == "Commercial Tax"
tax_profiles.each do |tax|
if tax.name == tax_type.to_s
sale_tax = SaleTax.new(:sale => self)
sale_tax.tax_name = tax.name
sale_tax.tax_rate = tax.rate
# substract , to give after discount
total_tax = total_taxable - total_discount
#include or execulive
if tax.inclusive
tax_incl_exec = "inclusive"
rate = tax.rate
divided_value = (100 + rate)/rate
sale_tax.tax_payable_amount = total_tax / divided_value
else
sale_tax.tax_payable_amount = total_tax * tax.rate / 100
total_tax_amount = total_tax_amount + sale_tax.tax_payable_amount
end
#new taxable amount is standard rule for step by step
if shop.calc_tax_order
total_taxable = total_taxable + sale_tax.tax_payable_amount
end
sale_tax.inclusive = tax.inclusive
sale_tax.save
end
end
elsif tax_type.to_s == "Service Charges"
tax_profiles.each do |tax|
if tax.name == tax_type.to_s
sale_tax = SaleTax.new(:sale => self)
sale_tax.tax_name = tax.name
sale_tax.tax_rate = tax.rate
# substract , to give after discount
total_tax = total_taxable - total_discount
#include or execulive
if tax.inclusive
tax_incl_exec = "inclusive"
rate = tax.rate
divided_value = (100 + rate)/rate
sale_tax.tax_payable_amount = total_tax / divided_value
else
sale_tax.tax_payable_amount = total_tax * tax.rate / 100
total_tax_amount = total_tax_amount + sale_tax.tax_payable_amount
end
#new taxable amount is standard rule for step by step
if shop.calc_tax_order
total_taxable = total_taxable + sale_tax.tax_payable_amount
end
sale_tax.inclusive = tax.inclusive
sale_tax.save
end
end
end
self.tax_type = tax_incl_exec
self.total_tax = total_tax_amount
@@ -556,7 +629,8 @@ class Sale < ApplicationRecord
# Tax Calculate
def apply_tax(total_taxable, order_source = nil, tax_type = nil)
shop = Shop.find_by_shop_code(self.shop_code)
shop = Shop.current_shop
#if tax is not apply create new record
# SaleTax.where("sale_id='#{self.sale_id}'").find_each do |existing_tax|
@@ -574,7 +648,7 @@ class Sale < ApplicationRecord
order_source = "cashier"
end
# tax_data = TaxProfile.unscoped.where("group_type=?",order_source).pluck(:id)
# tax_data = TaxProfile.unscope(:order).where("group_type=?",order_source).pluck(:id)
# customer = Customer.find(self.customer_id).tax_profiles
tax_profiles = unique_tax_profiles(order_source, self.customer_id)
@@ -595,6 +669,12 @@ class Sale < ApplicationRecord
sale_tax.tax_payable_amount = total_tax / divided_value
else
sale_tax.tax_payable_amount = total_tax * tax.rate / 100
end
sale_tax.inclusive = tax.inclusive
sale_tax.save
if !tax.inclusive
total_tax_amount = total_tax_amount + sale_tax.tax_payable_amount
end
@@ -602,9 +682,6 @@ class Sale < ApplicationRecord
if shop.calc_tax_order
total_taxable = total_taxable + sale_tax.tax_payable_amount
end
sale_tax.inclusive = tax.inclusive
sale_tax.save
end
self.tax_type = tax_incl_exec
self.total_tax = total_tax_amount
@@ -636,7 +713,8 @@ class Sale < ApplicationRecord
end
def adjust_rounding
shop_details = Shop.find_by_shop_code(self.shop_code)
shop_details = Shop.current_shop
# rounding adjustment
if shop_details.is_rounding_adj
new_total = Sale.get_rounding_adjustment(self.grand_total)
@@ -652,7 +730,8 @@ class Sale < ApplicationRecord
#Generate new Receipt No when it is not assigned
def generate_receipt_no
#shop_code and client_code
shop_details = Shop.find_by_shop_code(self.shop_code)
shop_details = Shop.current_shop
#Date-Shift-
if self.receipt_no.nil?
prefix = DateTime.now().utc
@@ -773,8 +852,8 @@ def self.daily_sales_list(from,to,shop_code)
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")
.along_with_sale_payments_except_void
.where("shop_code='#{shop_code}' and (sale_status = ? OR sale_status = ?) AND sales.receipt_date between ? AND ? ", 'completed', 'void', from, to)
.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)
.group("sale_id").to_sql
daily_total = connection.select_all("SELECT
@@ -1165,7 +1244,7 @@ end
#product sale report query
def self.get_menu_item_query(order_by)
query = MenuItem.unscoped.select("acc.id as account_id,
query = MenuItem.unscope(:order).select("acc.id as account_id,
acc.title as account_name,
mii.item_instance_code as item_code, " +
"(CASE WHEN si.qty IS NOT NULL THEN SUM(si.qty) ELSE 0 END) as total_item," +
@@ -1194,7 +1273,7 @@ def self.get_shift_sales_by_receipt_no(shift_sale_range,shift,from,to,payment_ty
payment_type = " and sale_payments.payment_method = '#{payment_type}'"
end
query = Sale.all.select("sales.*,sale_payments.*,df.name,df.type")
query = Sale.includes(:sale_items).select("sales.*,sale_payments.*,df.name,df.type")
.where("sale_status= 'completed' and sale_payments.payment_amount != 0 #{payment_type}")
.joins("join sale_payments on sale_payments.sale_id = sales.sale_id")
.joins("join bookings on bookings.sale_id = sales.sale_id")
@@ -1212,17 +1291,16 @@ end
def self.get_shift_sales_by_receipt_no_detail(shift_sale_range,shift,from,to,payment_type)
## => left join -> show all sales although no orders
if payment_type.blank?
payment_type = ''
else
payment_type = " and sale_payments.payment_method = '#{payment_type}'"
end
query = Sale.select("sales.*,bookings.dining_facility_id as table_id")
.where("sale_status= 'completed' and sale_payments.payment_amount != 0 #{payment_type}")
.joins("join sale_payments on sale_payments.sale_id = sales.sale_id")
.joins("join bookings on bookings.sale_id = sales.sale_id")
.group("sales.sale_id")
query = Sale.includes([:customer, :survey, :sale_payments])
.includes(:bookings => :dining_facility)
.select("sales.*, SUM(sale_payments.payment_amount) AS payments_for_credits_amount")
.joins(:bookings)
.left_joins(:sale_payments_for_credits)
.completed
.where.not(total_amount: 0)
.group(:sale_id)
.order(:receipt_date)
if shift.present?
query = query.where("sales.shift_sale_id in (?)", shift.to_a)
elsif shift_sale_range.present?
@@ -1230,6 +1308,9 @@ def self.get_shift_sales_by_receipt_no_detail(shift_sale_range,shift,from,to,pay
else
query = query.where("sales.receipt_date between ? and ?",from,to)
end
ActiveRecord::Associations::Preloader.new.preload(query, :sale_items, SaleItem.where.not(price: 0))
return query
end
@@ -1502,173 +1583,130 @@ end
return tax
end
def self.top_bottom_products(today,current_user,from,to,from_time,to_time,type,shop)
if (!from.nil? && !to.nil?) && (from != "" && to!="")
if current_user.nil?
query = Sale.top_bottom(shop,today,nil,from,to,from_time,to_time)
if type == "top"
query = query.group('i.product_name')
.order("SUM(i.qty) DESC").limit(20)
elsif type == "bottom"
query = query.group('i.product_name')
.order("SUM(i.qty) ASC").limit(20)
end
else
if current_user.role == 'administrator' || current_user.role == 'manager' || current_user.role == 'account' || current_user.role == 'supervisor'
query = Sale.top_bottom(shop,today,nil,from,to,from_time,to_time)
if type == "top"
query = query.group('i.product_name')
.order("SUM(i.qty) DESC").limit(20)
elsif type == "bottom"
query = query.group('i.product_name')
.order("SUM(i.qty) ASC").limit(20)
end
else
shift = ShiftSale.current_open_shift(current_user)
if !shift.nil?
query = Sale.top_bottom(shop,today,shift,from,to,from_time,to_time)
if type == "top"
query = query.group('i.product_name')
.order("SUM(i.qty) DESC").limit(20)
elsif type == "bottom"
query = query.group('i.product_name')
.order("SUM(i.qty) ASC").limit(20)
end
end
end
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}'")
.group("SUBSTRING_INDEX(product_name, ' - ', 1)")
if !from.nil? && !to.nil?
query = query.receipt_date_between(from, to)
else
if current_user.nil?
query = Sale.top_bottom(shop,today).group('i.product_name')
query = query.receipt_date_between(Time.now.beginning_of_day, Time.now.end_of_day)
end
if current_user.present? && !(current_user.role == 'administrator' || current_user.role == 'manager' || current_user.role == 'account' || current_user.role == 'supervisor')
if shift = ShiftSale.current_open_shift(current_user.id)
query = query.where("shift_sale_id='#{shift.id}'")
if type == "top"
query = query.order("SUM(i.qty) DESC").limit(20)
elsif type == "bottom"
query = query.order("SUM(i.qty) ASC").limit(20)
end
else
if current_user.role == 'administrator' || current_user.role == 'manager' || current_user.role == 'account' || current_user.role == 'supervisor'
query = Sale.top_bottom(shop,today).group('i.product_name')
if type == "top"
query = query.order("SUM(i.qty) DESC").limit(20)
elsif type == "bottom"
query = query.order("SUM(i.qty) ASC").limit(20)
end
else
shift = ShiftSale.current_open_shift(current_user)
if !shift.nil?
query = Sale.top_bottom(shop,today,shift).group('i.product_name')
if type == "top"
query = query.order("SUM(i.qty) DESC").limit(20)
elsif type == "bottom"
query = query.order("SUM(i.qty) ASC").limit(20)
end
end
end
end
end
if type == "top"
query = query.order("SUM(qty) DESC")
else
query = query.order("SUM(qty) ASC")
end
query.limit(20).sum('qty')
end
def self.hourly_sales(today,current_user,from,to,from_time,to_time,shop)
if (!from.nil? && !to.nil?) && (from != "" && to!="")
if current_user.nil?
query = Sale.hourly_sale_data(shop,today,nil,from,to,from_time,to_time)
else
if current_user.role == 'administrator' || current_user.role == 'manager' || current_user.role == 'account' || current_user.role == 'supervisor'
query = Sale.hourly_sale_data(shop,today,nil,from,to,from_time,to_time)
else
shift = ShiftSale.current_open_shift(current_user)
if !shift.nil?
query = Sale.hourly_sale_data(shop,today,shift,from,to,from_time,to_time)
end
end
end
def self.hourly_sales(current_user,from,to, current_shop)
query = Sale.group("date_format(CONVERT_TZ(receipt_date,'+00:00', '#{Time.zone.formatted_offset}'), '%I %p')")
.order('receipt_date').completed
if !from.nil? && !to.nil?
query = query.receipt_date_between(from, to)
else
if current_user.nil?
query = Sale.hourly_sale_data(shop,today)
else
if current_user.role == 'administrator' || current_user.role == 'manager' || current_user.role == 'account' || current_user.role == 'supervisor'
query = Sale.hourly_sale_data(shop,today)
else
shift = ShiftSale.current_open_shift(current_user)
if !shift.nil?
query = Sale.hourly_sale_data(shop,today,shift)
end
end
query = query.receipt_date_between(Time.now.beginning_of_day, Time.now.end_of_day)
end
if current_user.present? && !(current_user.role == 'administrator' || current_user.role == 'manager' || current_user.role == 'account' || current_user.role == 'supervisor')
if shift = ShiftSale.current_open_shift(current_user.id)
query = query.where("shift_sale_id='#{shift.id}'")
end
end
query.sum(:grand_total)
end
def self.employee_sales(today,current_user,from,to,from_time,to_time,shop)
def self.employee_sales(current_user,from,to, current_shop)
shift = if current_user.present? && !(current_user.role == 'administrator' || current_user.role == 'manager' || current_user.role == 'account' || current_user.role == 'supervisor')
ShiftSale.current_open_shift(current_user)
end
payments_for_credits = SalePayment.joins(:sale_audit).to_sql
query = employee_sale(shop,today, shift, from, to, from_time, to_time)
query = employee_sale(shift, from, to, current_shop)
.joins("LEFT JOIN (#{payments_for_credits}) payments_for_credits ON payments_for_credits.sale_id = sales.sale_id")
.select("SUM(sale_payments.payment_amount) - CASE WHEN sale_payments.payment_method = 'creditnote' THEN IFNULL(SUM(payments_for_credits.payment_amount), 0) ELSE ABS(SUM(CASE WHEN sale_payments.outstanding_amount < 0 THEN sale_payments.outstanding_amount ELSE 0 END)) END AS payment_amount,
CASE WHEN sale_payments.payment_method IN ('mpu', 'visa', 'master', 'jcb', 'unionpay', 'alipay', 'paymal', 'dinga', 'JunctionPay', 'giftvoucher') THEN 'card'
ELSE sale_payments.payment_method END AS payment_method, employees.name AS e_name")
end
def self.total_trans(today,current_user=nil,from=nil,to=nil,from_time=nil,to_time=nil,shop)
query = Sale.select("SUM(grand_total) as total_sale, COUNT(sales.sale_id) as total_count")
.where("sale_status = 'completed' AND shop_code='#{shop.shop_code}'")
if (!from.nil? && !to.nil?) && (from != "" && to!="")
query = query.date_between(from, to)
if !from_time.nil? && !to_time.nil?
query = query.time_between(from_time, to_time)
end
def self.total_trans(current_user=nil,from=nil,to=nil)
query = Sale.select("SUM(grand_total) as total_sale, COUNT(sales.sale_id) as total_count")
.where('sale_status = "completed"')
if (!from.nil? && !to.nil?)
query = query.receipt_date_between(from, to)
else
query = query.date_on(today)
query = query.receipt_date_between(Time.now.beginning_of_day, Time.now.end_of_day)
end
if current_user.present? && !(current_user.role == 'administrator' || current_user.role == 'manager' || current_user.role == 'account' || current_user.role == 'supervisor')
if shift = ShiftSale.current_open_shift(current_user)
query = query.where("sales.shift_sale_id = ?", shift.id)
end
end
return query
end
def self.total_card_sale(today,current_user=nil,from=nil,to=nil,from_time=nil,to_time=nil,shop)
def self.total_card_sale(current_user=nil,from=nil,to=nil)
query = Sale.joins("JOIN sale_payments sp ON sp.sale_id = sales.sale_id")
.where("sales.shop_code='#{shop.shop_code}' and sales.sale_status = 'completed' and (sp.payment_method = 'mpu' or sp.payment_method = 'visa' or sp.payment_method = 'master' or sp.payment_method = 'jcb' or sp.payment_method = 'unionpay' or sp.payment_method = 'alipay' or sp.payment_method = 'paymal' or sp.payment_method = 'dinga' or sp.payment_method = 'JunctionPay')")
if (!from.nil? && !to.nil?) && (from != "" && to!="")
query = query.date_between(from, to)
if !from_time.nil? && !to_time.nil?
query = query.time_between(from_time, to_time)
end
.where('sales.sale_status = "completed" and (sp.payment_method = "mpu" or sp.payment_method = "visa" or sp.payment_method = "master" or sp.payment_method = "jcb" or sp.payment_method = "unionpay" or sp.payment_method = "alipay" or sp.payment_method = "paymal" or sp.payment_method = "dinga" or sp.payment_method = "JunctionPay")')
if (!from.nil? && !to.nil?)
query = query.receipt_date_between(from, to)
else
query = query.date_on(today)
query = query.receipt_date_between(Time.now.beginning_of_day, Time.now.end_of_day)
end
if current_user.present? && !(current_user.role == 'administrator' || current_user.role == 'manager' || current_user.role == 'account' || current_user.role == 'supervisor')
if shift = ShiftSale.current_open_shift(current_user)
query = query.where("sales.shift_sale_id = ?", shift.id)
end
end
query = query.sum("sp.payment_amount")
end
def self.credit_payment(today,current_user=nil,from=nil,to=nil,from_time=nil,to_time=nil,shop)
def self.credit_payment(current_user=nil,from=nil,to=nil, current_shop)
payments_for_credits = SalePayment.joins(:sale_audit).to_sql
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',shop.shop_code)
.where("sale_payments.payment_method= ? AND sales.sale_status = ? AND sales.shop_code=?", 'creditnote', 'completed',current_shop.shop_code)
if (!from.nil? && !to.nil?) && (from != "" && to!="")
query = query.merge(Sale.date_between(from, to))
if !from_time.nil? && !to_time.nil?
query = query.merge(Sale.time_between(from_time, to_time))
end
if (!from.nil? && !to.nil?)
query = query.merge(Sale.receipt_date_between(from, to))
else
query = query.merge(Sale.date_on(today))
query = query.merge(Sale.receipt_date_between(Time.now.beginning_of_day, Time.now.end_of_day))
end
if current_user.present? && !(current_user.role == 'administrator' || current_user.role == 'manager' || current_user.role == 'account' || current_user.role == 'supervisor')
if shift = ShiftSale.current_open_shift(current_user)
query = query.where("sales.shift_sale_id = ?", shift.id)
@@ -1678,52 +1716,57 @@ end
return query.sum("sale_payments.payment_amount - IFNULL(payments_for_credits.payment_amount, 0)")
end
def self.summary_sale_receipt(shop,today,current_user=nil,from=nil,to=nil,from_time=nil,to_time=nil)
def self.summary_sale_receipt(current_user=nil,from=nil,to=nil)
query = Sale.select('count(sale_id) as total_receipt, (case when sum(total_amount) > 0 then sum(total_amount) else 0.0 end) as total_amount, (case when sum(grand_total) > 0 then sum(grand_total) else 0.0 end) as grand_total, (case when sum(total_discount) > 0 then sum(total_discount) else 0.0 end) as total_discount, (case when sum(total_tax) > 0 then sum(total_tax) else 0.0 end) as total_tax')
.where("shop_code='#{shop.shop_code}' and sale_status = 'completed'")
if (!from.nil? && !to.nil?) && (from != "" && to!="")
query = query.date_between(from, to)
if !from_time.nil? && !to_time.nil?
query = query.time_between(from_time, to_time)
end
.where('sale_status = "completed"')
if (!from.nil? && !to.nil?)
query = query.receipt_date_between(from, to)
else
query = query.date_on(today)
query = query.receipt_date_between(Time.now.beginning_of_day, Time.now.end_of_day)
end
if current_user.present? && !(current_user.role == 'administrator' || current_user.role == 'manager' || current_user.role == 'account' || current_user.role == 'supervisor')
if shift = ShiftSale.current_open_shift(current_user)
query = query.where("sales.shift_sale_id = ?", shift.id)
end
end
query = query.first()
end
def self.total_payment_methods(shop,today,current_user=nil,from=nil,to=nil,from_time=nil,to_time=nil)
query = Sale.select("distinct sp.payment_method")
.where("sales.shop_code='#{shop.shop_code}' and sales.sale_status = 'completed'")
def self.total_payment_methods(current_user=nil,from=nil,to=nil)
query = Sale.select("CASE WHEN sp.payment_method IN ('mpu', 'visa', 'master', 'jcb', 'unionpay', 'alipay', 'paymal', 'dinga', 'JunctionPay', 'giftvoucher') THEN 'card' ELSE sp.payment_method END as payment_method")
.where("sales.sale_status = 'completed'")
.joins("JOIN sale_payments as sp ON sp.sale_id = sales.sale_id")
if (!from.nil? && !to.nil?) && (from != "" && to!="")
query = query.date_between(from, to)
if !from_time.nil? && !to_time.nil?
query = query.time_between(from_time, to_time)
end
.group("CASE WHEN sp.payment_method IN ('mpu', 'visa', 'master', 'jcb', 'unionpay', 'alipay', 'paymal', 'dinga', 'JunctionPay', 'giftvoucher') THEN 'card' ELSE sp.payment_method END")
if (!from.nil? && !to.nil?)
query = query.receipt_date_between(from, to)
else
query = query.date_on(today)
query = query.receipt_date_between(Time.now.beginning_of_day, Time.now.end_of_day)
end
if current_user.present? && !(current_user.role == 'administrator' || current_user.role == 'manager' || current_user.role == 'account' || current_user.role == 'supervisor')
if shift = ShiftSale.current_open_shift(current_user)
query = query.where("sales.shift_sale_id = ?", shift.id)
end
end
return query
end
def self.payment_sale(shop,payment_method, today, current_user=nil,from=nil,to=nil,from_time=nil,to_time=nil)
def self.payment_sale(payment_method, current_user=nil,from=nil,to=nil)
payments_for_credits = SalePayment.joins(:sale_audit).to_sql
query = Sale.select("SUM(sale_payments.payment_amount) - CASE WHEN sale_payments.payment_method = 'creditnote' THEN IFNULL(SUM(payments_for_credits.payment_amount), 0) ELSE ABS(SUM(CASE WHEN sale_payments.outstanding_amount < 0 THEN sale_payments.outstanding_amount ELSE 0 END)) END AS payment_amount")
.joins(:sale_payments)
.joins("LEFT JOIN (#{payments_for_credits}) payments_for_credits ON payments_for_credits.sale_id = sales.sale_id")
.where("sales.shop_code='#{shop.shop_code}'")
.completed
if payment_method == 'card'
@@ -1732,13 +1775,10 @@ end
query = query.where("sale_payments.payment_method = ?", payment_method)
end
if (!from.nil? && !to.nil?) && (from != "" && to!="")
query = query.date_between(from, to)
if !from_time.nil? && !to_time.nil?
query = query.time_between(from_time,to_time)
end
if (!from.nil? && !to.nil?)
query = query.receipt_date_between(from, to)
else
query = query.date_on(today)
query = query.receipt_date_between(Time.now.beginning_of_day, Time.now.end_of_day)
end
if current_user.present? && !(current_user.role == 'administrator' || current_user.role == 'manager' || current_user.role == 'account' || current_user.role == 'supervisor')
@@ -1746,25 +1786,35 @@ end
query = query.where("sales.shift_sale_id = ?", shift.id)
end
end
query.first
end
def self.total_customer(shop,today,current_user=nil,from=nil,to=nil,from_time=nil,to_time=nil)
total_dinein_takeaway = self.total_dinein_takeaway(shop,today,current_user,from,to,from_time,to_time)
def self.total_customer(current_user=nil,from=nil,to=nil)
total_dinein_takeaway = self.total_dinein_takeaway(current_user,from,to)
dinein_cnt = 0
takeaway_cnt = 0
if !total_dinein_takeaway.nil?
if total_dinein_takeaway[0]
dinein_cnt = total_dinein_takeaway[0].total_dinein_cus
takeaway_cnt = total_dinein_takeaway[0].total_take_cus
end
end
membership_cnt = self.total_membership(shop,today,current_user,from,to,from_time,to_time)
membership_cnt = self.total_membership(current_user,from,to)
member_cnt = 0
if !membership_cnt.nil?
member_cnt = membership_cnt.total_memb_cus
end
total_cus = 0
if dinein_cnt > dinein_cnt || takeaway_cnt > 0 || !membership_cnt.nil?
total_cus = dinein_cnt.to_int + takeaway_cnt.to_int + member_cnt.to_int
end
@@ -1772,43 +1822,47 @@ end
return total_cus, dinein_cnt, takeaway_cnt, member_cnt
end
def self.total_dinein_takeaway(shop,today,current_user=nil,from=nil,to=nil,from_time=nil,to_time=nil)
def self.total_dinein_takeaway(current_user=nil,from=nil,to=nil)
query = Sale.select("(CASE WHEN c.customer_type='Dinein' THEN count(sales.customer_id) ELSE 0 END) as total_dinein_cus, (CASE WHEN c.customer_type='Takeaway' THEN count(sales.customer_id) ELSE 0 END) as total_take_cus")
.joins("JOIN customers as c ON c.customer_id = sales.customer_id")
.where("sales.shop_code='#{shop.shop_code}' and sales.sale_status = 'completed' and c.membership_id is null")
if (!from.nil? && !to.nil?) && (from != "" && to!="")
query = query.date_between(from, to)
if !from_time.nil? && !to_time.nil?
query = query.time_between(from_time, to_time)
end
.where('sales.sale_status = "completed" and c.membership_id is null')
if (!from.nil? && !to.nil?)
query = query.receipt_date_between(from, to)
else
query = query.date_on(today)
query = query.receipt_date_between(Time.now.beginning_of_day, Time.now.end_of_day)
end
if current_user.present? && !(current_user.role == 'administrator' || current_user.role == 'manager' || current_user.role == 'account' || current_user.role == 'supervisor')
if shift = ShiftSale.current_open_shift(current_user)
query = query.where("sales.shift_sale_id = ?", shift.id)
end
end
query = query.first()
end
def self.total_membership(shop,today,current_user=nil,from=nil,to=nil,from_time=nil,to_time=nil)
def self.total_membership(current_user=nil,from=nil,to=nil,from_time=nil,to_time=nil)
query = Sale.select("count(distinct sales.customer_id) as total_memb_cus")
.joins("JOIN customers as c ON c.customer_id = sales.customer_id")
.where("sales.shop_code='#{shop.shop_code}' and sales.sale_status = 'completed' and ((c.customer_type = 'Dinein' and c.membership_id is not null) or (c.customer_type = 'Takeaway' and c.membership_id is not null))")
if (!from.nil? && !to.nil?) && (from != "" && to!="")
query = query.date_between(from, to)
if !from_time.nil? && !to_time.nil?
query = query.time_between(from_time, to_time)
end
.where('sales.sale_status = "completed" and ((c.customer_type = "Dinein" and c.membership_id is not null) or (c.customer_type = "Takeaway" and c.membership_id is not null))')
if (!from.nil? && !to.nil?)
query = query.receipt_date_between(from, to)
else
query = query.date_on(today)
query = query.receipt_date_between(Time.now.beginning_of_day, Time.now.end_of_day)
end
if current_user.present? && !(current_user.role == 'administrator' || current_user.role == 'manager' || current_user.role == 'account' || current_user.role == 'supervisor')
if shift = ShiftSale.current_open_shift(current_user)
query = query.where("sales.shift_sale_id = ?", shift.id)
end
end
query = query.first()
end
@@ -1858,18 +1912,18 @@ end
# query = query.first()
# end
def self.total_order(shop,today,current_user=nil,from=nil,to=nil,from_time=nil,to_time=nil)
def self.total_order(current_user=nil,from=nil,to=nil, current_shop)
query = Sale.select("count(distinct sale_orders.order_id) as total_order")
.joins(:sale_orders)
.where("shop_code='#{shop.shop_code}'")
.where("shop_code='#{current_shop.shop_code}'")
.completed
if (!from.nil? && !to.nil?) && (from != "" && to!="")
query = query.date_between(from, to)
if !from_time.nil? && !to_time.nil?
query = query.time_between(from_time, to_time)
end
if (!from.nil? && !to.nil?)
query = query.receipt_date_between(from, to)
else
query = query.date_on(today)
query = query.receipt_date_between(Time.now.beginning_of_day, Time.now.end_of_day)
end
if current_user.present? && !(current_user.role == 'administrator' || current_user.role == 'manager' || current_user.role == 'account' || current_user.role == 'supervisor')
@@ -1881,85 +1935,70 @@ end
query = query.first
end
def self.total_account(shop,today,current_user=nil,from=nil,to=nil,from_time=nil,to_time=nil)
query = Sale.select("distinct b.id as account_id, b.title as title")
.joins("JOIN sale_items as a ON a.sale_id = sales.sale_id")
.joins("JOIN accounts as b ON b.id = a.account_id")
.where("sales.shop_code='#{shop.shop_code}' and sales.sale_status = 'completed'")
if (!from.nil? && !to.nil?) && (from != "" && to!="")
query = query.date_between(from, to)
if !from_time.nil? && !to_time.nil?
query = query.time_between(from_time, to_time)
end
else
query = query.date_on(today)
end
if current_user.present? && !(current_user.role == 'administrator' || current_user.role == 'manager' || current_user.role == 'account' || current_user.role == 'supervisor')
if shift = ShiftSale.current_open_shift(current_user)
query = query.where("sales.shift_sale_id = ?", shift.id)
end
end
return query
end
def self.account_data(shop,account_id, today, current_user=nil,from=nil,to=nil,from_time=nil,to_time=nil)
def self.account_data(account_id, current_user=nil,from=nil,to=nil)
query = Sale.select("count(*) as cnt_acc, SUM(a.price) as total_acc")
.joins("JOIN sale_items as a ON a.sale_id = sales.sale_id")
.where("sales.shop_code='#{shop.shop_code}' and sales.sale_status = 'completed' and a.account_id ='#{account_id}'")
if (!from.nil? && !to.nil?) && (from != "" && to!="")
query = query.date_between(from, to)
if !from_time.nil? && !to_time.nil?
query = query.time_between(from_time, to_time)
end
.where("sales.sale_status = 'completed' and a.account_id ='#{account_id}'")
if (!from.nil? && !to.nil?)
query = query.receipt_date_between(from, to)
else
query = query.date_on(today)
query = query.receipt_date_between(Time.now.beginning_of_day, Time.now.end_of_day)
end
if current_user.present? && !(current_user.role == 'administrator' || current_user.role == 'manager' || current_user.role == 'account' || current_user.role == 'supervisor')
if shift = ShiftSale.current_open_shift(current_user)
query = query.where("sales.shift_sale_id = ?", shift.id)
end
end
query = query.first
end
def self.top_items(shop,today,current_user=nil,from=nil,to=nil,from_time=nil,to_time=nil)
def self.top_items(current_user=nil,from=nil,to=nil)
query = Sale.select("a.product_name as item_name, SUM(a.price) as item_total_price")
.joins("JOIN sale_items as a ON a.sale_id = sales.sale_id")
.where("sales.shop_code='#{shop.shop_code}' and (a.qty > 0 and a.price > 0) and payment_status='paid' and sales.sale_status = 'completed'")
if (!from.nil? && !to.nil?) && (from != "" && to!="")
query = query.date_between(from, to)
if !from_time.nil? && !to_time.nil?
query = query.time_between(from_time, to_time)
end
.where("(a.qty > 0 and a.price > 0) and payment_status='paid' and sales.sale_status = 'completed'")
if (!from.nil? && !to.nil?)
query = query.receipt_date_between(from, to)
else
query = query.date_on(today)
query = query.receipt_date_between(Time.now.beginning_of_day, Time.now.end_of_day)
end
if current_user.present? && !(current_user.role == 'administrator' || current_user.role == 'manager' || current_user.role == 'account' || current_user.role == 'supervisor')
if shift = ShiftSale.current_open_shift(current_user)
query = query.where("sales.shift_sale_id = ?", shift.id)
end
end
query = query.group("a.product_code")
.order("SUM(a.qty) DESC")
.first()
end
def self.total_foc_items(shop,today,current_user=nil,from=nil,to=nil,from_time=nil,to_time=nil)
def self.total_foc_items(current_user=nil,from=nil,to=nil)
query = Sale.joins("JOIN sale_items as a ON a.sale_id = sales.sale_id")
.where("sales.shop_code='#{shop.shop_code}' and sales.sale_status = 'completed' and a.status='foc' and a.product_name like '%FOC%'")
if (!from.nil? && !to.nil?) && (from != "" && to!="")
query = query.date_between(from, to)
if !from_time.nil? && !to_time.nil?
query = query.time_between(from_time, to_time)
end
.where("sales.sale_status = 'completed' and a.status='foc' and a.product_name like '%FOC%'")
if (!from.nil? && !to.nil?)
query = query.receipt_date_between(from, to)
else
query = query.date_on(today)
query = query.receipt_date_between(Time.now.beginning_of_day, Time.now.end_of_day)
end
if current_user.present? && !(current_user.role == 'administrator' || current_user.role == 'manager' || current_user.role == 'account' || current_user.role == 'supervisor')
if shift = ShiftSale.current_open_shift(current_user)
query = query.where("sales.shift_sale_id = ?", shift.id)
end
end
query = query.count()
end
@@ -2096,71 +2135,16 @@ def unique_tax_profiles(order_source, customer_id)
return tax_data
end
def self.top_bottom(shop,today,shift=nil,from=nil,to=nil,from_time=nil,to_time=nil)
if !from.nil? && !to.nil?
query = Sale.select("(SUM(i.qty) * i.price) as grand_total,SUM(i.qty) as total_item," +
" i.price as unit_price,i.product_name")
.joins("JOIN sale_items i ON i.sale_id = sales.sale_id")
if !from_time.nil? && !to_time.nil?
query = query.where("(i.qty > 0 and i.price > 0) and DATE_FORMAT(CONVERT_TZ(receipt_date,'+00:00','+06:30'),'%Y-%m-%d') between '#{from}' and '#{to}'"+
" and DATE_FORMAT(CONVERT_TZ(receipt_date,'+00:00','+06:30'),'%H:%i') between '#{from_time}' and '#{to_time}' and sale_status= 'completed'")
else
query = query.where("shop_code='#{shop.shop_code}' and (i.qty > 0 and i.price > 0) and DATE_FORMAT(CONVERT_TZ(receipt_date,'+00:00','+06:30'),'%Y-%m-%d') between '#{from}' and '#{to}'"+
" and sale_status= 'completed'")
end
if !shift.nil?
query = query.where("shift_sale_id='#{shift.id}'")
end
else
query = Sale.select("(SUM(i.qty) * i.price) as grand_total,SUM(i.qty) as total_item," +
" i.price as unit_price,i.product_name")
.joins("JOIN sale_items i ON i.sale_id = sales.sale_id")
.where("shop_code='#{shop.shop_code}' and (i.qty > 0 and i.price > 0) and DATE_FORMAT(receipt_date,'%Y-%m-%d') = '#{today}'"+
" and sale_status= 'completed'")
if !shift.nil?
query = query.where("shift_sale_id='#{shift.id}'")
end
end
return query
end
def self.hourly_sale_data(shop,today,shift=nil,from=nil,to=nil,from_time=nil,to_time=nil)
if !from.nil? && !to.nil?
query = Sale.select("grand_total")
if !from_time.nil? && !to_time.nil?
query = query.where('sale_status = "completed" and DATE_FORMAT(CONVERT_TZ(receipt_date,"+00:00","+06:30"),"%Y-%m-%d") between ? and ? and DATE_FORMAT(CONVERT_TZ(receipt_date,"+00:00","+06:30"),"%H:%M") between ? and ?',from,to,from_time,to_time)
else
query = query.where('sale_status = "completed" and DATE_FORMAT(CONVERT_TZ(receipt_date,"+00:00","+06:30"),"%Y-%m-%d") between ? and ?',from,to)
end
if !shift.nil?
query = query.where("shift_sale_id='#{shift.id}'")
end
query = query.where("shop_code='#{shop.shop_code}'").group("date_format(CONVERT_TZ(receipt_date,'+00:00', '+06:30'), '%I %p')")
.order('receipt_date')
else
query = Sale.select("grand_total")
.where("shop_code='#{shop.shop_code}' and sale_status = 'completed' and DATE_FORMAT(receipt_date,'%Y-%m-%d') = ?",today)
if !shift.nil?
query = query.where("shift_sale_id='#{shift.id}'")
end
query = query.group("date_format(CONVERT_TZ(receipt_date,'+00:00', '+06:30'), '%I %p')")
.order('receipt_date')
end
def self.employee_sale(shift=nil,from=nil,to=nil,from_time=nil,to_time=nil, current_shop)
return query
end
def self.employee_sale(shop,today,shift=nil,from=nil,to=nil,from_time=nil,to_time=nil)
query = Sale.joins(:cashier)
.joins(:sale_payments)
.paid.completed.where("sales.shop_code='#{shop.shop_code}'")
.paid.completed.where("sales.shop_code='#{current_shop.shop_code}'")
if !from.nil? && !to.nil?
query = query.date_between(from, to)
if !from_time.nil? && !to_time.nil?
query = query.time_between(from_time, to_time)
end
query = query.receipt_date_between(from, to)
else
query = query.date_on(today)
query = query.receipt_date_between(Time.now.beginning_of_day, Time.now.end_of_day)
end
if !shift.nil?
@@ -2313,7 +2297,7 @@ end
def grand_total_round
print_settings = PrintSetting.get_precision_delimiter()
if !print_settings.nil?
self.grand_total =self.grand_total.round(print_settings.precision.to_i)
self.grand_total =self.grand_total.round(precision)
end
end
@@ -2460,8 +2444,6 @@ private
def round_to_precision
if (self.total_amount != self.total_amount_was || self.total_discount != self.total_discount_was || self.total_tax != self.total_tax_was)
if (self.total_amount % 1 > 0 || self.total_discount % 1 > 0 || self.total_tax % 1 > 0)
precision = PrintSetting.get_precision_delimiter().precision.to_i
self.total_amount = self.total_amount.round(precision)
self.total_discount = self.total_discount.round(precision)
self.total_tax = self.total_tax.round(precision)
@@ -2490,7 +2472,11 @@ private
found, inventory_definition = InventoryDefinition.find_product_in_inventory(item,self.shop_code)
if found
if stock_journal = StockJournal.find_by_trans_ref(item.order_items_id)
stock_journal.update(remark: self.sale_status)
if self.payment_status == "foc" && self.payment_status_was != "foc"
stock_journal.update(remark: self.payment_status)
else
stock_journal.update(remark: self.sale_status)
end
end
end
end

View File

@@ -6,7 +6,7 @@ class SaleAudit < ApplicationRecord
belongs_to :sale
belongs_to :credit_payment, -> { 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 :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"
def self.sync_sale_audit_records(sale_audits)
if !sale_audits.nil?

View File

@@ -1,4 +1,5 @@
class SaleItem < ApplicationRecord
include NumberFormattable
self.primary_key = "sale_item_id"
#primary key - need to be unique generated for multiple shops
@@ -13,6 +14,7 @@ class SaleItem < ApplicationRecord
before_validation :round_to_precision
after_update :update_stock_journal
after_save :update_stock_journal_set_item
# Add Sale Items
def self.add_sale_items(sale_items)
@@ -293,8 +295,6 @@ class SaleItem < ApplicationRecord
if self.unit_price != self.unit_price_was || self.price != self.price_was
if unit_price_fraction > 0 || price_fraction > 0
if ['Discount', 'promotion'].include?(self.status)
precision = PrintSetting.get_precision_delimiter().precision.to_i
self.unit_price = self.unit_price.round(precision)
self.price = (self.unit_price * self.qty).round(precision)
self.taxable_price = self.price
@@ -304,40 +304,42 @@ class SaleItem < ApplicationRecord
end
def update_stock_journal
is_void = self.status == "void" && self.status_before_last_save != "void"
cancel_void = self.status_before_last_save == "void" && self.status.nil?
is_edit = self.qty >= 0 && self.qty != self.qty_before_last_save
is_foc = self.status == "foc" && self.status_before_last_save != "foc"
cancel_foc = self.status_before_last_save == "foc"
unless MenuItemInstance.where("item_instance_name <> ''").pluck(:item_instance_code).include?(self.item_instance_code)
is_void = self.status == "void" && self.status_before_last_save != "void"
cancel_void = self.status_before_last_save == "void" && self.status.nil?
is_edit = self.qty >= 0 && self.qty != self.qty_before_last_save
is_foc = self.status == "foc" && self.status_before_last_save != "foc"
cancel_foc = self.status_before_last_save == "foc"
if is_void or cancel_void or is_edit or is_foc or cancel_foc
found, inventory_definition = InventoryDefinition.find_product_in_inventory(self,self.sale.shop_code)
if found
stock = StockJournal.where("shop_code='#{self.sale.shop_code}' and item_code=?", self.item_instance_code).order("id DESC").first
unless stock.nil?
check_item = StockCheckItem.where("shop_code='#{self.sale.shop_code}' and item_code=?", self.item_instance_code).order("id DESC").first
if is_void or cancel_void or is_edit
if is_void
qty = -self.qty
remark = "void"
elsif cancel_void
qty = self.qty
remark = "cancel void"
elsif is_edit
qty = self.qty - self.qty_before_last_save
remark = "edit"
end
StockJournal.add_to_journal(self.item_instance_code, qty, stock.balance, remark, inventory_definition, self.id, StockJournal::SALES_TRANS)
check_item.different = check_item.different + qty
check_item.save
else is_foc or cancel_foc
qty = StockJournal.where(trans_ref: self.sale_item_id).sum("credit-debit")
if order_item_id = self.sale.bookings.first.order_items.where(item_instance_code: self.item_instance_code, qty: self.qty + qty).select(:order_items_id).first.order_items_id
if stock_journal = StockJournal.find_by_trans_ref(order_item_id)
if is_foc
stock_journal.update(remark: "foc")
elsif cancel_foc
stock_journal.update(remark: "cancel_foc")
if is_void or cancel_void or is_edit or is_foc or cancel_foc
found, inventory_definition = InventoryDefinition.find_product_in_inventory(self)
if found
stock = StockJournal.where('item_code=?', self.item_instance_code).order("id DESC").first
unless stock.nil?
check_item = StockCheckItem.where('item_code=?', self.item_instance_code).order("id DESC").first
if is_void or cancel_void or is_edit
if is_void
qty = -self.qty
remark = "void"
elsif cancel_void
qty = self.qty
remark = "cancel void"
elsif is_edit
qty = self.qty - self.qty_before_last_save
remark = "edit"
end
StockJournal.add_to_journal(self.item_instance_code, qty, stock.balance, remark, inventory_definition, self.id, StockJournal::SALES_TRANS)
check_item.different = check_item.different + qty
check_item.save
else is_foc or cancel_foc
qty = StockJournal.where(trans_ref: self.sale_item_id).sum("credit-debit")
if order_item_id = self.sale.bookings.first.order_items.where(item_instance_code: self.item_instance_code, qty: self.qty + qty).select(:order_items_id).first.order_items_id
if stock_journal = StockJournal.find_by_trans_ref(order_item_id)
if is_foc
stock_journal.update(remark: "foc")
elsif cancel_foc
stock_journal.update(remark: "cancel_foc")
end
end
end
end
@@ -346,4 +348,80 @@ class SaleItem < ApplicationRecord
end
end
end
def update_stock_journal_set_item
is_void = self.status == "void" && self.status_before_last_save != "void" && self.qty > 0
cancel_void = self.status_before_last_save == "void" && self.status.nil?
is_edit = self.qty >= 0 && self.qty != self.qty_before_last_save
is_foc = self.status == "foc" && self.status_before_last_save != "foc"
cancel_foc = self.status_before_last_save == "foc"
is_waste = self.status == "waste"
is_spoile = self.status == "spoile"
if MenuItemInstance.where("item_instance_name <> ''").pluck(:item_instance_code).include?(self.item_instance_code)
if self.qty == 1 && self.qty != self.qty_before_last_save
found, inventory_definition = InventoryDefinition.find_product_in_inventory(self)
if found
stock = StockJournal.where('item_code=?', self.item_instance_code).order("id DESC").first
unless stock.nil?
check_item = StockCheckItem.where('item_code=?', self.item_instance_code).order("id DESC").first
if self.qty.to_i >= 0
qty = self.qty - self.qty_was
if stock.balance.to_i >= qty
Rails.logger.info ">> stock is greater than order qty"
remark = "ok"
else
Rails.logger.info " << stock is less than order qty"
remark = "out of stock"
end
end
StockJournal.add_to_journal(self.item_instance_code, qty, stock.balance, remark, inventory_definition, self.id, StockJournal::SALES_TRANS)
check_item.different = check_item.different - qty
check_item.save
else
StockJournal.add_to_journal(self.item_instance_code, self.qty, 0, "out of stock", inventory_definition, self.id, StockJournal::SALES_TRANS)
end
end
elsif is_void or cancel_void or is_edit
if is_void
qty = -self.qty
remark = "void"
elsif cancel_void
qty = self.qty
remark = "cancel void"
elsif is_edit
qty = self.qty - self.qty_before_last_save
remark = "edit"
end
found, inventory_definition = InventoryDefinition.find_product_in_inventory(self)
if found
stock = StockJournal.where('item_code=?', self.item_instance_code).order("id DESC").first
unless stock.nil?
check_item = StockCheckItem.where('item_code=?', self.item_instance_code).order("id DESC").first
StockJournal.add_to_journal(self.item_instance_code, qty, stock.balance, remark, inventory_definition, self.id, StockJournal::SALES_TRANS)
check_item.different = check_item.different + qty
check_item.save
end
end
elsif is_foc or cancel_foc
qty = StockJournal.where(trans_ref: self.sale_item_id).sum("credit-debit")
if stock_journal = StockJournal.where(trans_ref: self.sale_item_id, item_code: self.item_instance_code).order(id: :desc).first
if is_foc
stock_journal.update(remark: "foc")
elsif cancel_foc
stock_journal.update(remark: "cancel_foc")
end
end
elsif is_waste or is_spoile
found, inventory_definition = InventoryDefinition.find_product_in_inventory(self)
if found
if stock_journal = StockJournal.where(trans_ref: self.sale_item_id, item_code: self.item_instance_code)
stock_journal.update(remark: self.status)
end
end
end
end
end
end

View File

@@ -70,8 +70,6 @@ class SalePayment < ApplicationRecord
self.sale = invoice
self.received_amount = cash_amount
self.payment_reference = remark
# puts action_by
# puts "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
self.action_by = action_by
#get all payment for this invoices
if payment_for
@@ -242,10 +240,7 @@ class SalePayment < ApplicationRecord
end
def self.redeem(paypar_url,token,membership_id,received_amount,sale_id)
# membership_actions_data = MembershipAction.find_by_membership_type("redeem");
membership_actions_data = PaymentMethodSetting.find_by_payment_method("Redeem")
puts "This is membership_actions_data"
puts membership_actions_data.to_json
if !membership_actions_data.nil?
url = paypar_url.to_s + membership_actions_data.gateway_url.to_s
@@ -334,8 +329,7 @@ class SalePayment < ApplicationRecord
merchant_uid:merchant_uid,
auth_token:auth_token}.to_json
end
puts params
# Control for Paypar Cloud
begin
response = HTTParty.post(url,

View File

@@ -1,4 +1,5 @@
class SaleTax < ApplicationRecord
include NumberFormattable
self.primary_key = "sale_tax_id"
#primary key - need to be unique generated for multiple shops
@@ -44,7 +45,6 @@ class SaleTax < ApplicationRecord
def round_to_precision
if self.tax_payable_amount != self.tax_payable_amount_was
if self.tax_payable_amount % 1 > 0
precision = PrintSetting.get_precision_delimiter().precision.to_i
self.tax_payable_amount = self.tax_payable_amount.round(precision)
end
end

View File

@@ -1,12 +1,18 @@
class Shop < ApplicationRecord
#ShopDetail = Shop.find_by_id(1)
#ShopDetail = Shop.current_shop
# Shop Image Uploader
mount_uploader :logo, ShopImageUploader
has_many :display_images
accepts_nested_attributes_for :display_images
def file_data=(input_data)
self.data = input_data.read
end
def self.current_shop
ActsAsTenant.current_tenant
end
end

View File

@@ -4,6 +4,8 @@ class StockJournal < ApplicationRecord
ORDER_TRANS = "order"
STOCK_CHECK_TRANS = "stock_check"
scope :created_at_between, -> (from, to) { where(created_at: from..to)}
def self.add_to_journal(item_instance_code, qty, old_balance, stock_message, inventory_definition, trans_ref, trans_type) # item => saleObj | balance => Stock journal
balance = calculate_balance(old_balance, qty)
@@ -56,23 +58,14 @@ class StockJournal < ApplicationRecord
journal.save
end
def self.inventory_balances(today,from,to,from_time,to_time,shop)
def self.inventory_balances(from,to, current_shop)
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")
.order("mii.item_instance_name ASC")
if !from.nil? && !to.nil?
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")
if !from_time.nil? && !to_time.nil?
query = query.where("DATE_FORMAT(CONVERT_TZ(stock_journals.created_at,'+00:00','+06:30'),'%Y-%m-%d') between '#{from}' and '#{to}'")
else
query = query.where("DATE_FORMAT(CONVERT_TZ(stock_journals.created_at,'+00:00','+06:30'),'%Y-%m-%d') between '#{from}' and '#{to}' and DATE_FORMAT(CONVERT_TZ(stock_journals.created_at,'+00:00','+06:30'),'%H:%M') between '#{from_time}' and '#{to_time}'")
end
query = query.where("shop_code='#{shop.shop_code}'").group("mii.item_instance_name")
.order("mii.item_instance_name ASC")
else
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")
.where("shop_code='#{shop.shop_code}' and DATE_FORMAT(stock_journals.created_at,'%Y-%m-%d') = '#{today}'")
.group("mii.item_instance_name")
.order("mii.item_instance_name ASC")
query = query.created_at_between(from, to)
end
end

View File

@@ -4,7 +4,6 @@ class VerifyNumber < ApplicationRecord
url = "http://smspoh.com/api/http/send?key=5QfyN0OtGsFXnOqwtpVAGZCyPGP28nbX_Nm_oPsUw2ybq714T_951ycz3Ypl5URA&message=Doemal,+Pin+Code:+"+pin.to_s+"&recipients="+ phone.to_s
puts url
begin
@result = HTTParty.get(url.to_str)
@@ -18,7 +17,6 @@ class VerifyNumber < ApplicationRecord
response = { status: false, message: "Can't open membership server "}
end
puts @result
puts "<><><><><><<><>><><"
end
end