Merge branch 'r-1902001-01' into foodcourt

This commit is contained in:
Thein Lin Kyaw
2020-07-11 04:00:55 +06:30
99 changed files with 2085 additions and 1781 deletions

View File

@@ -62,7 +62,6 @@ class Booking < ApplicationRecord
scope :active, -> {where("booking_status != 'moved'")}
scope :today, -> {where("created_at >= #{Time.now.utc}")}
scope :assign, -> { where(booking_status: 'assign')}
scope :within_time_limit, -> { where(checkin_at: Lookup.get_checkin_time_limit.hours.ago..DateTime::Infinity.new) }
def self.sync_booking_records(bookings)
if !bookings.nil?

View File

@@ -9,12 +9,12 @@ class DiningFacility < ApplicationRecord
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_bookings, -> { left_joins(:sale).assign.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.merge(Sale.where(sale_status: nil)) }, class_name: "Booking"
has_one :current_checkout_booking, -> { left_joins(:sale).assign.where.not(checkout_at: nil).merge(Sale.where(sale_status: 'new')) }, class_name: "Booking"
has_one :current_reserved_booking, -> { left_joins(:sale).assign.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"
has_many :current_sales, -> { where(sale_status: 'new').merge(Booking.assign) }, through: :bookings, class_name: "Sale", source: "sale"
TABLE_TYPE = "Table"
ROOM_TYPE = "Room"
@@ -45,9 +45,7 @@ class DiningFacility < ApplicationRecord
end
def get_current_booking
checkin_time_lookup = Lookup.get_checkin_time_limit
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
Booking.where(dining_facility_id: self.id, booking_status: 'assign', checkout_at: nil).first #and checkout_at is null
end
def get_checkout_booking
@@ -89,8 +87,6 @@ class DiningFacility < ApplicationRecord
end
def self.get_checkin_booking
checkin_time_lookup = Lookup.get_checkin_time_limit
bookings = self.current_checkin_booking
arr_booking = Array.new
if bookings

View File

@@ -1,6 +1,5 @@
class Employee < ApplicationRecord
has_secure_password
# has_secure_token :auth_token
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"
@@ -34,6 +33,7 @@ class Employee < ApplicationRecord
if (user)
#user.authenticate(password)
if (user.authenticate(password))
puts user
user.generate_token
user.session_expiry = DateTime.now.utc + expiry_time.minutes
user.session_last_login = DateTime.now.utc
@@ -44,20 +44,21 @@ class Employee < ApplicationRecord
return nil
end
def self.authenticate_by_token(token)
if token
if user = Employee.find_by_token_session(token)
expiry_time = login_expiry_time
if user.session_expiry && 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
user.save
return user
end
elsif user = Employee.find_by_app_token(token)
return user
def self.authenticate_by_token(session_token)
if (session_token)
user = Employee.find_by_token_session(session_token)
expiry_time = login_expiry_time
puts expiry_time
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
user.save
return true
else
return false
end
end
return false
end

View File

@@ -27,7 +27,7 @@ class License
end
# For Cloud
def detail_with_local_cache(lookup)
def detail_with_local_cache
aes = MyAesCrypt.new
aes_key, aes_iv = aes.export_to_file(lookup)
@@ -75,21 +75,14 @@ class License
end
# For Local System
def detail_with_local_file()
renewal_date_str = read_license("renewable_date")
if check_expiring(renewal_date_str)
# return for all ok
return 1
def detail_with_local_file
if expired?
return 0
elsif expire_in?(10)
return 2
else
has_license = verify_license()
if has_license
# return for expiring
return 2
else
return 0
end
return 1
end
# end
end
# License Activation
@@ -99,42 +92,58 @@ class License
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)
@activate = response.parsed_response
if (@activate["status"])
begin
response = self.class.get("/activate", @params)
@activate = response.parsed_response
##Check from local redis - if available load local otherwise get from remote
cache_key = "shop:#{@activate["shop_name"]}"
if (@activate["status"])
##Get redis connection from connection pool
# redis = Redis.new
# cache_license = redis.get(cache_key)
##Check from local redis - if available load local otherwise get from remote
cache_key = "shop:#{@activate["shop_name"]}"
Rails.logger.info "Cache key - " + cache_key.to_s
##Get redis connection from connection pool
# redis = Redis.new
# cache_license = redis.get(cache_key)
# 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
Rails.logger.info "Cache key - " + cache_key.to_s
Rails.logger.info "License - " + response.parsed_response.to_s
# 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
response = create_license_file(@activate)
Rails.logger.info "License - " + response.parsed_response.to_s
if(response[:status])
#sym_path = "/home/user/symmetric/"
sym_path = File.expand_path("~/symmetric/")
response = create_symmetric_config(sym_path, db_host, db_schema, db_user, db_password)
response = create_license_file(@activate)
if(response[:status])
response = run_symmetric(sym_path)
#sym_path = "/home/user/symmetric/"
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
else
response = { "status": false, "message": "Activation Failed! Please contact code2lab call center!"}
rescue SocketError => e
Rails.logger.debug "In SocketError No Internet connection !"
response = { "status": false, "message": "In SocketError No Internet connection !"}
rescue HTTParty::Error
Rails.logger.debug "Server Error HTTParty"
response = { "status": false, "message": "Server Error HTTParty"}
rescue Net::OpenTimeout
Rails.logger.debug "connection Timeout"
response = { "status": false, "message": "Connection Timeout"}
rescue OpenURI::HTTPError
Rails.logger.debug "Can't connect server"
response = { "status": false, "message": "Can't connect server"}
end
return response
end
@@ -144,39 +153,50 @@ class License
@params = { query: {lookup_type: "application", api_token: api_token} }
begin
response = self.class.get("/verify", @params)
@varified = response.parsed_response
Rails.logger.debug "License Remote Response - " + response.parsed_response.to_s
if (@varified["status"])
if (!check_expired(@varified["renewable_date"]))
return true
end
else
delete_license_file
response = self.class.get("/verify", @params)
@varified = response.parsed_response
Rails.logger.debug "License Remote Response - " + response.parsed_response.to_s
if (@varified["status"])
old_renewable_date = read_license("renewable_date")
if old_renewable_date.to_date < @varified['renewable_date'].to_date
update_license("renewable_date", @varified['renewable_date'])
return true
end
end
rescue SocketError => e
Rails.logger.debug "In SocketError No Internet connection ! "
return true
rescue HTTParty::Error
Rails.logger.debug "Server Error HTTParty"
return true
rescue Net::OpenTimeout
Rails.logger.debug "connection Timeout"
return true
rescue OpenURI::HTTPError
Rails.logger.debug "Can't connect server"
return true
end
return false
end
def exists?
License.check_license_file(lookup)
end
# Check Expired before 30 days
def check_expiring(renewal_date_str)
if !renewal_date_str.empty?
def expired?
if renewal_date_str = read_license("renewable_date")
renewal_date = DateTime.parse(renewal_date_str)
renewal_date > Date.today.advance(:days => 30)
renewal_date < Date.today
end
end
def expire_in?(days)
if renewal_date_str = read_license("renewable_date")
renewal_date = DateTime.parse(renewal_date_str)
renewal_date < days.days.from_now
end
end
def days_to_expire
if renewal_date_str = read_license("renewable_date")
Date.today - DateTime.parse(renewal_date_str).to_date
end
end
@@ -195,13 +215,14 @@ class License
end
end
def check_license_subdomain(lookup)
def check_license_subdomain
aes = MyAesCrypt.new
aes_key, aes_iv = aes.export_key(lookup)
params = { query: { lookup_type: "cloud", lookup: lookup, iv_key: aes_iv} }
response = self.class.get("/subdomain", params)
response.parsed_response["status"]
rescue
end
# Check License File exists
@@ -209,15 +230,21 @@ class License
return unless File.exist?("config/license.yml")
if license = YAML.load_file("config/license.yml")
if license[lookup].nil?
if ENV["SERVER_MODE"] == "application"
license[lookup] = license.values.first
if license['iv_key']
license = { lookup => license }
else
tld_length = Rails.application.config.action_dispatch.tld_length
subdomains = URL.extract_subdomains(lookup, tld_length)
if key = license.keys.find { |k| URL.extract_subdomains(k, tld_length).last == subdomains.last}
license[lookup] = license[key]
if subdomains.last && subdomains.last != 'www'
if key = license.keys.find { |k| URL.extract_subdomains(k, tld_length).last == subdomains.last}
license[lookup] = license[key]
end
else
license[lookup] = license.values.first
end
end
if license[lookup]
File.open("config/license.yml", "w") { |file| file.write license.to_yaml }
end
@@ -228,9 +255,8 @@ class License
# read line by key for license file
def read_license(key_name)
key, iv = get_redis_key()
if File.exist?("config/license.yml")
key, iv = get_redis_key()
if license = YAML.load(File.read("config/license.yml"))
if license[lookup]
AESCrypt.decrypt_data(decode_str(license[lookup][key_name]), decode_str(key), decode_str(iv), ENV['CIPHER_TYPE'])
@@ -252,13 +278,12 @@ class License
# Update license file for line
def update_license(content, new_content)
key, iv = get_redis_key()
if !new_content.include? "=="
crypted_str = AESCrypt.encrypt_data(new_content, decode_str(key), decode_str(iv), ENV['CIPHER_TYPE'])
end
if File.exist?("config/license.yml")
key, iv = get_redis_key()
if !new_content.include? "=="
crypted_str = AESCrypt.encrypt_data(new_content, decode_str(key), decode_str(iv), ENV['CIPHER_TYPE'])
end
if license = YAML.load_file("config/license.yml")
license[lookup][content] = encode_str(crypted_str)

View File

@@ -38,7 +38,7 @@ class Printer::CashierStationPrinter < Printer::PrinterWorker
# self.print(filename, cashier_terminal.printer_name)
# end
def print_close_cashier(printer_settings,cashier_terminal,shift_sale, sale_items, total_other_charges_info,shop_details,sale_taxes,other_payment,amount,discount,member_discount,total_dinein,total_takeway,total_other_charges,total_waste,total_spoile,total_credit_payments,foodcourt=nil)
def print_close_cashier(printer_settings,cashier_terminal,shift_sale, sale_items, total_other_charges_info,shop_details,sale_taxes,other_payment,amount,discount,member_discount,total_dinein,total_takeway,total_other_charges,total_waste,total_spoile,total_credit_payments,payment_methods,foodcourt=nil)
if !sale_items.blank? or !sale_items.nil?
@account_cate_count = Hash.new {|hash, key| hash[key] = 0}
@@ -59,7 +59,7 @@ class Printer::CashierStationPrinter < Printer::PrinterWorker
cashier = shift_sale.employee.name
shift_name = shift_sale.shift_started_at.utc.getlocal.strftime("%d-%m-%Y %I:%M %p") + "_" + shift_sale.shift_closed_at.utc.getlocal.strftime("%d-%m-%Y %I:%M %p")
filename = "tmp/close_cashier_#{cashier}_#{shift_name}.pdf"
pdf = CloseCashierPdf.new(printer_settings,shift_sale, sale_items, total_other_charges_info, @account_cate_count, @menu_cate_count, @totalByAccount, shop_details,sale_taxes,other_payment,amount,discount,member_discount,total_dinein,total_takeway,total_other_charges,total_waste,total_spoile,total_credit_payments,foodcourt)
pdf = CloseCashierPdf.new(printer_settings,shift_sale, sale_items, total_other_charges_info, @account_cate_count, @menu_cate_count, @totalByAccount, shop_details,sale_taxes,other_payment,amount,discount,member_discount,total_dinein,total_takeway,total_other_charges,total_waste,total_spoile,total_credit_payments,payment_methods,foodcourt)
close_cashier_pdf = Lookup.collection_of("print_settings") #print_settings with name:CloseCashierPdf
if !close_cashier_pdf.empty?
@@ -68,7 +68,7 @@ class Printer::CashierStationPrinter < Printer::PrinterWorker
if close_cashier[1] == '1'
pdf = CloseCashierCustomisePdf.new(printer_settings,shift_sale,shop_details,sale_taxes,other_payment,amount,discount,member_discount,total_dinein,total_takeway,total_other_charges,total_waste,total_spoile,total_credit_payments,foodcourt)
else
pdf = CloseCashierPdf.new(printer_settings,shift_sale, sale_items, total_other_charges_info, @account_cate_count, @menu_cate_count, @totalByAccount, shop_details,sale_taxes,other_payment,amount,discount,member_discount,total_dinein,total_takeway,total_other_charges,total_waste,total_spoile,total_credit_payments,foodcourt)
pdf = CloseCashierPdf.new(printer_settings,shift_sale, sale_items, total_other_charges_info, @account_cate_count, @menu_cate_count, @totalByAccount, shop_details,sale_taxes,other_payment,amount,discount,member_discount,total_dinein,total_takeway,total_other_charges,total_waste,total_spoile,total_credit_payments,payment_methods,foodcourt)
end
end
end

View File

@@ -684,7 +684,7 @@ class Sale < ApplicationRecord
.joins("JOIN orders ON orders.order_id=booking_orders.order_id")
.joins("JOIN order_items ON orders.order_id=order_items.order_id")
.joins("JOIN customers ON orders.customer_id=customers.customer_id")
.where("sales.sale_status =? and sales.payment_status =? and orders.source='app' and sales.shift_sale_id = ?",
.where("sales.sale_status =? and sales.payment_status =? and orders.source='app' and sales.shift_sale_id = ?",
'completed','paid', @current_shift.id
).order("bookings.created_at desc").uniq
@@ -791,20 +791,20 @@ class Sale < ApplicationRecord
return num
end
def self.daily_sales_list(from,to)
payment_methods = SalePayment.where.not(payment_method: ['cash', 'creditnote', 'foc']).distinct.pluck(:payment_method)
def self.daily_sales_list(from,to)
payment_methods = SalePayment.where.not(payment_method: ['cash', 'creditnote', 'foc']).distinct.pluck(:payment_method)
sales = select(Sale.column_names)
.select("#{payment_methods.map { |method| "SUM(case when (sale_payments.payment_method='#{method}') then sale_payments.payment_amount else 0 end) as #{method == 'paypar' ? 'redeem' : method}"}.push('').join(', ')}
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) -
SUM(case when (sale_payments.payment_method not in('creditnote') and 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='foc') then sale_payments.payment_amount else 0 end) as foc_amount")
.sale_payments_with_audit_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
sales = select(Sale.column_names)
.select("#{payment_methods.map { |method| "SUM(case when (sale_payments.payment_method='#{method}') then sale_payments.payment_amount else 0 end) as #{method == 'paypar' ? 'redeem' : method}"}.push('').join(', ')}
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) -
SUM(case when (sale_payments.payment_method not in('creditnote') and 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='foc') then sale_payments.payment_amount else 0 end) as foc_amount")
.sale_payments_with_audit_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
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,
@@ -1238,11 +1238,21 @@ 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)
.joins("INNER JOIN sale_payments sp ON sp.sale_id = sales.sale_id")
.left_joins(:payments_for_credits)
.completed
.where.not(total_amount: 0)
.group(:sale_id)
.order(:receipt_date)
if payment_type.present?
if payment_type == 'card'
query = query.where(sanitize_sql_array(["sp.payment_method IN (?)", SalePayment::CARD]))
else
query = query.where("sp.payment_method = (?)", payment_type)
end
end
if shift.present?
query = query.where("sales.shift_sale_id in (?)", shift.to_a)
elsif shift_sale_range.present?
@@ -1528,7 +1538,7 @@ end
def self.employee_sales(current_user,from,to)
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.id)
ShiftSale.current_open_shift(current_user)
end
payments_for_credits = SalePayment.joins(:sale_audit).to_sql
@@ -1575,7 +1585,7 @@ end
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)
if shift = ShiftSale.current_open_shift(current_user)
query = query.where("sales.shift_sale_id = ?", shift.id)
end
end
@@ -1631,10 +1641,10 @@ end
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")
query = Sale.select(sanitize_sql_array(["CASE WHEN sp.payment_method IN (?) THEN 'card' ELSE sp.payment_method END as payment_method", SalePayment::CARD]))
.where("sales.sale_status = 'completed'")
.joins("JOIN sale_payments as sp ON sp.sale_id = sales.sale_id")
.group("CASE WHEN sp.payment_method IN ('mpu', 'visa', 'master', 'jcb', 'unionpay', 'alipay', 'paymal', 'dinga', 'JunctionPay', 'giftvoucher') THEN 'card' ELSE sp.payment_method END")
.group(sanitize_sql_array(["CASE WHEN sp.payment_method IN (?) THEN 'card' ELSE sp.payment_method END", SalePayment::CARD]))
if (!from.nil? && !to.nil?)
query = query.receipt_date_between(from, to)
@@ -1777,7 +1787,7 @@ end
# query = query.where('DATE_FORMAT(CONVERT_TZ(sales.receipt_date,"+00:00","+06:30"),"%Y-%m-%d") between ? and ?',from,to)
# end
# else
# shift = ShiftSale.current_open_shift(current_user.id)
# shift = ShiftSale.current_open_shift(current_user)
# if !shift.nil?
# if !from_time.nil? && !to_time.nil?
# query = query.where('DATE_FORMAT(CONVERT_TZ(sales.receipt_date,"+00:00","+06:30"),"%Y-%m-%d") between ? and ? and DATE_FORMAT(CONVERT_TZ(sales.receipt_date,"+00:00","+06:30"),"%H:%i") between ? and ? and sales.shift_sale_id=?',from,to,from_time,to_time,shift.id)
@@ -1794,7 +1804,7 @@ end
# if current_user.role == 'administrator' || current_user.role == 'manager' || current_user.role == 'account' || current_user.role == 'supervisor'
# query = query.where('DATE_FORMAT(CONVERT_TZ(sales.receipt_date,"+00:00","+06:30"),"%Y-%m-%d") = ?',today)
# else
# shift = ShiftSale.current_open_shift(current_user.id)
# shift = ShiftSale.current_open_shift(current_user)
# if !shift.nil?
# query = query.where('DATE_FORMAT(CONVERT_TZ(sales.receipt_date,"+00:00","+06:30"),"%Y-%m-%d") = ? and sales.shift_sale_id=?',today,shift.id)
# end
@@ -2311,7 +2321,7 @@ def self.get_daily_sale_data(transaction_date)
CASE WHEN sale_payments.payment_method = 'giftvoucher' THEN SUM(sale_payments.payment_amount) ELSE SUM(0) END as voucher_sales
FROM sale_payments
GROUP BY sale_payments.sale_id, sale_payments.payment_method"
query = Sale.select("
sales.receipt_no as check_num,
sales.receipt_date as business_date,
@@ -2348,49 +2358,50 @@ def self.get_daily_sale_data(transaction_date)
.where("DATE(sales.receipt_date) = ? AND sales.sale_status != ?", transaction_date, :void)
.group("sales.receipt_no,sales.sale_status")
end
def paymal_payment_void
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?
account_no =sale_payments[0].payment_reference
url = membership_setting.gateway_url.to_s + membership_actions_data.gateway_url.to_s
merchant_uid = membership_actions_data.merchant_account_id
auth_token = membership_actions_data.auth_token
params = { receipt_no:self.receipt_no,
account_no:account_no,
merchant_uid:merchant_uid,
auth_token:auth_token}.to_json
# Control for Paypar Cloud
begin
response = HTTParty.post(url,
:body => params,
:headers => {
'Content-Type' => 'application/json',
'Accept' => 'application/json; version=3'
},
:timeout => 10
)
rescue Errno::ECONNREFUSED
response = { "status" => false, "message" => "Can't open membership server"}
rescue Net::OpenTimeout
response = { "status" => false, "message" => "No internet connection " }
rescue OpenURI::HTTPError
response = { "status" => false, "message" => "No internet connection "}
rescue SocketError
response = { "status" => false, "message" => "No internet connection "}
end
def paymal_payment_void
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?
account_no =sale_payments[0].payment_reference
url = membership_setting.gateway_url.to_s + membership_actions_data.gateway_url.to_s
merchant_uid = membership_actions_data.merchant_account_id
auth_token = membership_actions_data.auth_token
params = { receipt_no:self.receipt_no,
account_no:account_no,
merchant_uid:merchant_uid,
auth_token:auth_token}.to_json
# Control for Paypar Cloud
begin
response = HTTParty.post(url,
:body => params,
:headers => {
'Content-Type' => 'application/json',
'Accept' => 'application/json; version=3'
},
:timeout => 10
)
rescue Errno::ECONNREFUSED
response = { "status" => false, "message" => "Can't open membership server"}
rescue Net::OpenTimeout
response = { "status" => false, "message" => "No internet connection " }
rescue OpenURI::HTTPError
response = { "status" => false, "message" => "No internet connection "}
rescue SocketError
response = { "status" => false, "message" => "No internet connection "}
end
end
else
response = { "status" => false}
end
else
response = { "status" => false}
end
Rails.logger.debug "Void Payment response"
Rails.logger.debug response.to_json
return response;
end
Rails.logger.debug "Void Payment response"
Rails.logger.debug response.to_json
return response;
end
# Loader Service SFTP End
private
@@ -2408,7 +2419,9 @@ private
self.total_tax = self.total_tax.round(precision)
end
self.grand_total = (self.total_amount - self.total_discount) + self.total_tax
adjust_rounding
if (!['foc', 'waste', 'spoile', 'void'].include? self.payment_status)
adjust_rounding
end
end
def update_stock_journal

View File

@@ -142,8 +142,9 @@ class SaleAudit < ApplicationRecord
if paymal[0]
remark = paymal[0].remark.split("}")
response = "["+remark[0]+'}]'
response = JSON.parse(response)
# puts response
# response = JSON.parse(response)
if response[0]["status"] == true
if response[0]["current_rebate_amount"].present?
amount = response[0]["current_rebate_amount"]

View File

@@ -1,4 +1,7 @@
class SalePayment < ApplicationRecord
CARD = ['mpu', 'visa', 'master', 'jcb', 'unionpay']
self.primary_key = "sale_payment_id"
#primary key - need to be unique generated for multiple shops
@@ -11,7 +14,7 @@ class SalePayment < ApplicationRecord
attr_accessor :received_amount, :card_payment_reference, :voucher_no, :giftcard_no, :customer_id, :external_payment_status,:action_by
scope :credits, -> { where(payment_method: 'creditnote') }
scope :cards, -> { where(payment_method: ['mpu', 'visa', 'master', 'jcb', 'unionpay', 'alipay', 'paymal', 'dinga', 'JunctionPay', 'giftvoucher']) }
scope :cards, -> { where(payment_method: ['mpu', 'visa', 'master', 'jcb', 'unionpay']) }
def self.sync_sale_payment_records(sale_payments)
if !sale_payments.nil?
@@ -36,7 +39,8 @@ class SalePayment < ApplicationRecord
def self.get_kbz_pay_amount(sale_id, current_user)
amount = 0
kbz_pay_method = PaymentMethodSetting.where(:payment_method => KbzPay::KBZ_PAY).last
kbz_pay_method = PaymentMethodSetting.where(payment_method: KbzPay::KBZ_PAY, gateway_communication_type: ['api', 'Api'], is_active: true)
.where.not(gateway_url: [nil, ''], auth_token: [nil, ''], merchant_account_id: [nil, '']).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'
@@ -120,10 +124,8 @@ class SalePayment < ApplicationRecord
payment_status,membership_data = dinga_payment
when "GiftVoucher"
payment_status = giftvoucher_payment
when KbzPay::KBZ_PAY
payment_status = kbz_payment
else
puts "it was something else"
else
payment_status = external_terminal_card_payment(payment_method, payment_for)
end
if payment_status
@@ -361,10 +363,16 @@ class SalePayment < ApplicationRecord
# Check for Card Payment
def self.get_sale_payments_by_card(sale_payments)
# Check for Card Payment
payment_methods = SalePayment.where.not(payment_method: ['cash', 'creditnote', 'foc']).distinct.pluck(:payment_method)
sale_payments.each do |sp|
if sp.payment_method == "jcb" || sp.payment_method == "mpu" || sp.payment_method == "visa" || sp.payment_method == "master" || sp.payment_method == "unionpay" || sp.payment_method == "alipay"
return true;
payment_methods.each do |m|
if sp.payment_method == m
return true;
end
end
# if sp.payment_method == "jcb" || sp.payment_method == "mpu" || sp.payment_method == "visa" || sp.payment_method == "master" || sp.payment_method == "unionpay" || sp.payment_method == "alipay"
# return true;
# end
end
end
@@ -616,22 +624,12 @@ class SalePayment < ApplicationRecord
return payment_status
end
def kbz_payment
payment_status = false
self.payment_amount = self.received_amount
self.payment_reference = self.payment_reference
self.outstanding_amount = self.sale.grand_total.to_f - self.received_amount.to_f
self.payment_status = "paid"
payment_status = self.save!
# sale_update_payment_status(self.received_amount)
return payment_status
end
def sale_update_payment_status(paid_amount, check_foc = false)
#update amount_outstanding
if ['completed'].include? sale.sale_status
if !self.sale || ['completed'].include?(self.sale.sale_status)
return
end
sale = self.sale
sale_payments = sale.sale_payments.reload
@@ -639,18 +637,14 @@ class SalePayment < ApplicationRecord
is_foc = sale_payments.any? { |x| x.payment_method == "foc" } || check_foc
if is_foc
total_payment_amount = 0.0
else
total_payment_amount = sale_payments.sum(&:payment_amount)
end
sale.amount_received = sale.amount_received.to_f + paid_amount.to_f
sale.amount_changed = total_payment_amount - sale.grand_total.to_f
if is_foc
sale.amount_received = 0.0
sale.amount_changed = 0.0
sale.payment_status = 'foc'
sale.sale_status = 'completed'
elsif sale.grand_total <= total_payment_amount && sale.sale_status == "new"
elsif sale.grand_total <= sale_payments.sum(&:payment_amount) && sale.sale_status == "new"
sale.amount_received = sale.amount_received + paid_amount.to_d
sale.amount_changed = sale_payments.sum(&:payment_amount) - sale.grand_total
sale.payment_status = "paid"
if is_credit
sale.payment_status = "outstanding"
@@ -682,19 +676,9 @@ class SalePayment < ApplicationRecord
end
end
end
sale.save!
if check_foc
table_update_status(sale)
update_shift
elsif paid_amount.to_f > 0 #|| paid_amount != "0.0"
table_update_status(sale)
update_shift
elsif paid_amount.to_f == 0 && !is_credit
table_update_status(sale)
update_shift
end
table_update_status(sale)
update_shift
end
# update for cashier shift

View File

@@ -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("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).take
return shift
#end
end
@@ -150,23 +150,15 @@ class ShiftSale < ApplicationRecord
end
def self.get_by_shift_other_payment(shift)
payment_methods = SalePayment.where.not(payment_method: ['cash', 'creditnote', 'foc']).distinct.pluck(:payment_method)
other_payment = Sale.select("sale_payments.payment_method as name,
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='visa') then (sale_payments.payment_amount) else 0 end) as visa_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='jcb') then (sale_payments.payment_amount) else 0 end) as jcb_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='dinga') then (sale_payments.payment_amount) else 0 end) as dinga_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='JunctionPay') then (sale_payments.payment_amount) else 0 end) as junctionpay_amount,
SUM(case when (sale_payments.payment_method='foc') then (sale_payments.payment_amount) else 0 end) as foc_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='paypar') then (sale_payments.payment_amount) else 0 end) as paypar_amount")
.joins("join sale_payments on sale_payments.sale_id = sales.sale_id")
.where("sales.shift_sale_id =? and sale_status = 'completed' and sale_payments.payment_amount != 0 ", shift.id)
shift_other_payments = Sale.select("sales.sale_id,sale_payments.payment_method as name")
if payment_methods.present?
shift_other_payments = shift_other_payments.select("#{payment_methods.map { |method| "SUM(case when (sale_payments.payment_method='#{method}') then sale_payments.payment_amount else 0 end) as #{method == 'paypar' ? 'redeem' : method}"}.join(', ')}")
end
shift_other_payments.select("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.shift_sale_id =? and sale_status = 'completed' and sale_payments.payment_amount != 0 ", shift.id)
end
def self.calculate_total_price_by_accounts(shift,type)