diff --git a/.gitignore b/.gitignore index 6e0c5583..4f0ac524 100755 --- a/.gitignore +++ b/.gitignore @@ -37,6 +37,7 @@ pickle-email-*.html .rbenv-version config/deploy/config/* config/puma.rb +config/shops.json !/log/.keep !/tmp/.keep .ruby-version diff --git a/Gemfile b/Gemfile index 1432e3af..de22a68c 100755 --- a/Gemfile +++ b/Gemfile @@ -1,5 +1,5 @@ source 'https://rubygems.org' - +ruby '2.4.0' git_source(:github) do |repo_name| repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/") "https://github.com/#{repo_name}.git" @@ -89,10 +89,10 @@ gem 'cancancan', '~> 1.10' # Use Capistrano for deployment # gem 'capistrano-rails', group: :development -group :development, :test do +#group :development, :test do # Call 'byebug' anywhere in the code to stop execution and get a debugger console - gem 'byebug', platform: :mri -end +# gem 'byebug', platform: :mri +#end group :development do # Access an IRB console on exception pages or by using <%= console %> anywhere in the code. @@ -103,6 +103,10 @@ group :development do gem 'spring-watcher-listen', '~> 2.0.0' gem 'rspec-rails', '~> 3.5' gem 'schema_to_scaffold' + gem 'capistrano' + gem 'capistrano-bundler' + gem 'capistrano-rails' + gem 'capistrano-rbenv', github: "capistrano/rbenv" end group :test do @@ -122,4 +126,4 @@ gem 'momentjs-rails' # for date-range selector # gem 'bootstrap-datepicker-rails' # date picker # gem 'jquery-datetimepicker-rails' # gem 'select2-rails' # for multi-select and auto-complete select box -gem "chartkick" #chart lib \ No newline at end of file +gem "chartkick" #chart lib diff --git a/Gemfile.lock b/Gemfile.lock index d29f4058..b7804803 100755 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,3 +1,11 @@ +GIT + remote: https://github.com/capistrano/rbenv.git + revision: c029e4128e4a8f25adda35795f5729bd4f62e51f + specs: + capistrano-rbenv (2.1.3) + capistrano (~> 3.1) + sshkit (~> 1.3) + GEM remote: https://rubygems.org/ specs: @@ -39,12 +47,24 @@ GEM minitest (~> 5.1) tzinfo (~> 1.1) aescrypt (1.0.0) + airbrussh (1.3.0) + sshkit (>= 1.6.1, != 1.7.0) arel (8.0.0) bcrypt (3.1.11) bindex (0.5.0) builder (3.2.3) - byebug (9.1.0) cancancan (1.17.0) + capistrano (3.10.1) + airbrussh (>= 1.0.0) + i18n + rake (>= 10.0.0) + sshkit (>= 1.9.0) + capistrano-bundler (1.3.0) + capistrano (~> 3.1) + sshkit (~> 1.2) + capistrano-rails (1.3.1) + capistrano (~> 3.1) + capistrano-bundler (~> 1.1) carrierwave (1.2.1) activemodel (>= 4.0.0) activesupport (>= 4.0.0) @@ -128,6 +148,9 @@ GEM multi_xml (0.6.0) mysql2 (0.4.9) nested_form (0.3.2) + net-scp (1.2.1) + net-ssh (>= 2.6.5) + net-ssh (4.2.0) nio4r (2.1.0) nokogiri (1.8.1) mini_portile2 (~> 2.3.0) @@ -228,6 +251,9 @@ GEM actionpack (>= 4.0) activesupport (>= 4.0) sprockets (>= 3.0.0) + sshkit (1.15.1) + net-scp (>= 1.1.2) + net-ssh (>= 2.8.0) tether-rails (1.4.0) rails (>= 3.1) thor (0.20.0) @@ -260,8 +286,11 @@ PLATFORMS DEPENDENCIES aescrypt bcrypt (~> 3.1.7) - byebug cancancan (~> 1.10) + capistrano + capistrano-bundler + capistrano-rails + capistrano-rbenv! carrierwave (~> 1.0) chartkick coffee-rails (~> 4.2) @@ -306,5 +335,8 @@ DEPENDENCIES web-console (>= 3.3.0) whenever +RUBY VERSION + ruby 2.4.0p0 + BUNDLED WITH - 1.16.0 + 1.16.1 diff --git a/README.md b/README.md index ef68d0b7..5ff1aeda 100755 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ ruby 2.4.1p111 Campaign Id => {"campaign_type_id": 1} - +java -jar ~/Documents/Jade.jar http://192.168.1.88:3002 * ToDo list diff --git a/app/assets/javascripts/OQS.js b/app/assets/javascripts/OQS.js index f7d517ea..6068b53f 100755 --- a/app/assets/javascripts/OQS.js +++ b/app/assets/javascripts/OQS.js @@ -61,11 +61,11 @@ $(document).on('turbolinks:load', function() { if (data[field]["options"] == "[]" || data[field]["options"] == "") { var options = ""; }else{ - var options = data.options; + var options = data[field]["options"]; } var date = new Date(data[field]["created_at"]); - var show_date = date.getDate() + "-" + date.getMonth() + "-" + date.getFullYear() + ' ' + date.getHours()+ ':' + date.getMinutes(); + var show_date = date.getDate() + "-" + (date.getMonth()+1) + "-" + date.getFullYear() + ' ' + date.getHours()+ ':' + date.getMinutes(); row ='
' +'
' @@ -80,7 +80,7 @@ $(document).on('turbolinks:load', function() { +' [x'+ data[field]["qty"] +'] ' +'

' - +'

'+ options +'

' + +'

'+ options +'

' +'' +'Order at - ' @@ -223,8 +223,9 @@ $(document).on('turbolinks:load', function() { var params = { 'options':options }; $.ajax({ - type: 'GET', + type: 'POST', url: '/oqs/print/print/'+assigned_item_id, + data: params, success: function(data){ } }); }); @@ -243,21 +244,4 @@ $(document).on('turbolinks:load', function() { success: function(data){ } }); }); - - // Qty update for OQS Edit Controller - $('#qty-update').on('click', function(){ - var qty_weight = $("input[name='qty_weight']").val(); - var remarks = $("textarea[name='remarks']").val(); - var order_items_id = $(this).attr('data-id'); - var params = { 'order_items_id': order_items_id, 'qty_weight': qty_weight, 'remarks': remarks } - $.ajax({ - type: 'POST', - url: '/oqs/' + order_items_id, - data: params, - success: function(result){ - alert("Updated!"); - window.location.href = '/oqs'; - } - }); - }); }); diff --git a/app/assets/javascripts/addorder.js b/app/assets/javascripts/addorder.js index 427f9e7b..d8608481 100755 --- a/app/assets/javascripts/addorder.js +++ b/app/assets/javascripts/addorder.js @@ -73,8 +73,9 @@ $(function() { } //end show list function //click menu sidebar menu category - $(".menu_category").on("click", function(){ - var menu_id = $(this).find(".menu-id").text(); + // $(".menu_category").on("click", function(){ + $(document).on('click', '.menu_category', function(event){ + var menu_id = $(this).attr("data-id"); var url = "get_menu_category/"+menu_id; show_menu_item_list(url); }); @@ -525,7 +526,7 @@ $(function() { } }); if (active) { - $(this).revoveClass('selected-option'); + $(this).removeClass('selected-option'); }else{ $(this).addClass('selected-option'); } @@ -855,12 +856,12 @@ $(function() { $('#'+minus).on("click", function(){ - var count = parseInt($('#'+id).val()); - var countEl = document.getElementById(id); + // var count = parseInt($('#'+id).val()); + // var countEl = document.getElementById(id); if (count > 1) { count--; - countEl.value = count; + $('#'+id).val(count); if (id=="count") { price = $("#unit_price").text(); @@ -918,6 +919,47 @@ $(function() { } }); + //click menu sidebar menu category + + $(".sub_click").on("click", function(){ + var menu_id = $(this).attr("data-id"); + var url = "get_menu_sub_category/"+menu_id; + sub_category = $(this).find('.sub_category_list'); + show_sub_category_list(url,sub_category); + }); + //End menu category Click + + //show menu item list when click menu category + function show_sub_category_list(url,sub_category){ + + var menu_list = $('.sub_category_list'); + menu_list.empty(); + //Start Ajax + $.ajax({ + type: "GET", + url: url, + data: {}, + dataType: "json", + success: function(data) { + var sub_category_list = $('.sub_category_list'); + sub_category_list.empty(); + data = data.sub_category; + + if (data.length>0) { + $(sub_category).removeClass('hidden'); + for(var i in data) { + + row = '' ; + $(sub_category).append(row); + //end is_sub_item false + } + } + } + }); + //end Ajax + } /* $("input").keypress(function(){ $("span").text(i += 1); });*/ diff --git a/app/assets/javascripts/application.js b/app/assets/javascripts/application.js index 92fab4ab..76341958 100755 --- a/app/assets/javascripts/application.js +++ b/app/assets/javascripts/application.js @@ -62,9 +62,6 @@ $(document).ready(function() { clearButton: true, date: false }); - - // first input focus for all form - $("body").has("form").find("input:first").focus(); // Image Upload $("#simple_menu_item_image_path").fileinput({ @@ -107,6 +104,9 @@ $(document).ready(function() { } }); + // first input focus for all form + $('form:first *input[data-behaviour!=datepicker]:input[type!=hidden]:first').focus(); + // $(document).on("focus", "[data-behaviour~='datepicker']", function(e){ // $(this).datepicker({"format": "yyyy-M-dd", "weekStart": 1, "autoclose": true}); // $('.dropdown-toggle').dropdown(); diff --git a/app/assets/javascripts/channels/bill.js b/app/assets/javascripts/channels/bill.js index ab8e0898..b4016b1c 100755 --- a/app/assets/javascripts/channels/bill.js +++ b/app/assets/javascripts/channels/bill.js @@ -5,10 +5,15 @@ App.order = App.cable.subscriptions.create('BillChannel', { disconnected: function() {}, - received: function(data) { - $('.table_'+data.table.id).removeClass('blue'); - $('.table_'+data.table.id).addClass('red'); - $('.new_text_'+data.table.id).removeClass('hide') + received: function(data) { + if($('.table_'+data.table.id).hasClass('blue')){ + $('.table_'+data.table.id).removeClass('blue'); + $('.table_'+data.table.id).addClass('red'); + }else{ + $('.table_'+data.table.id).removeClass('orange'); + $('.table_'+data.table.id).addClass('red'); + } + $('.new_text_'+data.table.id).removeClass('hide'); } }); diff --git a/app/assets/javascripts/channels/call_waiter.js b/app/assets/javascripts/channels/call_waiter.js new file mode 100644 index 00000000..941a6359 --- /dev/null +++ b/app/assets/javascripts/channels/call_waiter.js @@ -0,0 +1,61 @@ +App.call_waiter = App.cable.subscriptions.create('CallWaiterChannel', { +// App.messages = App.cable.subscriptions.create('MessagesChannel', { + + connected: function() {}, + + disconnected: function() {}, + + received: function(data) { + table = data.table + + // for Notificaiotn message + var element = "#notify-wrapper" + var placementFrom = "top"; + var placementAlign = "center"; + var animateEnter = ""; + var animateExit = ""; + var colorName = "alert-warning"; + var text = " Calling Waiter
"+table.name ; + + if (text != null || colorName != null){ + showNotification(element, colorName, text, placementFrom, placementAlign, animateEnter, animateExit); + } + + function showNotification(element, colorName, text, placementFrom, placementAlign, animateEnter, animateExit) { + if (colorName === null || colorName === '') { colorName = 'bg-black'; } + if (animateEnter === null || animateEnter === '') { animateEnter = 'animated fadeInDown'; } + if (animateExit === null || animateExit === '') { animateExit = 'animated fadeOutUp'; } + var allowDismiss = true; + + $.notify({ + message: text + }, + { + element: element, + type: colorName, + allow_dismiss: allowDismiss, + timer: 200000000000000, + placement: { + from: placementFrom, + align: placementAlign + }, + animate: { + enter: animateEnter, + exit: animateExit + }, + template: '' + }); + } + //end Notificaiotn message +} +}); + diff --git a/app/assets/javascripts/channels/check_in_booking.js b/app/assets/javascripts/channels/check_in_booking.js new file mode 100644 index 00000000..18597f4d --- /dev/null +++ b/app/assets/javascripts/channels/check_in_booking.js @@ -0,0 +1,16 @@ +App.checkin = App.cable.subscriptions.create('CheckInBookingChannel', { +// App.messages = App.cable.subscriptions.create('MessagesChannel', { + + connected: function() {}, + + disconnected: function() {}, + + received: function(data) { + if($('.table_'+data.table.id).hasClass('green')){ + $('.table_'+data.table.id).removeClass('green'); + $('.table_'+data.table.id).addClass('blue'); + } + $('.new_text_'+data.table.id).removeClass('hide'); + } +}); + diff --git a/app/assets/javascripts/channels/checkin.js b/app/assets/javascripts/channels/checkin.js new file mode 100644 index 00000000..03159170 --- /dev/null +++ b/app/assets/javascripts/channels/checkin.js @@ -0,0 +1,26 @@ +App.order = App.cable.subscriptions.create('CheckinChannel', { +// App.messages = App.cable.subscriptions.create('MessagesChannel', { + + connected: function() {}, + + disconnected: function() {}, + + received: function(data) { + $.each(data.table,function(key,value){ + if($('.table_'+value.table_id).hasClass('blue')){ + $('.table_'+value.table_id).removeClass('blue'); + $('.table_'+value.table_id).addClass('orange'); + } + else if($('.table_'+value.table_id).hasClass('red')){ + $('.table_'+value.table_id).removeClass('red'); + $('.table_'+value.table_id).addClass('orange'); + } + else { + $('.table_'+value.table_id).removeClass('green'); + $('.table_'+value.table_id).addClass('orange'); + } + $('.new_text_'+value.table_id).removeClass('hide'); + }); + } +}); + diff --git a/app/assets/javascripts/channels/order_queue_station.js b/app/assets/javascripts/channels/order_queue_station.js index 4e169f19..d2b502d4 100755 --- a/app/assets/javascripts/channels/order_queue_station.js +++ b/app/assets/javascripts/channels/order_queue_station.js @@ -14,7 +14,7 @@ App.order_queue_station = App.cable.subscriptions.create('OrderQueueStationChann if (items[field]["options"] == "[]" || items[field]["options"] == "") { var options = ""; }else{ - var options = items.options; + var options = items[field]["options"]; } //for count test = document.getElementsByClassName("oqs_count"); @@ -30,7 +30,7 @@ App.order_queue_station = App.cable.subscriptions.create('OrderQueueStationChann //end count var date = new Date(items[field]["created_at"]); - var show_date = date.getDate() + "-" + date.getMonth() + "-" + date.getFullYear() + ' ' + date.getHours()+ ':' + date.getMinutes(); + var show_date = date.getDate() + "-" + (date.getMonth()+1) + "-" + date.getFullYear() + ' ' + date.getHours()+ ':' + date.getMinutes(); if (oqs_id == items[field]["order_queue_station_id"]) { @@ -49,7 +49,7 @@ App.order_queue_station = App.cable.subscriptions.create('OrderQueueStationChann +' [x'+ items[field]["qty"] +'] ' +'

' - +'

'+ options +'

' + +'

'+ options +'

' +'' +'Order at - ' diff --git a/app/assets/javascripts/origami.js b/app/assets/javascripts/origami.js index f23d13c6..33252efa 100755 --- a/app/assets/javascripts/origami.js +++ b/app/assets/javascripts/origami.js @@ -143,3 +143,55 @@ $(document).on('turbolinks:load', function() { return false; }); }); + +/* start check first bill or not funs: */ +function checkReceiptNoInFirstBillData(receipt_no,payment) { + // localStorage.removeItem('receipt_lists'); + var status = false; + if((receipt_no!=undefined) && (receipt_no!="")){ + if(localStorage.hasOwnProperty("receipt_lists")===true){ + var arr_data = JSON.parse(localStorage.getItem("receipt_lists")); + if (payment) { + var json_data = arr_data.filter(function(e) { return e.receipt_no == receipt_no }); + }else{ + var json_data = arr_data.filter(function(e) { return e.receipt_no !== receipt_no }); + } + + if((arr_data.length) > (json_data.length)){ + status = true; + } + } + } + if (payment) { + return json_data[0]["payment"]; + }else{ + return status; + } +} + +function createReceiptNoInFirstBillData(receipt_no,payment) { + var arr_data = []; + var json_data = []; + if(localStorage.hasOwnProperty("receipt_lists") === true){ + arr_data = JSON.parse(localStorage.getItem("receipt_lists")); + json_data = arr_data.filter(function(e) { return e.receipt_no == receipt_no }); + if (payment) { + jdata = arr_data.filter(function(e) { return e.receipt_no !== receipt_no }); + jdata.push({'receipt_no':receipt_no,'payment':payment}); + localStorage.setItem("receipt_lists",JSON.stringify(jdata)); + } + } + if(((arr_data.length == 0) && (json_data.length == 0)) || ((arr_data.length > 0) && (json_data.length == 0))){ + arr_data.push({'receipt_no':receipt_no,'payment':payment}); + localStorage.setItem("receipt_lists",JSON.stringify(arr_data)); + } +} + +function deleteReceiptNoInFirstBillData(receipt_no) { + if(localStorage.hasOwnProperty("receipt_lists") ===true ){ + var arr_data = JSON.parse(localStorage.getItem("receipt_lists")); + var json_data = arr_data.filter(function(e) { return e.receipt_no !== receipt_no }); + localStorage.setItem("receipt_lists",JSON.stringify(json_data)); + } +} +/* end check first bill or not funs: */ \ No newline at end of file diff --git a/app/assets/stylesheets/CRM.scss b/app/assets/stylesheets/CRM.scss index 7f9192f2..8b652eac 100755 --- a/app/assets/stylesheets/CRM.scss +++ b/app/assets/stylesheets/CRM.scss @@ -114,9 +114,11 @@ .green{ background-color: #009900; } -.left{ + +.left-margin-1 { margin-left:1px; } + .bottom{ margin-bottom:1px; } @@ -149,3 +151,9 @@ nav.pagination .page a:hover, text-decoration: none; } + +/*Logout Icon*/ +i.logout_icon{ + position: relative; + top: 5px; +} \ No newline at end of file diff --git a/app/assets/stylesheets/OQS.scss b/app/assets/stylesheets/OQS.scss index 12fbd548..88b00402 100755 --- a/app/assets/stylesheets/OQS.scss +++ b/app/assets/stylesheets/OQS.scss @@ -100,3 +100,8 @@ select.form-control { border-left:1px solid #fff; } +/*Logout Icon*/ +i.logout_icon{ + position: relative; + top: 5px; +} \ No newline at end of file diff --git a/app/assets/stylesheets/addorder.scss b/app/assets/stylesheets/addorder.scss index 8c535855..bf09f726 100755 --- a/app/assets/stylesheets/addorder.scss +++ b/app/assets/stylesheets/addorder.scss @@ -69,7 +69,17 @@ section .content{ font-weight: bold; border-color: #fff #fff #fff #54A5AF; } - +.sub_category_list{ + background:#fff; + margin-top:8px; +} +.sub_category_list > li{ + list-style:none; + margin-left:-40px; +} +.sub_category_list > li > a.nav-link{ + border-bottom:1px solid #eee; +} .custom-modal-dialog { left:auto; right: auto; @@ -157,4 +167,10 @@ section.content{ .add_icon{ cursor: pointer; +} + +/*Logout Icon*/ +i.logout_icon{ + position: relative; + top: 5px; } \ No newline at end of file diff --git a/app/assets/stylesheets/application.scss b/app/assets/stylesheets/application.scss index 9caef6fe..2249d049 100755 --- a/app/assets/stylesheets/application.scss +++ b/app/assets/stylesheets/application.scss @@ -93,3 +93,9 @@ nav.pagination .page a:hover, text-decoration: none; } + +/*Logout Icon*/ +i.logout_icon{ + position: relative; + top: 5px; +} \ No newline at end of file diff --git a/app/assets/stylesheets/inventory_definitions.scss b/app/assets/stylesheets/inventory_definitions.scss index 9d2c2775..aa02f08d 100755 --- a/app/assets/stylesheets/inventory_definitions.scss +++ b/app/assets/stylesheets/inventory_definitions.scss @@ -275,3 +275,8 @@ tr.discount-item-row:hover { -moz-opacity: 1; /* mozilla */ } +/*Logout Icon*/ +i.logout_icon{ + position: relative; + top: 5px; +} \ No newline at end of file diff --git a/app/assets/stylesheets/origami.scss b/app/assets/stylesheets/origami.scss index e097b448..30d8a090 100755 --- a/app/assets/stylesheets/origami.scss +++ b/app/assets/stylesheets/origami.scss @@ -262,6 +262,10 @@ select.form-control { margin-left:1px; } +.dtp-date .left{ + margin-left:0px; +} + .bottom{ margin-bottom:1px; } @@ -357,3 +361,32 @@ tr.discount-item-row:hover { } /* End Payment Page */ + +/* Logout Icon */ + +i.logout_icon{ + position: relative; + top: 5px; +} + +/* End Logout Icon */ + +/* Notify */ + +#notify-wrapper { + position: absolute; + top: 55px; + left: 10px; + z-index: 9999; + opacity: 0.8; +} + +[data-notify="container"] { + margin-bottom: 5px !important; + margin-left:5px !important; + position:relative !important; + top: 25% !important; + width: 100% !important; +} + +/* End Notify */ diff --git a/app/assets/stylesheets/reset.css b/app/assets/stylesheets/reset.css index e118c9f8..ea0aaa4f 100644 --- a/app/assets/stylesheets/reset.css +++ b/app/assets/stylesheets/reset.css @@ -265,5 +265,13 @@ section.content { color: #F44336; } + +/*notification */ +.alert { + padding: .25rem .25rem !important; +} +.alert-dismissible .close { + padding: 0.5rem 0.44rem; +} /* End Reset Theme */ /* *************************************************** */ \ No newline at end of file diff --git a/app/channels/application_cable/channel.rb b/app/channels/application_cable/channel.rb index b2cb741f..89fe509d 100755 --- a/app/channels/application_cable/channel.rb +++ b/app/channels/application_cable/channel.rb @@ -15,4 +15,9 @@ module ApplicationCable class BillChannel < ActionCable::Channel::Base end + + # Call Waiter Channel + class CallWaiterChannel < ActionCable::Channel::Base + + end end diff --git a/app/channels/application_cable/connection.rb b/app/channels/application_cable/connection.rb index 9da60bf4..4efdb70d 100755 --- a/app/channels/application_cable/connection.rb +++ b/app/channels/application_cable/connection.rb @@ -1,7 +1,7 @@ module ApplicationCable class Connection < ActionCable::Connection::Base def connect - logger.add_tags "ActionCable" + logger.add_tags "SX-ActionCable" end end end diff --git a/app/channels/call_waiter_channel.rb b/app/channels/call_waiter_channel.rb new file mode 100644 index 00000000..53eb7e61 --- /dev/null +++ b/app/channels/call_waiter_channel.rb @@ -0,0 +1,14 @@ +class CallWaiterChannel < ApplicationCable::Channel + def subscribed + stream_from "call_waiter_channel" + end + + def unsubscribed + stop_all_streams + # Any cleanup needed when channel is unsubscribed + end + + def order(message) + # ToDo + end +end \ No newline at end of file diff --git a/app/channels/check_in_booking_channel.rb b/app/channels/check_in_booking_channel.rb new file mode 100644 index 00000000..f9df89ba --- /dev/null +++ b/app/channels/check_in_booking_channel.rb @@ -0,0 +1,10 @@ +class CheckInBookingChannel < ApplicationCable::Channel + def subscribed + stream_from "check_in_booking_channel" + end + + def unsubscribed + stop_all_streams + # Any cleanup needed when channel is unsubscribed + end +end diff --git a/app/channels/checkin_channel.rb b/app/channels/checkin_channel.rb new file mode 100644 index 00000000..c2e78132 --- /dev/null +++ b/app/channels/checkin_channel.rb @@ -0,0 +1,10 @@ +class CheckinChannel < ApplicationCable::Channel + def subscribed + stream_from "checkin_channel" + end + + def unsubscribed + stop_all_streams + # Any cleanup needed when channel is unsubscribed + end +end diff --git a/app/controllers/api/bill_controller.rb b/app/controllers/api/bill_controller.rb index aff97bff..387b7bf8 100755 --- a/app/controllers/api/bill_controller.rb +++ b/app/controllers/api/bill_controller.rb @@ -5,7 +5,8 @@ class Api::BillController < Api::ApiController def create @status = false @error_message = "Order ID or Booking ID is require to request for a bill." - if ShiftSale.current_shift + + if shift_by_terminal = ShiftSale.current_open_shift(get_cashier[0].id) #create Bill by Booking ID table = 0 if (params[:booking_id]) @@ -15,16 +16,18 @@ class Api::BillController < Api::ApiController cashier_zone = CashierTerminalByZone.find_by_zone_id(table.zone_id) - shift_by_terminal = ShiftSale.find_by_cashier_terminal_id(cashier_zone.cashier_terminal_id) + shift_by_terminal = ShiftSale.find_by_cashier_terminal_id_and_shift_closed_at(cashier_zone.cashier_terminal_id,nil) get_cashier_by_terminal = Employee.find(shift_by_terminal.employee_id) if booking if booking.sale_id.nil? @sale = Sale.new @status, @sale_id = @sale.generate_invoice_from_booking(params[:booking_id], current_login_employee, get_cashier_by_terminal) + @sale_data = Sale.find_by_sale_id(@sale_id) else @status = true @sale_id = booking.sale_id + @sale_data = Sale.find_by_sale_id(@sale_id) end end @@ -36,6 +39,11 @@ class Api::BillController < Api::ApiController booking = Booking.find_by_sale_id(@sale_id) table = DiningFacility.find(booking.dining_facility_id) end + + # Bind shift sale id to sale + @sale_data.shift_sale_id = shift_by_terminal.id + @sale_data.save + Promotion.promo_activate(@sale) BillBroadcastJob.perform_later(table) diff --git a/app/controllers/api/call_waiters_controller.rb b/app/controllers/api/call_waiters_controller.rb new file mode 100644 index 00000000..a778af12 --- /dev/null +++ b/app/controllers/api/call_waiters_controller.rb @@ -0,0 +1,20 @@ +class Api::CallWaitersController < ActionController::API + + #List all active customers by name + def index + @table_id = params[:dining_id] + @time = params[:time] + @table = DiningFacility.find(@table_id) + CallWaiterJob.perform_later(@table,@time) + + # get printer info + # @shop = Shop::ShopDetail + # unique_code = "CallWaiterPdf" + # print_settings = PrintSetting.find_by_unique_code(unique_code) + # printer = Printer::ReceiptPrinter.new(print_settings) + # printer.print_call_waiter(print_settings,@table,@time,@shop) + + end + + +end diff --git a/app/controllers/api/check_in_process_controller.rb b/app/controllers/api/check_in_process_controller.rb index 0baa258a..488684e7 100644 --- a/app/controllers/api/check_in_process_controller.rb +++ b/app/controllers/api/check_in_process_controller.rb @@ -1,23 +1,47 @@ class Api::CheckInProcessController < Api::ApiController + def check_in_time + if params[:dining_id] + dining_facility = DiningFacility.find(params[:dining_id]) + booking = dining_facility.get_current_checkout_booking + if !booking.nil? + + DiningFacility.check_in_booking(params[:dining_id]) + + check_in_time = booking.checkin_at.utc.getlocal.strftime("%Y-%m-%d %H:%M") + check_out_time = booking.checkout_at.utc.getlocal.strftime("%Y-%m-%d %H:%M") + + lookup_checkout_time = Lookup.collection_of("checkout_alert_time") + alert_time_min = 0 + if !lookup_checkout_time.nil? + if lookup_checkout_time[0][0] == 'min' + alert_time_min = (lookup_checkout_time[0][1]).to_i + else + alert_time_min = 15 + end + end + + render :json => { :status => true, :check_in_time => check_in_time, :check_out_time => check_out_time, :alert_time_min => alert_time_min } + else + render :json => { :status => false, :error_message => "No current booking!" } + end + end + end + def check_in_process if params[:dining_id] dining_facility = DiningFacility.find(params[:dining_id]) if dining_facility.status == "available" - dining_charge = DiningCharge.select('charge_type','charge_block') - .where('dining_facility_id = ?',params[:dining_id]) - .first() + lookup_checkout_time = Lookup.collection_of("checkout_time") checkout_at = Time.now.utc - if !dining_charge.nil? - hr = (dining_charge.charge_block.utc.strftime("%H").to_i).to_int - min = (dining_charge.charge_block.utc.strftime("%M").to_i).to_int - # if dining_charge.charge_type == 'hr' - checkout_at = checkout_at + hr.hour + min.minutes - # else - - # end + if !lookup_checkout_time.nil? + if lookup_checkout_time[0][0] == 'hr' + checkout_at = checkout_at + (lookup_checkout_time[0][1]).to_i.hour + else + checkout_at = checkout_at + (lookup_checkout_time[0][1]).to_i.minutes + end end dining_facility.status = "occupied" @@ -28,12 +52,12 @@ class Api::CheckInProcessController < Api::ApiController else type = "RoomBooking" end - + booking = Booking.create({:dining_facility_id => params[:dining_id],:type => type, - :checkin_at => Time.now.utc,:checkout_at =>checkout_at, :booking_status => "assign" }) + :checkin_by=>current_login_employee.name,:checkin_at => Time.now.utc,:checkout_at =>checkout_at, :booking_status => "assign", :reserved_at => checkout_at, :reserved_by => current_login_employee.name }) booking.save! - render :json => { :status => true, :checkout_at => booking.checkout_at.utc.strftime("%Y-%m-%d %H:%M") } + render :json => { :status => true, :checkout_at => booking.checkout_at.utc.getlocal.strftime("%Y-%m-%d %H:%M") } else error_message = "#{dining_facility.type} is not available!" render :json => { :status => false, :error_message => error_message } @@ -58,7 +82,7 @@ class Api::CheckInProcessController < Api::ApiController booking.checkout_at = checkout_at booking.save! - render :json => { :status => true, :checkout_at => booking.checkout_at.utc.strftime("%Y-%m-%d %H:%M") } + render :json => { :status => true, :checkout_at => booking.checkout_at.utc.getlocal.strftime("%Y-%m-%d %H:%M") } elsif !params[:booking_id].nil? && params[:time].nil? error_message = "time is required!" render :json => { :status => false, :error_message => error_message } diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 83222004..7fafd6bd 100755 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -22,9 +22,10 @@ class ApplicationController < ActionController::Base { locale: I18n.locale } end - def lookup_domain - if request.subdomain.present? && request.subdomain != "www" - @license = cache_license(ENV["SX_PROVISION_URL"], request.subdomain.downcase) # request.subdomain.downcase + def lookup_domain + if request.subdomain.present? && request.subdomain != "www" + from = request.subdomain.downcase + "." + request.domain.downcase + @license = cache_license(ENV["SX_PROVISION_URL"], from) # request.subdomain.downcase if (!@license.nil?) # logger.info "Location - " + @license.name ActiveRecord::Base.establish_connection(website_connection(@license)) @@ -35,31 +36,32 @@ class ApplicationController < ActionController::Base # redirect_to root_url(:host => request.domain) + "store_error" render :json => [{ status: false, message: 'Invalid Access!'}] end - else + else # check for license file - if check_license - current_license(ENV["SX_PROVISION_URL"]) - end + # if check_license + # current_license(ENV["SX_PROVISION_URL"]) + # else + # redirect_to activate_path + # end end end - def current_license(url) + def current_license(url) @license = License.new(url) - - if (@license.detail_with_local_file() == true) - puts "RUN SAY BYAR" + flag = @license.detail_with_local_file() + if (flag == 0) + flash[:notice] = 'Expired or No License!' + elsif (flag == 2) + flash[:notice] = 'Expiring! Please, License extend...' else - return nil + puts "RUN SAY BYAR" end end - def cache_license(url, lookup) - @license = License.new(url, lookup) - # Export for Key - aes = MyAesCrypt.new - aes_key, aes_iv = aes.export_key(lookup) + def cache_license(url, lookup) + @license = License.new(url, lookup) - if (@license.detail_with_local_cache(lookup, aes_key, aes_iv) == true) + if (@license.detail_with_local_cache(lookup) == true) return @license else return nil @@ -109,9 +111,8 @@ class ApplicationController < ActionController::Base def check_license if License.check_license_file return true - else - redirect_to install_path end + return false end end diff --git a/app/controllers/base_controller.rb b/app/controllers/base_controller.rb index 9f0914c4..1bf5b4d4 100755 --- a/app/controllers/base_controller.rb +++ b/app/controllers/base_controller.rb @@ -1,4 +1,5 @@ class BaseController < ActionController::Base layout "installation" protect_from_forgery with: :exception + end diff --git a/app/controllers/base_origami_controller.rb b/app/controllers/base_origami_controller.rb index 979fdf02..ec415bad 100755 --- a/app/controllers/base_origami_controller.rb +++ b/app/controllers/base_origami_controller.rb @@ -2,6 +2,8 @@ class BaseOrigamiController < ActionController::Base include LoginVerification layout "origami" + # before_action :checkin_process + #before_action :check_installation protect_from_forgery with: :exception rescue_from CanCan::AccessDenied do |exception| @@ -13,4 +15,7 @@ class BaseOrigamiController < ActionController::Base @current_user ||= Employee.find_by_token_session(session[:session_token]) if session[:session_token] end + # def checkin_process + # CheckinJob.set(wait: 1.minute).perform_later() + # end end diff --git a/app/controllers/crm/customers_controller.rb b/app/controllers/crm/customers_controller.rb index f95b54a9..51ddc9eb 100755 --- a/app/controllers/crm/customers_controller.rb +++ b/app/controllers/crm/customers_controller.rb @@ -72,7 +72,9 @@ class Crm::CustomersController < BaseCrmController #get customer amount @customer = Customer.find(params[:id]) @response = Customer.get_membership_transactions(@customer) - puts @response.to_json + + Rails.logger.debug "get membership transactions response" + Rails.logger.debug @response.to_json # @response = "" #end customer amount @@ -156,7 +158,8 @@ class Crm::CustomersController < BaseCrmController rescue SocketError response = {"status" => false, "message" => "Can't open membership server "} end - + Rails.logger.debug "--------------Create Member---------" + Rails.logger.debug response.to_json if response["status"] == true customer = Customer.find(@crm_customers.customer_id) status = customer.update_attributes(membership_id: response["customer_datas"]["id"],membership_type:member_group_id ) @@ -235,7 +238,7 @@ end id = @crm_customer.membership_id member_group_id = params[:member_group_id] - if id.nil? && !member_group_id.nil? + if !id.present? && !member_group_id.nil? membership = MembershipSetting.find_by_membership_type("paypar_url") memberaction = MembershipAction.find_by_membership_type("create_membership_customer") merchant_uid = memberaction.merchant_account_id.to_s @@ -277,10 +280,9 @@ end rescue SocketError response = { status: false} end - puts "ssssssss" - puts response.to_json customer = Customer.find(@crm_customer.customer_id) - + Rails.logger.debug "--------Update Member response -------" + Rails.logger.debug response.to_json if response["status"] == true status = customer.update_attributes(membership_id: response["customer_datas"]["id"],membership_type:member_group_id ) @@ -337,10 +339,8 @@ end rescue SocketError response = { status: false} end - - puts "ssssssss" - puts response.to_json - + Rails.logger.debug "--------Update Member response -------" + Rails.logger.debug response.to_json if response["status"] == true customer = Customer.find(@crm_customer.customer_id) # Check membership id and bind to user diff --git a/app/controllers/home_controller.rb b/app/controllers/home_controller.rb index 8c3d7cc4..1ee30bab 100755 --- a/app/controllers/home_controller.rb +++ b/app/controllers/home_controller.rb @@ -3,7 +3,8 @@ class HomeController < ApplicationController skip_before_action :authenticate, only: [:index, :show, :create, :update, :destroy] def index - @employees = Employee.all_emp_except_waiter.order("name asc") + # @employees = Employee.all_emp_except_waiter.order("name asc") + @employees = Employee.all.order("name asc") @login_form = LoginForm.new() render "layouts/login_dashboard", layout: false end @@ -45,7 +46,7 @@ class HomeController < ApplicationController elsif @employee.role == "manager" session[:session_token] = @employee.token_session redirect_to dashboard_path - elsif @employee.role == "supervisor" + elsif @employee.role == "supervisor" || @employee.role == "waiter" session[:session_token] = @employee.token_session redirect_to origami_root_path elsif @employee.role == "account" @@ -72,7 +73,8 @@ class HomeController < ApplicationController @hourly_sales = Sale.hourly_sales(today).sum(:grand_total) # .group_by_hour(:created_at, :time_zone => 'Asia/Rangoon',format: '%I:%p') # .sum(:grand_total) - @employee_sales = Sale.employee_sales(today).sum(:grand_total) + @employee_sales = Sale.employee_sales(today) + .sum('(CASE WHEN sp.payment_method="cash" THEN (sp.payment_amount - sales.amount_changed) ELSE sp.payment_amount END)') @inventories = StockJournal.inventory_balances(today).sum(:balance) @total_sale = Sale.total_sale(today) @@ -86,10 +88,10 @@ class HomeController < ApplicationController @total_payment_methods.each do |payment| if payment.payment_method == "mpu" || payment.payment_method == "visa" || payment.payment_method == "master" || payment.payment_method == "jcb" pay = Sale.payment_sale('card', today) - @sale_data.push({'card' => pay}) + @sale_data.push({'card' => pay.payment_amount}) else pay = Sale.payment_sale(payment.payment_method, today) - @sale_data.push({payment.payment_method => pay}) + @sale_data.push({payment.payment_method => pay.payment_amount}) end end @summ_sale = Sale.summary_sale_receipt(today) diff --git a/app/controllers/install_controller.rb b/app/controllers/install_controller.rb index cf16adfe..fac74926 100755 --- a/app/controllers/install_controller.rb +++ b/app/controllers/install_controller.rb @@ -1,42 +1,77 @@ class InstallController < BaseController + skip_before_action :verify_authenticity_token + # before_action :check_license + def index end - def create + def activate + flag = "<%= ENV['AES_IV'] %>" + key_base = "<%= ENV['secret_key_base'] %>" + restaurant = params[:restaurant_name] license_key = params[:license_key] - admin_user = params[:admin_user] - admin_password = params[:admin_password] + # admin_user = params[:admin_user] + # admin_password = params[:admin_password] + db_host = params[:db_host] + db_schema = params[:db_schema] + db_user = params[:db_user] + db_password = params[:db_password] + phrase = license_key + + # Check Exists IV + # if flag == "<%= ENV['AES_IV'] %>" + # # Export for Key + # aes = MyAesCrypt.new + # aes_key, aes_iv = aes.export_key(phrase) + # else + # aes_key = ENV["AES_KEY"] + # aes_iv = ENV["AES_IV"] + # end + + @license = License.new(ENV["SX_PROVISION_URL"]) + response = @license.license_activate(restaurant, license_key, db_host, db_schema, db_user, db_password) + if response[:status] + redirect_to root_url, notice: response["message"] + else + redirect_to activate_path, notice: response["message"] + end end - def lookup_domain - if request.subdomain.present? && request.subdomain != "www" - @license = current_license(ENV["SX_PROVISION_URL"], request.subdomain.downcase) - if (!@license.nil?) - # logger.info "Location - " + @license.name - ActiveRecord::Base.establish_connection(website_connection(@license)) - # logger.info "Connecting to - " + @license.subdomain + " - "+ @license.dbhost + "@" + @license.dbschema - else - # reconnect_default_db - logger.info 'License is nil' - # redirect_to root_url(:host => request.domain) + "store_error" - render :json => [{ status: false, message: 'Invalid Access!'}] - end + def check_license + if License.check_license_file + redirect_to root_url end end - def current_license(url, key) - @license = License.new(url, key) + # def lookup_domain + # if request.subdomain.present? && request.subdomain != "www" + # @license = current_license(ENV["SX_PROVISION_URL"], request.subdomain.downcase) + # if (!@license.nil?) + # # logger.info "Location - " + @license.name + # ActiveRecord::Base.establish_connection(website_connection(@license)) + # # logger.info "Connecting to - " + @license.subdomain + " - "+ @license.dbhost + "@" + @license.dbschema + # else + # # reconnect_default_db + # logger.info 'License is nil' + # # redirect_to root_url(:host => request.domain) + "store_error" + # render :json => [{ status: false, message: 'Invalid Access!'}] + # end + # end + # end - ##creating md5 hash - md5_hostname = Digest::MD5.new - md5key = md5_hostname.update(request.host) - if (@license.detail_with_local_cache(key, md5key.to_s) == true) - #if (@license.detail == true) + # def current_license(url, key) + # @license = License.new(url, key) - return @license - else - return nil - end - end + # ##creating md5 hash + # md5_hostname = Digest::MD5.new + # md5key = md5_hostname.update(request.host) + # if (@license.detail_with_local_cache(key, md5key.to_s) == true) + # #if (@license.detail == true) + + # return @license + # else + # return nil + # end + # end end diff --git a/app/controllers/inventory/inventory_controller.rb b/app/controllers/inventory/inventory_controller.rb index 673cf943..1a311552 100755 --- a/app/controllers/inventory/inventory_controller.rb +++ b/app/controllers/inventory/inventory_controller.rb @@ -1,5 +1,5 @@ class Inventory::InventoryController < BaseInventoryController - + load_and_authorize_resource def index @products = InventoryDefinition.all.active.order('created_at desc') end diff --git a/app/controllers/oqs/edit_controller.rb b/app/controllers/oqs/edit_controller.rb index 33ffd8a6..8ec0725e 100755 --- a/app/controllers/oqs/edit_controller.rb +++ b/app/controllers/oqs/edit_controller.rb @@ -2,7 +2,7 @@ class Oqs::EditController < BaseOqsController def index assigned_item_id = params[:id] assigned_item = AssignedOrderItem.find(assigned_item_id) - @order_item = OrderItem.where("order_id='#{ assigned_item.order_id }' AND item_code='#{ assigned_item.item_code }'"); + @order_item = OrderItem.where("order_id='#{ assigned_item.order_id }' AND item_instance_code='#{ assigned_item.instance_code }'"); end def update @@ -17,7 +17,7 @@ class Oqs::EditController < BaseOqsController order_item.save # print - assigned_item = AssignedOrderItem.find_by_item_code(order_item.item_code) + assigned_item = AssignedOrderItem.find_by_instance_code(order_item.item_instance_code) # order queue stations oqs = assigned_item.order_queue_station @@ -25,6 +25,6 @@ class Oqs::EditController < BaseOqsController print_settings=PrintSetting.find_by_unique_code(unique_code) order_queue_printer= Printer::OrderQueuePrinter.new(print_settings) - order_queue_printer.print_order_item(print_settings, oqs,assigned_item.order_id, assigned_item.item_code, print_status=" (Edited)" ) + order_queue_printer.print_order_item(print_settings, oqs, order_item.order_id, order_items_id, print_status=" (Updated)" ) end end diff --git a/app/controllers/oqs/print_controller.rb b/app/controllers/oqs/print_controller.rb index e3001098..f432ad29 100755 --- a/app/controllers/oqs/print_controller.rb +++ b/app/controllers/oqs/print_controller.rb @@ -4,11 +4,12 @@ class Oqs::PrintController < ApplicationController unique_code="OrderItemPdf" assigned_item_id = params[:id] options = params[:options] - assigned_item = AssignedOrderItem.find(assigned_item_id) + assigned_item = AssignedOrderItem.find(assigned_item_id) assigned_items = AssignedOrderItem.where("item_code='" + assigned_item.item_code + "' AND " + "order_id='" + assigned_item.order_id + "'"); # order queue stations oqs = assigned_item.order_queue_station + order_item = OrderItem.where("order_id='#{assigned_item.order_id}' AND item_instance_code='#{assigned_item.instance_code}'").first() # Check Printed print_status = assigned_item.print_status == true ? " (Re-Print)" : "" @@ -16,7 +17,7 @@ class Oqs::PrintController < ApplicationController # print when complete click print_settings = PrintSetting.find_by_unique_code(unique_code) order_queue_printer = Printer::OrderQueuePrinter.new(print_settings) - order_queue_printer.print_order_item(print_settings,oqs, assigned_item.order_id, assigned_item.instance_code, print_status, options ) + order_queue_printer.print_order_item(print_settings,oqs, assigned_item.order_id, order_item.order_items_id, print_status, options ) # update print status for completed same order items assigned_items.each do |ai| diff --git a/app/controllers/origami/addorders_controller.rb b/app/controllers/origami/addorders_controller.rb index d97212f3..d283b06e 100755 --- a/app/controllers/origami/addorders_controller.rb +++ b/app/controllers/origami/addorders_controller.rb @@ -43,6 +43,17 @@ class Origami::AddordersController < ApplicationController#BaseOrigamiController MenuCategory.current_menu end end + + + def get_menu_sub_category () + id = params[:id] + if (id) + #Pull this menu + @sub_menu = MenuCategory.where("menu_category_id = #{id}").active + # puts @menu.menu_items[1].item_attributes.to_json + return @sub_menu + end + end def get_all_product() @product = Product.all @@ -58,9 +69,6 @@ class Origami::AddordersController < ApplicationController#BaseOrigamiController items_arr.push(items) } -puts "sssssssssss" -puts params[:customer_id] -puts params.to_json # begin @order = Order.new @order.source = params[:order_source] diff --git a/app/controllers/origami/check_in_process_controller.rb b/app/controllers/origami/check_in_process_controller.rb index 8e9a1f38..37f58d8f 100644 --- a/app/controllers/origami/check_in_process_controller.rb +++ b/app/controllers/origami/check_in_process_controller.rb @@ -1,20 +1,15 @@ class Origami::CheckInProcessController < BaseOrigamiController def check_in_process - dining_charge = DiningCharge.select('charge_type','charge_block') - .where('dining_facility_id = ?',params[:dining_id]) - .first() - + lookup_checkout_time = Lookup.collection_of("checkout_time") checkout_at = Time.now.utc - if !dining_charge.nil? - hr = (dining_charge.charge_block.utc.strftime("%H").to_i).to_int - min = (dining_charge.charge_block.utc.strftime("%M").to_i).to_int - # if dining_charge.charge_type == 'hr' - checkout_at = checkout_at + hr.hour + min.minutes - # else - - # end + if !lookup_checkout_time.nil? + if lookup_checkout_time[0][0] == 'hr' + checkout_at = checkout_at + (lookup_checkout_time[0][1]).to_i.hour + else + checkout_at = checkout_at + (lookup_checkout_time[0][1]).to_i.minutes + end end @dining_facility = DiningFacility.find(params[:dining_id]) @dining_facility.status = "occupied" @@ -25,9 +20,9 @@ class Origami::CheckInProcessController < BaseOrigamiController else type = "RoomBooking" end - + @booking = Booking.create({:dining_facility_id => params[:dining_id],:type => type, - :checkin_at => Time.now.utc,:checkout_at =>checkout_at, :booking_status => "assign" }) + :checkin_by=>current_login_employee.name,:checkin_at => Time.now.utc,:checkout_at =>checkout_at, :booking_status => "assign", :reserved_at => checkout_at, :reserved_by => current_login_employee.name }) @booking.save! respond = {:status => 'ok'} diff --git a/app/controllers/origami/credit_payments_controller.rb b/app/controllers/origami/credit_payments_controller.rb index a4978a6f..404b1506 100755 --- a/app/controllers/origami/credit_payments_controller.rb +++ b/app/controllers/origami/credit_payments_controller.rb @@ -4,11 +4,20 @@ class Origami::CreditPaymentsController < BaseOrigamiController # limit visa_amount sale_data = Sale.find_by_sale_id(@sale_id) - total = sale_data.grand_total + total = sale_data.grand_total @creditcount = 0 others = 0 + + @shop = Shop::ShopDetail + if @shop.is_rounding_adj + new_total = Sale.get_rounding_adjustment(sale_data.grand_total) + else + new_total = sale_data.grand_total + end + @rounding_adj = new_total-sale_data.grand_total + sale_data.sale_payments.each do |sale_payment| - if sale_payment.payment_method == "visa" + if sale_payment.payment_method == "creditnote" @creditcount = @creditcount + sale_payment.payment_amount else others = others + sale_payment.payment_amount @@ -21,6 +30,16 @@ class Origami::CreditPaymentsController < BaseOrigamiController cash = params[:amount] sale_id = params[:sale_id] if(Sale.exists?(sale_id)) + saleObj = Sale.find(sale_id) + shop_details = Shop::ShopDetail + + # rounding adjustment + if shop_details.is_rounding_adj + new_total = Sale.get_rounding_adjustment(saleObj.grand_total) + rounding_adj = new_total-saleObj.grand_total + saleObj.update_attributes(grand_total: new_total,old_grand_total: saleObj.grand_total,rounding_adjustment:rounding_adj) + end + saleObj = Sale.find(sale_id) sale_payment = SalePayment.new @status, @sale = sale_payment.process_payment(saleObj, @user, cash, "creditnote") diff --git a/app/controllers/origami/discounts_controller.rb b/app/controllers/origami/discounts_controller.rb index cf723fd6..1166a705 100755 --- a/app/controllers/origami/discounts_controller.rb +++ b/app/controllers/origami/discounts_controller.rb @@ -29,8 +29,6 @@ class Origami::DiscountsController < BaseOrigamiController # sale.grand_total = (sub_total.to_f - overall_discount.to_f) + sale.total_tax; # sale.save if discount_items.length > 0 - puts discount_items.to_json - puts "dddddddddddd" #save sale item for discount discount_items.each do |di| @@ -159,11 +157,15 @@ class Origami::DiscountsController < BaseOrigamiController is_card = params[:is_card] sub_total = params[:sub_total] sale = Sale.find(sale_id) - + if is_card == 'true' + is_card = true + else is_card.to_s == 'false' + is_card = false + end # Check for Card Payment - is_card_payment = SaleItem.get_sale_payments_by_card(sale.sale_payments) + is_card_payment = SalePayment.get_sale_payments_by_card(sale.sale_payments) - if is_card_payment != true + # if is_card != "true" account_types = Account.where("discount=?",true) table_id = sale.bookings[0].dining_facility_id table_type = DiningFacility.find(table_id).type @@ -180,8 +182,7 @@ class Origami::DiscountsController < BaseOrigamiController end end end - - generic_customer_id = sale.customer.membership_id + generic_customer_id = sale.customer.membership_id receipt_no = sale.receipt_no membership = MembershipSetting.find_by_membership_type("paypar_url") memberaction = MembershipAction.find_by_membership_type("member_discount") @@ -189,12 +190,13 @@ class Origami::DiscountsController < BaseOrigamiController campaign_type_id = memberaction.additional_parameter["campaign_type_id"] auth_token = memberaction.auth_token.to_s url = membership.gateway_url.to_s + memberaction.gateway_url.to_s + account_no = sale.customer.paypar_account_no rescue nil # Check for items for Paypar Cloud if acc_prices.length > 0 begin response = HTTParty.post(url, - :body => { account_no: nil, + :body => { account_no: account_no, generic_customer_id:generic_customer_id , campaign_type_id: campaign_type_id, receipt_no: receipt_no, @@ -221,8 +223,8 @@ class Origami::DiscountsController < BaseOrigamiController else response = {"status": false, "message": "You have no selected discount item" } end - puts "discountttttttttttt" - puts response.to_json + Rails.logger.debug "-------------- Member Discount Osaka ---------" + Rails.logger.debug response.to_json # Re-calc All Amount in Sale if response["status"] == true discount_amount = response["discount_earned"] @@ -239,7 +241,7 @@ class Origami::DiscountsController < BaseOrigamiController render :json => result.to_json - end #end Is Card Payment + # end #end Is Card Payment end #discount for selected order diff --git a/app/controllers/origami/home_controller.rb b/app/controllers/origami/home_controller.rb index 12c7fb76..22ca34c2 100755 --- a/app/controllers/origami/home_controller.rb +++ b/app/controllers/origami/home_controller.rb @@ -6,7 +6,7 @@ class Origami::HomeController < BaseOrigamiController @rooms = Room.all.active.order('status desc') @complete = Sale.where("DATE_FORMAT(created_at,'%Y-%m-%d') = ? and sale_status != 'new'",DateTime.now.strftime('%Y-%m-%d')) @orders = Order.all.order('date desc') - @shop = Shop.find_by_id(1) + @shop = Shop::ShopDetail # @shift = ShiftSale.current_open_shift(current_user.id) end @@ -22,6 +22,10 @@ class Origami::HomeController < BaseOrigamiController @status_sale = "" @sale_array = Array.new + @shop = Shop::ShopDetail + @membership = MembershipSetting::MembershipSetting + @payment_methods = PaymentMethodSetting.all + @dining.bookings.active.each do |booking| if booking.sale_id.nil? && booking.booking_status != 'moved' @order_items = Array.new diff --git a/app/controllers/origami/in_duties_controller.rb b/app/controllers/origami/in_duties_controller.rb index 2c30bbd9..5607939a 100755 --- a/app/controllers/origami/in_duties_controller.rb +++ b/app/controllers/origami/in_duties_controller.rb @@ -1,6 +1,5 @@ class Origami::InDutiesController < BaseOrigamiController before_action :set_in_duty, only: %i[show edit update edit_in_duty update_for_in_duty destroy destroy_in_duty] - # GET /in_duties # GET /in_duties.json def index diff --git a/app/controllers/origami/jcb_controller.rb b/app/controllers/origami/jcb_controller.rb index a8b77861..a3b93efd 100755 --- a/app/controllers/origami/jcb_controller.rb +++ b/app/controllers/origami/jcb_controller.rb @@ -8,6 +8,15 @@ class Origami::JcbController < BaseOrigamiController total = sale_data.grand_total @jcbcount = 0 others = 0 + + @shop = Shop::ShopDetail + if @shop.is_rounding_adj + new_total = Sale.get_rounding_adjustment(sale_data.grand_total) + else + new_total = sale_data.grand_total + end + @rounding_adj = new_total-sale_data.grand_total + sale_data.sale_payments.each do |sale_payment| if sale_payment.payment_method == "jcb" @jcbcount = @jcbcount + sale_payment.payment_amount @@ -26,6 +35,16 @@ class Origami::JcbController < BaseOrigamiController cash = params[:amount] sale_id = params[:sale_id] if(Sale.exists?(sale_id)) + saleObj = Sale.find(sale_id) + shop_details = Shop::ShopDetail + + # rounding adjustment + if shop_details.is_rounding_adj + new_total = Sale.get_rounding_adjustment(saleObj.grand_total) + rounding_adj = new_total-saleObj.grand_total + saleObj.update_attributes(grand_total: new_total,old_grand_total: saleObj.grand_total,rounding_adjustment:rounding_adj) + end + saleObj = Sale.find(sale_id) sale_payment = SalePayment.new @status, @sale = sale_payment.process_payment(saleObj, @user, cash, "jcb") diff --git a/app/controllers/origami/master_controller.rb b/app/controllers/origami/master_controller.rb index ba97cad9..8eb2e02b 100755 --- a/app/controllers/origami/master_controller.rb +++ b/app/controllers/origami/master_controller.rb @@ -8,6 +8,15 @@ class Origami::MasterController < BaseOrigamiController total = sale_data.grand_total @mastercount = 0 others = 0 + + @shop = Shop::ShopDetail + if @shop.is_rounding_adj + new_total = Sale.get_rounding_adjustment(sale_data.grand_total) + else + new_total = sale_data.grand_total + end + @rounding_adj = new_total-sale_data.grand_total + sale_data.sale_payments.each do |sale_payment| if sale_payment.payment_method == "master" @mastercount = @mastercount + sale_payment.payment_amount @@ -25,6 +34,16 @@ class Origami::MasterController < BaseOrigamiController cash = params[:amount] sale_id = params[:sale_id] if(Sale.exists?(sale_id)) + saleObj = Sale.find(sale_id) + shop_details = Shop::ShopDetail + + # rounding adjustment + if shop_details.is_rounding_adj + new_total = Sale.get_rounding_adjustment(saleObj.grand_total) + rounding_adj = new_total-saleObj.grand_total + saleObj.update_attributes(grand_total: new_total,old_grand_total: saleObj.grand_total,rounding_adjustment:rounding_adj) + end + saleObj = Sale.find(sale_id) sale_payment = SalePayment.new @status, @sale = sale_payment.process_payment(saleObj, @user, cash, "master") diff --git a/app/controllers/origami/mpu_controller.rb b/app/controllers/origami/mpu_controller.rb index 8e62ecda..6bd0778f 100755 --- a/app/controllers/origami/mpu_controller.rb +++ b/app/controllers/origami/mpu_controller.rb @@ -8,6 +8,14 @@ class Origami::MpuController < BaseOrigamiController @mpucount = 0 others = 0 + @shop = Shop::ShopDetail + if @shop.is_rounding_adj + new_total = Sale.get_rounding_adjustment(sale_data.grand_total) + else + new_total = sale_data.grand_total + end + @rounding_adj = new_total-sale_data.grand_total + sale_data.sale_payments.each do |sale_payment| if sale_payment.payment_method == "mpu" @mpucount = @mpucount + sale_payment.payment_amount @@ -26,6 +34,16 @@ class Origami::MpuController < BaseOrigamiController cash = params[:amount] sale_id = params[:sale_id] if(Sale.exists?(sale_id)) + saleObj = Sale.find(sale_id) + shop_details = Shop::ShopDetail + + # rounding adjustment + if shop_details.is_rounding_adj + new_total = Sale.get_rounding_adjustment(saleObj.grand_total) + rounding_adj = new_total-saleObj.grand_total + saleObj.update_attributes(grand_total: new_total,old_grand_total: saleObj.grand_total,rounding_adjustment:rounding_adj) + end + saleObj = Sale.find(sale_id) sale_payment = SalePayment.new @status, @sale = sale_payment.process_payment(saleObj, @user, cash, "mpu") diff --git a/app/controllers/origami/other_charges_controller.rb b/app/controllers/origami/other_charges_controller.rb index ae3d1073..51a1f7db 100755 --- a/app/controllers/origami/other_charges_controller.rb +++ b/app/controllers/origami/other_charges_controller.rb @@ -37,7 +37,7 @@ class Origami::OtherChargesController < BaseOrigamiController sale_item.qty = 1 sale_item.unit_price = di["price"] sale_item.taxable_price = di["price"] * 1 - sale_item.is_taxable = 1 + sale_item.is_taxable = di["is_taxable"] sale_item.account_id = 0 sale_item.price = di["price"] * 1 diff --git a/app/controllers/origami/payments_controller.rb b/app/controllers/origami/payments_controller.rb index fdd55f06..02e0c4ef 100755 --- a/app/controllers/origami/payments_controller.rb +++ b/app/controllers/origami/payments_controller.rb @@ -24,13 +24,30 @@ class Origami::PaymentsController < BaseOrigamiController # Print for First Bill to Customer unique_code = "ReceiptBillPdf" #shop detail - shop_details = Shop.find(1) + shop_details = Shop::ShopDetail # customer= Customer.where('customer_id=' +.customer_id) - customer= Customer.find(sale_data.customer_id) + customer = Customer.find(sale_data.customer_id) + + # rounding adjustment + if shop_details.is_rounding_adj + a = sale_data.grand_total % 25 # Modulus + b = sale_data.grand_total / 25 # Division + #not calculate rounding if modulus is 0 and division is even + #calculate rounding if modulus is zero or not zero and division are not even + if (a != 0.0 && b%2 != 0.0) || (a==0.0 && b%2 !=0) + new_total = Sale.get_rounding_adjustment(sale_data.grand_total) + rounding_adj = new_total-sale_data.grand_total + sale_data.update_attributes(grand_total: new_total,old_grand_total: sale_data.grand_total,rounding_adjustment:rounding_adj) + end + end + #end rounding adjustment + # get member information rebate = MembershipSetting.find_by_rebate(1) if customer.membership_id != nil && rebate member_info = Customer.get_member_account(customer) + # current_balance = SaleAudit.paymal_search(sale_id) + current_balance = 0 end # get printer info print_settings=PrintSetting.find_by_unique_code(unique_code) @@ -44,7 +61,7 @@ class Origami::PaymentsController < BaseOrigamiController printer = Printer::ReceiptPrinter.new(print_settings) - printer.print_receipt_bill(print_settings,cashier_terminal,sale_items,sale_data,customer.name, item_price_by_accounts, discount_price_by_accounts, member_info, shop_details, "Frt") + printer.print_receipt_bill(print_settings,cashier_terminal,sale_items,sale_data,customer.name, item_price_by_accounts, discount_price_by_accounts, member_info, shop_details, "Frt",current_balance) end def create @@ -54,6 +71,22 @@ class Origami::PaymentsController < BaseOrigamiController if(Sale.exists?(sale_id)) saleObj = Sale.find(sale_id) + shop_details = Shop::ShopDetail + + # rounding adjustment + if shop_details.is_rounding_adj + a = saleObj.grand_total % 25 # Modulus + b = saleObj.grand_total / 25 # Division + #not calculate rounding if modulus is 0 and division is even + #calculate rounding if modulus is zero or not zero and division are not even + if (a != 0.0 && b%2 != 0.0) || (a==0.0 && b%2 !=0) + new_total = Sale.get_rounding_adjustment(saleObj.grand_total) + rounding_adj = new_total-saleObj.grand_total + saleObj.update_attributes(grand_total: new_total,old_grand_total: saleObj.grand_total,rounding_adjustment:rounding_adj) + end + end + #end rounding adjustment + sale_payment = SalePayment.new sale_payment.process_payment(saleObj, @user, cash, "cash") @@ -75,16 +108,17 @@ class Origami::PaymentsController < BaseOrigamiController # For Print unique_code = "ReceiptBillPdf" customer= Customer.find(saleObj.customer_id) - - #shop detail - shop_details = Shop.find(1) + # get member information rebate = MembershipSetting.find_by_rebate(1) - if customer.membership_id != nil && rebate + credit_data = SalePayment.find_by_sale_id_and_payment_method(sale_id,'creditnote') + + if customer.membership_id != nil && rebate && credit_data.nil? member_info = Customer.get_member_account(customer) rebate_amount = Customer.get_membership_transactions(customer,saleObj.receipt_no) + current_balance = SaleAudit.paymal_search(sale_id) end - + # get printer info print_settings=PrintSetting.find_by_unique_code(unique_code) # Calculate Food and Beverage Total @@ -92,7 +126,7 @@ class Origami::PaymentsController < BaseOrigamiController discount_price_by_accounts = SaleItem.get_discount_price_by_accounts(saleObj.sale_items) printer = Printer::ReceiptPrinter.new(print_settings) - printer.print_receipt_bill(print_settings,cashier_terminal,saleObj.sale_items,saleObj,customer.name, item_price_by_accounts, discount_price_by_accounts, member_info,rebate_amount,shop_details, "Paid") + printer.print_receipt_bill(print_settings,cashier_terminal,saleObj.sale_items,saleObj,customer.name, item_price_by_accounts, discount_price_by_accounts, member_info,rebate_amount,shop_details, "Paid",current_balance) end end @@ -114,6 +148,14 @@ class Origami::PaymentsController < BaseOrigamiController @accountable_type = '' @table_no = '' + @shop = Shop::ShopDetail + if @shop.is_rounding_adj + new_total = Sale.get_rounding_adjustment(@sale_data.grand_total) + else + new_total = @sale_data.grand_total + end + @rounding_adj = new_total-@sale_data.grand_total + #get customer amount @customer = Customer.find(@sale_data.customer_id) accounts = @customer.tax_profiles @@ -127,7 +169,6 @@ class Origami::PaymentsController < BaseOrigamiController # get member information if @customer.membership_id != nil && rebate response = Customer.get_member_account(@customer) - puts response.to_json if response["status"]==true response["account_data"].each do |res| if res["accountable_type"] == "RebateAccount" || res["accountable_type"] == "RebatebonusAccount" @@ -191,12 +232,13 @@ class Origami::PaymentsController < BaseOrigamiController customer= Customer.find(saleObj.customer_id) #shop detail - shop_details = Shop.find(1) + shop_details = Shop::ShopDetail # get member information rebate = MembershipSetting.find_by_rebate(1) if customer.membership_id != nil && rebate member_info = Customer.get_member_account(customer) rebate_amount = Customer.get_membership_transactions(customer,saleObj.receipt_no) + current_balance = SaleAudit.paymal_search(sale_id) end # get printer info print_settings=PrintSetting.find_by_unique_code(unique_code) @@ -206,7 +248,7 @@ class Origami::PaymentsController < BaseOrigamiController discount_price_by_accounts = SaleItem.get_discount_price_by_accounts(saleObj.sale_items) printer = Printer::ReceiptPrinter.new(print_settings) - printer.print_receipt_bill(print_settings,cashier_terminal,saleObj.sale_items,saleObj,customer.name, item_price_by_accounts, discount_price_by_accounts, member_info,rebate_amount,shop_details, "Re-print") + printer.print_receipt_bill(print_settings,cashier_terminal,saleObj.sale_items,saleObj,customer.name, item_price_by_accounts, discount_price_by_accounts, member_info,rebate_amount,shop_details, "Re-print",current_balance) end def foc @@ -215,6 +257,7 @@ class Origami::PaymentsController < BaseOrigamiController sub_total = params[:sub_total] member_info = nil rebate_amount = nil + current_balance = nil if(Sale.exists?(sale_id)) saleObj = Sale.find(sale_id) @@ -240,7 +283,7 @@ class Origami::PaymentsController < BaseOrigamiController customer= Customer.find(saleObj.customer_id) #shop detail - shop_details = Shop.find(1) + shop_details = Shop::ShopDetail # get printer info print_settings=PrintSetting.find_by_unique_code(unique_code) @@ -249,7 +292,7 @@ class Origami::PaymentsController < BaseOrigamiController discount_price_by_accounts = SaleItem.get_discount_price_by_accounts(saleObj.sale_items) printer = Printer::ReceiptPrinter.new(print_settings) - printer.print_receipt_bill(print_settings,cashier_terminal,saleObj.sale_items,saleObj,customer.name, item_price_by_accounts, discount_price_by_accounts, member_info,rebate_amount,shop_details, "FOC") + printer.print_receipt_bill(print_settings,cashier_terminal,saleObj.sale_items,saleObj,customer.name, item_price_by_accounts, discount_price_by_accounts, member_info,rebate_amount,shop_details, "FOC",nil) end end @@ -259,14 +302,15 @@ class Origami::PaymentsController < BaseOrigamiController @shop = Shop.find_by_id(1) if @shop.is_rounding_adj - new_total = Sale.get_rounding_adjustment(saleObj.grand_total) - else - new_total = saleObj.grand_total + a = saleObj.grand_total % 25 # Modulus + b = saleObj.grand_total / 25 # Division + #not calculate rounding if modulus is 0 and division is even + #calculate rounding if modulus is zero or not zero and division are not even + if (a != 0.0 && b%2 != 0.0) || (a==0.0 && b%2 !=0) + new_total = Sale.get_rounding_adjustment(saleObj.grand_total) + rounding_adj = new_total-saleObj.grand_total + saleObj.update_attributes(grand_total: new_total,old_grand_total: saleObj.grand_total,rounding_adjustment:rounding_adj) + end end - - rounding_adj = new_total-saleObj.grand_total - - saleObj.update_attributes(grand_total: new_total,old_grand_total: saleObj.grand_total,rounding_adjustment:rounding_adj) - end -end +end \ No newline at end of file diff --git a/app/controllers/origami/paypar_payments_controller.rb b/app/controllers/origami/paypar_payments_controller.rb index 0c3ea11f..5a15aa8c 100755 --- a/app/controllers/origami/paypar_payments_controller.rb +++ b/app/controllers/origami/paypar_payments_controller.rb @@ -6,6 +6,15 @@ class Origami::PayparPaymentsController < BaseOrigamiController payment_method = "paypar" if(Sale.exists?(sale_id)) saleObj = Sale.find(sale_id) + shop_details = Shop::ShopDetail + + # rounding adjustment + if shop_details.is_rounding_adj + new_total = Sale.get_rounding_adjustment(saleObj.grand_total) + rounding_adj = new_total-saleObj.grand_total + saleObj.update_attributes(grand_total: new_total,old_grand_total: saleObj.grand_total,rounding_adjustment:rounding_adj) + end + sale_payment = SalePayment.new status,msg =sale_payment.process_payment(saleObj, @user, redeem_amount,payment_method) if status == true diff --git a/app/controllers/origami/redeem_payments_controller.rb b/app/controllers/origami/redeem_payments_controller.rb index 802ba51b..b0f40d34 100755 --- a/app/controllers/origami/redeem_payments_controller.rb +++ b/app/controllers/origami/redeem_payments_controller.rb @@ -5,76 +5,65 @@ class Origami::RedeemPaymentsController < BaseOrigamiController @membership_rebate_balance=0 sale_data = Sale.find_by_sale_id(@sale_id) - # limit redeem_amount - # rebate_prices = SaleItem.calculate_food_beverage(sale_data.sale_items) - # nonrebate_prices = sale_data.total_amount - rebate_prices - # @payparcount = 0 - # others = 0 - # sale_data.sale_payments.each do |sale_payment| - # if sale_payment.payment_method == "paypar" - # @payparcount = @payparcount + sale_payment.payment_amount - # else - # others = others + sale_payment.payment_amount - # end - # end - # non_rebate_exceed = others - (nonrebate_prices + sale_data.total_tax) - # if non_rebate_exceed < 0 - # @redeem_prices = rebate_prices - @payparcount - # else - # @redeem_prices = rebate_prices - @payparcount -non_rebate_exceed - # end - - @payparcount = 0 - others = 0 - sale_data.sale_payments.each do |sale_payment| - if sale_payment.payment_method == "paypar" - @payparcount = @payparcount + sale_payment.payment_amount + @shop = Shop::ShopDetail + if @shop.is_rounding_adj + new_total = Sale.get_rounding_adjustment(sale_data.grand_total) else - others = others + sale_payment.payment_amount + new_total = sale_data.grand_total end - end - @redeem_prices = sale_data.grand_total - @payparcount -others + @rounding_adj = new_total-sale_data.grand_total + + @payparcount = 0 + others = 0 + sale_data.sale_payments.each do |sale_payment| + if sale_payment.payment_method == "paypar" + @payparcount = @payparcount + sale_payment.payment_amount + else + others = others + sale_payment.payment_amount + end + end + @redeem_prices = sale_data.grand_total - @payparcount -others - if sale_data - if sale_data.customer_id - customer_data= Customer.find_by_customer_id(sale_data.customer_id) - if customer_data - @membership_id = customer_data.membership_id - if !@membership_id.nil? - membership_setting = MembershipSetting.find_by_membership_type("paypar_url") - if membership_setting.gateway_url - member_actions =MembershipAction.find_by_membership_type("get_account_balance") - if member_actions.gateway_url - @campaign_type_id = member_actions.additional_parameter["campaign_type_id"] - url = membership_setting.gateway_url.to_s + member_actions.gateway_url.to_s - merchant_uid= member_actions.merchant_account_id - auth_token = member_actions.auth_token.to_s - membership_data = SalePayment.get_paypar_account(url,membership_setting.auth_token,@membership_id,@campaign_type_id,merchant_uid,auth_token) - if membership_data["status"]==true - @membership_rebate_balance=membership_data["balance"] - @out = true, @membership_rebate_balance,@membership_id - end - else - @out =false,0 - end - else - @out = false,0 - end + if sale_data + if sale_data.customer_id + customer_data= Customer.find_by_customer_id(sale_data.customer_id) + if customer_data + @membership_id = customer_data.membership_id + if !@membership_id.nil? + membership_setting = MembershipSetting.find_by_membership_type("paypar_url") + if membership_setting.gateway_url + member_actions =MembershipAction.find_by_membership_type("get_account_balance") + if member_actions.gateway_url + @campaign_type_id = member_actions.additional_parameter["campaign_type_id"] + url = membership_setting.gateway_url.to_s + member_actions.gateway_url.to_s + merchant_uid= member_actions.merchant_account_id + auth_token = member_actions.auth_token.to_s + membership_data = SalePayment.get_paypar_account(url,membership_setting.auth_token,@membership_id,@campaign_type_id,merchant_uid,auth_token) + if membership_data["status"]==true + @membership_rebate_balance=membership_data["balance"] + @out = true, @membership_rebate_balance,@membership_id + end + else + @out =false,0 + end + else + @out = false,0 + end - else - @out = false, 0 - end - else - @out = false, 0 - end - else - @out = false, 0 - end - else - @out = false, 0 - end - @out = false, 0 - end + else + @out = false, 0 + end + else + @out = false, 0 + end + else + @out = false, 0 + end + else + @out = false, 0 + end + @out = false, 0 + end end diff --git a/app/controllers/origami/rooms_controller.rb b/app/controllers/origami/rooms_controller.rb index 6c0b98c8..5e5b42cb 100755 --- a/app/controllers/origami/rooms_controller.rb +++ b/app/controllers/origami/rooms_controller.rb @@ -19,6 +19,10 @@ class Origami::RoomsController < BaseOrigamiController @status_sale = "" @sale_array = Array.new + @shop = Shop::ShopDetail + @membership = MembershipSetting::MembershipSetting + @payment_methods = PaymentMethodSetting.all + @room.bookings.active.each do |booking| if booking.sale_id.nil? && booking.booking_status != 'moved' @order_items = Array.new diff --git a/app/controllers/origami/sale_edit_controller.rb b/app/controllers/origami/sale_edit_controller.rb index a4dcb31d..c00c35f0 100755 --- a/app/controllers/origami/sale_edit_controller.rb +++ b/app/controllers/origami/sale_edit_controller.rb @@ -43,7 +43,7 @@ class Origami::SaleEditController < BaseOrigamiController @newsaleitem = saleitemObj.dup @newsaleitem.save @newsaleitem.qty = saleitemObj.qty * -1 - @newsaleitem.unit_price = saleitemObj.unit_price * -1 + @newsaleitem.unit_price = saleitemObj.unit_price * 1 @newsaleitem.taxable_price = saleitemObj.taxable_price * -1 @newsaleitem.price = saleitemObj.price * -1 @newsaleitem.product_name = saleitemObj.product_name + ' (FOC)' diff --git a/app/controllers/origami/sales_controller.rb b/app/controllers/origami/sales_controller.rb index 3c895b91..e5350706 100755 --- a/app/controllers/origami/sales_controller.rb +++ b/app/controllers/origami/sales_controller.rb @@ -5,6 +5,10 @@ class Origami::SalesController < BaseOrigamiController @complete = Sale.where("DATE_FORMAT(created_at,'%Y-%m-%d') = ? and sale_status != 'new'",DateTime.now.strftime('%Y-%m-%d')) @orders = Order.all.order('date desc') @sale = Sale.find(params[:sale_id]) + @order = SaleOrder.find_by_sale_id(@sale.sale_id).order_id + @booking = BookingOrder.find_by_order_id(@order).booking_id + @table_id = Booking.find(@booking).dining_facility_id + @dining = DiningFacility.find(@table_id) end def add_to_existing_invoice diff --git a/app/controllers/origami/visa_controller.rb b/app/controllers/origami/visa_controller.rb index 4f750fb5..3e2e56a3 100755 --- a/app/controllers/origami/visa_controller.rb +++ b/app/controllers/origami/visa_controller.rb @@ -7,6 +7,15 @@ class Origami::VisaController < BaseOrigamiController total = sale_data.grand_total @visacount = 0 others = 0 + + @shop = Shop::ShopDetail + if @shop.is_rounding_adj + new_total = Sale.get_rounding_adjustment(sale_data.grand_total) + else + new_total = sale_data.grand_total + end + @rounding_adj = new_total-sale_data.grand_total + sale_data.sale_payments.each do |sale_payment| if sale_payment.payment_method == "visa" @visacount = @visacount + sale_payment.payment_amount @@ -25,6 +34,17 @@ class Origami::VisaController < BaseOrigamiController sale_id = params[:sale_id] if(Sale.exists?(sale_id)) saleObj = Sale.find(sale_id) + shop_details = Shop::ShopDetail + + # rounding adjustment + if shop_details.is_rounding_adj + new_total = Sale.get_rounding_adjustment(saleObj.grand_total) + rounding_adj = new_total-saleObj.grand_total + saleObj.update_attributes(grand_total: new_total,old_grand_total: saleObj.grand_total,rounding_adjustment:rounding_adj) + end + + saleObj = Sale.find(sale_id) + #end rounding adjustment sale_payment = SalePayment.new @status, @sale = sale_payment.process_payment(saleObj, @user, cash, "visa") end diff --git a/app/controllers/origami/void_controller.rb b/app/controllers/origami/void_controller.rb index 80594a26..242a1c2e 100755 --- a/app/controllers/origami/void_controller.rb +++ b/app/controllers/origami/void_controller.rb @@ -8,12 +8,19 @@ class Origami::VoidController < BaseOrigamiController sale = Sale.find_by_sale_id(sale_id) # update count for shift sale - # if(sale.sale_status == "completed") + if(sale.sale_status == "completed") if sale.shift_sale_id != nil shift = ShiftSale.find(sale.shift_sale_id) shift.calculate(sale_id, "void") end - # end + else + # void before sale payment complete + if sale.shift_sale_id != nil + shift = ShiftSale.find(sale.shift_sale_id) + shift.total_void = shift.total_void + sale.grand_total + shift.save + end + end sale.payment_status = 'void' sale.sale_status = 'void' @@ -73,6 +80,7 @@ class Origami::VoidController < BaseOrigamiController if customer.membership_id != nil && rebate member_info = Customer.get_member_account(customer) rebate_amount = Customer.get_membership_transactions(customer,saleObj.receipt_no) + current_balance = SaleAudit.paymal_search(sale_id) end # get printer info print_settings=PrintSetting.find_by_unique_code(unique_code) @@ -81,7 +89,7 @@ class Origami::VoidController < BaseOrigamiController discount_price_by_accounts = SaleItem.get_discount_price_by_accounts(sale.sale_items) printer = Printer::ReceiptPrinter.new(print_settings) - printer.print_receipt_bill(print_settings,cashier_terminal,sale.sale_items,sale,customer.name, item_price_by_accounts, discount_price_by_accounts, member_info,rebate_amount,shop_details, "VOID") + printer.print_receipt_bill(print_settings,cashier_terminal,sale.sale_items,sale,customer.name, item_price_by_accounts, discount_price_by_accounts, member_info,rebate_amount,shop_details, "VOID",current_balance) #end print @@ -93,6 +101,5 @@ class Origami::VoidController < BaseOrigamiController end end end - end - + end end \ No newline at end of file diff --git a/app/controllers/origami/voucher_controller.rb b/app/controllers/origami/voucher_controller.rb index 421c31a0..c4b3c840 100755 --- a/app/controllers/origami/voucher_controller.rb +++ b/app/controllers/origami/voucher_controller.rb @@ -7,6 +7,15 @@ class Origami::VoucherController < BaseOrigamiController total = sale_data.grand_total @vouchercount = 0 others = 0 + + @shop = Shop::ShopDetail + if @shop.is_rounding_adj + new_total = Sale.get_rounding_adjustment(sale_data.grand_total) + else + new_total = sale_data.grand_total + end + @rounding_adj = new_total-sale_data.grand_total + sale_data.sale_payments.each do |sale_payment| if sale_payment.payment_method == "voucher" @vouchercount = @vouchercount + sale_payment.payment_amount diff --git a/app/controllers/reports/payment_method_controller.rb b/app/controllers/reports/payment_method_controller.rb index 23c256d3..bbff8900 100644 --- a/app/controllers/reports/payment_method_controller.rb +++ b/app/controllers/reports/payment_method_controller.rb @@ -21,8 +21,6 @@ class Reports::PaymentMethodController < BaseReportController end @payment_type = params[:payment_type] @sale_data,@pyament_method = Sale.get_payment_method_by_shift(@shift_sale_range,@shift,from,to,@payment_type) - puts @pyament_method.to_json - puts "sssssssssssss" @from = from @to = to diff --git a/app/controllers/reports/receipt_no_controller.rb b/app/controllers/reports/receipt_no_controller.rb index 3ca19e9d..2bd5e813 100755 --- a/app/controllers/reports/receipt_no_controller.rb +++ b/app/controllers/reports/receipt_no_controller.rb @@ -20,7 +20,7 @@ authorize_resource :class => false payment_type = params[:payment_type] @sale_data = Sale.get_shift_sales_by_receipt_no(@shift_sale_range,@shift,from,to,payment_type) @sale_taxes = Sale.get_separate_tax(@shift_sale_range,@shift,from,to,payment_type) - + @tax_profiles = TaxProfile.order('order_by asc') @from = from @to = to diff --git a/app/controllers/reports/saleitem_controller.rb b/app/controllers/reports/saleitem_controller.rb index bd933f83..7e7469f9 100755 --- a/app/controllers/reports/saleitem_controller.rb +++ b/app/controllers/reports/saleitem_controller.rb @@ -15,9 +15,10 @@ class Reports::SaleitemController < BaseReportController shift = ShiftSale.where('shift_started_at = ? and shift_closed_at = ? ',shift_sale.shift_started_at, shift_sale.shift_closed_at) end end - @sale_data, @discount_data , @cash_data , @card_data , @credit_data , @foc_data , @grand_total , @change_amount = Sale.get_by_shift_items(shift_sale_range,shift, from, to, Sale::SALE_STATUS_COMPLETED) - puts @sale_data.to_json - puts "SSSSSSSSSSS" + @sale_data, @other_charges,@discount_data , @cash_data , @card_data , @credit_data , @foc_data , @grand_total , @change_amount = Sale.get_by_shift_items(shift_sale_range,shift, from, to, Sale::SALE_STATUS_COMPLETED) + + @sale_taxes = Sale.get_separate_tax(shift_sale_range,shift,from,to,nil) + @account_cate_count = Hash.new {|hash, key| hash[key] = 0} diff --git a/app/controllers/settings/menu_item_instances_controller.rb b/app/controllers/settings/menu_item_instances_controller.rb index 336bf7c8..596887c3 100755 --- a/app/controllers/settings/menu_item_instances_controller.rb +++ b/app/controllers/settings/menu_item_instances_controller.rb @@ -26,8 +26,6 @@ class Settings::MenuItemInstancesController < ApplicationController def get_instance @id = MenuItemInstance.find(params[:id]) - puts "iddddddddd" - puts @id.to_json end # GET /settings/menu_item_instances/1/edit @@ -67,12 +65,13 @@ class Settings::MenuItemInstancesController < ApplicationController respond_to do |format| if @settings_menu_item_instances.save - @settings_menu_item_instances.item_attributes = params[:menu_item_instance][:item_attributes].reject(&:blank?) + @settings_menu_item_instances.item_attributes = params[:menu_item_instance][:item_attributes].split(" ") @settings_menu_item_instances.save format.html { redirect_to settings_menu_category_simple_menu_item_path(category,catID), notice: 'Menu item instance was successfully created.' } format.json { render :show, status: :created, location: @settings_menu_item_instances } else - format.html { render :new } + flash[:instance_code_error] = @settings_menu_item_instances.errors + format.html { redirect_to new_settings_simple_menu_item_menu_item_instance_path } format.json { render json: @settings_menu_item_instances.errors, status: :unprocessable_entity } end end @@ -105,9 +104,9 @@ class Settings::MenuItemInstancesController < ApplicationController end respond_to do |format| - if @settings_menu_item_instances.update(settings_menu_item_instance_params) - @settings_menu_item_instances.item_attributes = params[:menu_item_instance][:item_attributes].reject(&:blank?) + #@settings_menu_item_instances.item_attributes = params[:menu_item_instance][:item_attributes].reject(&:blank?) + @settings_menu_item_instances.item_attributes = params[:menu_item_instance][:item_attributes].split(" ") @settings_menu_item_instances.save format.html { redirect_to settings_menu_category_simple_menu_item_path(category,catID), notice: 'Menu item instance was successfully updated.' } format.json { render :show, status: :ok, location: @settings_menu_item_instances } @@ -154,6 +153,9 @@ class Settings::MenuItemInstancesController < ApplicationController else @item = MenuItem.find(params[:set_menu_item_id]) end + + # To Only show in Menu item selected attrs + @item.item_attributes = MenuItemAttribute.where(id: @item.item_attributes).select("id, name").map { |e| [e.name, e.id] } end # Never trust parameters from the scary internet, only allow the white list through. diff --git a/app/controllers/settings/promotions_controller.rb b/app/controllers/settings/promotions_controller.rb index ec09aaab..ec00c5f6 100755 --- a/app/controllers/settings/promotions_controller.rb +++ b/app/controllers/settings/promotions_controller.rb @@ -29,8 +29,12 @@ class Settings::PromotionsController < ApplicationController def create @promotion = Promotion.new(promotion_params) @promotion.created_by = current_login_employee.id - @promotion.promo_start_hour = @promotion.promo_start_hour.to_datetime.advance(hours: +6, minutes: +30) - @promotion.promo_end_hour = @promotion.promo_end_hour.to_datetime.advance(hours: +6, minutes: +30) + if !@promotion.promo_start_hour.nil? + @promotion.promo_start_hour = @promotion.promo_start_hour.to_datetime.advance(hours: +6, minutes: +30) + end + if !@promotion.promo_end_hour.nil? + @promotion.promo_end_hour = @promotion.promo_end_hour.to_datetime.advance(hours: +6, minutes: +30) + end respond_to do |format| if @promotion.save promo_pros = @promotion.promotion_products @@ -95,16 +99,23 @@ class Settings::PromotionsController < ApplicationController def find_parent_item res = [] - item = MenuItemInstance.find_by_item_instance_code(params[:item_instance_code]) - if item.nil? + arr_inst = [] + item_inst = MenuItemInstance.find_by_item_instance_code(params[:item_instance_code]) + if item_inst.nil? product = Product.where("item_code = ?",params[:item_instance_code]).pluck(:name,:item_code) res.push(product.name) res.push(product.item_code) else - # menu_item = item.menu_item.pluck(:name,:item_code) - res.push(item.item_instance_name) - res.push(item.menu_item.item_code) + # menu_item = item_inst.menu_item.pluck(:name,:item_code) + # res.push(item_inst.item_instance_name) + # res.push(item_inst.menu_item.item_code) + item_inst.menu_item.menu_item_instances.each do |inst| + arr_inst.push({inst.item_instance_code => inst.item_instance_name}) + end + res.push({item_inst.menu_item.item_code => arr_inst}) end + puts "res" + p res render json: res end diff --git a/app/controllers/settings/set_menu_items_controller.rb b/app/controllers/settings/set_menu_items_controller.rb index 1fbeb148..c460c362 100755 --- a/app/controllers/settings/set_menu_items_controller.rb +++ b/app/controllers/settings/set_menu_items_controller.rb @@ -141,6 +141,6 @@ class Settings::SetMenuItemsController < ApplicationController # Never trust parameters from the scary internet, only allow the white list through. def settings_menu_item_params - params.require(:set_menu_item).permit(:item_code, :name, :alt_name, :type, :image_path, :menu_category_id,:account_id , :item_attributes, :item_options, :min_qty, :is_sub_item, :is_available, :created_by, :item_sets, :unit) + params.require(:set_menu_item).permit(:item_code, :name, :alt_name, :type, :image_path, :menu_category_id,:account_id , :item_attributes, :item_options, :min_qty, :is_sub_item, :is_available, :created_by, :item_sets, :unit, :taxable) end end diff --git a/app/controllers/settings/simple_menu_items_controller.rb b/app/controllers/settings/simple_menu_items_controller.rb index 35af3b83..9a7c46db 100755 --- a/app/controllers/settings/simple_menu_items_controller.rb +++ b/app/controllers/settings/simple_menu_items_controller.rb @@ -157,6 +157,6 @@ class Settings::SimpleMenuItemsController < ApplicationController # Never trust parameters from the scary internet, only allow the white list through. def settings_menu_item_params - params.require(:simple_menu_item).permit(:item_code, :name, :alt_name, :type, :image_path, :menu_category_id, :account_id, :item_attributes, :item_options, :min_qty, :is_sub_item, :is_available, :created_by, :item_sets, :unit) + params.require(:simple_menu_item).permit(:item_code, :name, :alt_name, :type, :image_path, :menu_category_id, :account_id, :item_attributes, :item_options, :min_qty, :is_sub_item, :is_available, :created_by, :item_sets, :unit, :taxable) end end diff --git a/app/controllers/sym_control_controller.rb b/app/controllers/sym_control_controller.rb new file mode 100644 index 00000000..816b8f2c --- /dev/null +++ b/app/controllers/sym_control_controller.rb @@ -0,0 +1,35 @@ +class SymControlController < BaseController + skip_before_action :verify_authenticity_token + + def run + sym_path = "/home/yan/symmetric/" + check_sym_proc_str = `#{"service SymmetricDS status"}` + # Check Sym Installed + # if sym_install_status[1] == "false" + # response = { "status": false, "message": "Activation is success but Symmetric service not Installed. \n Please contact code2lab call center!"} + # end + + if check_sym_proc_str.include? "Active: active (running)" || "Active: active (exited)" #"Server is already running" + # Create Sym Table + check_sym_table = system(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(sym_path + "bin/dbimport --engine sx " + sym_sql.to_s) + stop_sym = system("service SymmetricDS stop") + run_sym = system("service SymmetricDS start") + if run_sym + render :text => "

Success!

" + end + else + render :text => "

Sym Sql file not found!

" + end + end + else + render :text => "

Sym not running!

" + end + end + +end \ No newline at end of file diff --git a/app/controllers/transactions/bookings_controller.rb b/app/controllers/transactions/bookings_controller.rb index 3b8e241e..63090c9c 100644 --- a/app/controllers/transactions/bookings_controller.rb +++ b/app/controllers/transactions/bookings_controller.rb @@ -4,7 +4,7 @@ class Transactions::BookingsController < ApplicationController def index - filter = params[:filter] + filter = params[:receipt_no] from = params[:from] to = params[:to] diff --git a/app/controllers/transactions/credit_notes_controller.rb b/app/controllers/transactions/credit_notes_controller.rb index 09f48d66..e35baa77 100755 --- a/app/controllers/transactions/credit_notes_controller.rb +++ b/app/controllers/transactions/credit_notes_controller.rb @@ -14,7 +14,8 @@ class Transactions::CreditNotesController < ApplicationController to = params[:to] if filter.nil? && from.nil? && to.nil? && customer.nil? - @credit_notes = Sale.where('payment_status = ?', Sale::SALE_STATUS_OUTSTANDING) + @credit_notes = Sale.where('payment_status = ?', Sale::SALE_STATUS_OUTSTANDING) + @credit_notes = Kaminari.paginate_array(@credit_notes).page(params[:page]).per(20) else sale = Sale.search_credit_sales(customer,filter,from,to) if sale.count > 0 diff --git a/app/controllers/transactions/orders_controller.rb b/app/controllers/transactions/orders_controller.rb index a76fa385..17a117bb 100755 --- a/app/controllers/transactions/orders_controller.rb +++ b/app/controllers/transactions/orders_controller.rb @@ -3,16 +3,13 @@ class Transactions::OrdersController < ApplicationController def index filter = params[:filter] - count = params[:count] from = params[:from] to = params[:to] - if filter.nil? && from.nil? && to.nil? && count.nil? + if filter.nil? && from.nil? && to.nil? orders = Order.order("order_id desc") - else - orders = Order.search(filter,from,to,count) - + orders = Order.search(filter,from,to) end if !orders.nil? diff --git a/app/jobs/call_waiter_job.rb b/app/jobs/call_waiter_job.rb new file mode 100644 index 00000000..89c1b9ae --- /dev/null +++ b/app/jobs/call_waiter_job.rb @@ -0,0 +1,8 @@ +class CallWaiterJob < ApplicationJob + queue_as :default + + def perform(table,time) + ActionCable.server.broadcast "call_waiter_channel",table: table,time:time + # Rails.logger.debug "Testing: I'm performing my job with arguments: #{table}" + end +end diff --git a/app/jobs/check_in_booking_job.rb b/app/jobs/check_in_booking_job.rb new file mode 100644 index 00000000..7f8d39d3 --- /dev/null +++ b/app/jobs/check_in_booking_job.rb @@ -0,0 +1,9 @@ +class CheckInBookingJob < ApplicationJob + queue_as :default + + def perform(table) + ActionCable.server.broadcast "check_in_booking_channel",table: table + end +end + + diff --git a/app/jobs/checkin_job.rb b/app/jobs/checkin_job.rb new file mode 100644 index 00000000..298a42f5 --- /dev/null +++ b/app/jobs/checkin_job.rb @@ -0,0 +1,12 @@ +class CheckinJob < ApplicationJob + queue_as :default + + def self.perform() + table = DiningFacility.get_checkin_booking + if table.length > 0 + ActionCable.server.broadcast "checkin_channel",table: table + end + end + + +end diff --git a/app/jobs/order_queue_processor_job.rb b/app/jobs/order_queue_processor_job.rb index d8e5d6e1..18fdc2dd 100755 --- a/app/jobs/order_queue_processor_job.rb +++ b/app/jobs/order_queue_processor_job.rb @@ -3,9 +3,8 @@ class OrderQueueProcessorJob < ApplicationJob def perform(order_id, table_id) # Do something later - #Order ID - - order = Order.find(order_id) + #Order ID + order = Order.find(order_id) #Execute orders and send to order stations if order diff --git a/app/models/ability.rb b/app/models/ability.rb index c2947fe1..4470fb4b 100755 --- a/app/models/ability.rb +++ b/app/models/ability.rb @@ -25,11 +25,6 @@ class Ability can :manage, TaxProfile can :manage, PrintSetting can :manage, Account - can :manage, Commission - can :manage, Commissioner - can :manage, Promotion - can :manage, Product - can :manage, Order can :manage, Booking @@ -46,6 +41,13 @@ class Ability can :index, :credit_payment can :index, :void_sale + can :show, :dailysale + can :show, :saleitem + can :show, :receipt_no + can :show, :shiftsale + can :show, :credit_payment + can :show, :void_sale + can :get_customer, Customer can :add_customer, Customer can :update_sale_by_customer, Customer @@ -79,6 +81,13 @@ class Ability can :overall_void, :void + can :manage, Commission + can :manage, Commissioner + can :manage, Promotion + can :manage, Product + + can :manage, Inventory + elsif user.role == "cashier" # can :overall_void, :void @@ -112,6 +121,11 @@ class Ability can :move_dining, :moveroom can :manage, DiningQueue + + can :manage, Commission + can :manage, Commissioner + can :manage, Promotion + can :manage, Product elsif user.role == "account" @@ -121,6 +135,12 @@ class Ability can :index, :shiftsale can :index, :credit_payment can :index, :void_sale + can :show, :dailysale + can :show, :saleitem + can :show, :receipt_no + can :show, :shiftsale + can :show, :credit_payment + can :show, :void_sale elsif user.role == "supervisor" @@ -148,6 +168,12 @@ class Ability can :show, :payment can :reprint, :payment can :rounding_adj, :payment + + can :manage, Commission + can :manage, Commissioner + can :manage, Promotion + can :manage, Product + end end end diff --git a/app/models/customer.rb b/app/models/customer.rb index 13e6c277..8865448f 100755 --- a/app/models/customer.rb +++ b/app/models/customer.rb @@ -46,7 +46,8 @@ class Customer < ApplicationRecord rescue SocketError response = { status: false, message: "Can't connect server"} end - + Rails.logger.debug "--------Get Member Account response -------" + Rails.logger.debug response.to_json return response; end @@ -131,6 +132,8 @@ class Customer < ApplicationRecord rescue SocketError response = { status: false, message: "Can't connect server"} end + Rails.logger.debug "--------Update Membership response -------" + Rails.logger.debug response.to_json if response["status"] == true status = customer.update_attributes(membership_id: response["customer_datas"]["id"]) end @@ -141,7 +144,11 @@ class Customer < ApplicationRecord sales = Sale.where("rebate_status = 'false'") sales.each do |sale| if sale.customer.membership_id - response = self.rebat(Sale.find(sale.sale_id)) + response = self.rebat(Sale.find(sale.sale_id)) + #record an payment in sale-audit + remark = "UPdate Rebate Response - #{response} for Customer #{sale.customer_id} Sale Id [#{sale.sale_id}]| pay amount -> #{sale.received_amount} " + sale_audit = SaleAudit.record_paymal(sale.sale_id, remark, 1) + if response["status"] == true status = sale.update_attributes(rebate_status: "true") end @@ -184,12 +191,17 @@ class Customer < ApplicationRecord # Control for Paypar Cloud begin - response = HTTParty.post(url, :body => { generic_customer_id:generic_customer_id ,total_sale_transaction_amount: sObj.grand_total,merchant_uid:merchant_uid,total_amount: total_amount,campaign_type_id: campaign_type_id, - receipt_no: receipt_no,auth_token:auth_token}.to_json, - :headers => { - 'Content-Type' => 'application/json', - 'Accept' => 'application/json; version=2' - }, :timeout => 10) + response = HTTParty.post(url, :body => { generic_customer_id:generic_customer_id , + total_sale_transaction_amount: sObj.grand_total, + merchant_uid:merchant_uid, + total_amount: total_amount, + campaign_type_id: campaign_type_id, + receipt_no: receipt_no, + auth_token:auth_token}.to_json, + :headers => { + 'Content-Type' => 'application/json', + 'Accept' => 'application/json; version=2' + }, :timeout => 10) rescue Net::OpenTimeout response = { "status": false , "message": "Connect To" } @@ -201,7 +213,9 @@ class Customer < ApplicationRecord response = { "status": false, "message": "Can't connect server"} end - return response + return response + Rails.logger.debug "--------Update Rebate response -------" + Rails.logger.debug response.to_json end end end @@ -236,6 +250,8 @@ class Customer < ApplicationRecord rescue SocketError response = { status: false, message: "Can't connect server"} end + Rails.logger.debug "--------Search Paypar Account No response -------" + Rails.logger.debug response.to_json return response end diff --git a/app/models/dining_facility.rb b/app/models/dining_facility.rb index 1130003e..bd6f3436 100755 --- a/app/models/dining_facility.rb +++ b/app/models/dining_facility.rb @@ -67,7 +67,7 @@ class DiningFacility < ApplicationRecord end def get_current_checkout_booking - booking = Booking.where("dining_facility_id = #{self.id} and booking_status ='assign' and sale_id is null and checkout_at is not null and checkout_by is null").limit(1) + booking = Booking.where("dining_facility_id = #{self.id} and booking_status ='assign' and checkin_at between '#{DateTime.now.utc - 5.hours}' and '#{DateTime.now.utc}' and reserved_by is not null and checkout_by is null").limit(1) if booking.count > 0 then return booking[0] else @@ -78,19 +78,75 @@ class DiningFacility < ApplicationRecord def get_checkout_booking booking = self.get_current_checkout_booking if booking + lookup_checkout_time = Lookup.collection_of("checkout_alert_time") + free_time_min = 0 + if !lookup_checkout_time.nil? + if lookup_checkout_time[0][0] == 'min' + free_time_min = (lookup_checkout_time[0][1]).to_i + else + free_time_min = 15 + end + end + now = Time.now.utc hr = (now.strftime("%H").to_i).to_int min = (now.strftime("%M").to_i).to_int - - checkout_at = booking.checkout_at.utc - - checkout_at = checkout_at - hr.hour - checkout_at = checkout_at - min.minutes - checkout_at = checkout_at.utc.strftime("%M").to_i - - if checkout_at <= 15 - return booking + if !booking.checkout_at.nil? + checkout_at = booking.checkout_at.utc + checkout_at_hr = (checkout_at.strftime("%H").to_i).to_int + checkout_at_min = (checkout_at.strftime("%M").to_i).to_int + checkout_at_min -= min + if (checkout_at_hr < hr) + return booking + elsif (checkout_at_hr == hr && checkout_at_min <= free_time_min) + return booking + else + return nil + end + else + return nil end end end + + def self.get_checkin_booking + bookings = Booking.where("booking_status ='assign' and checkin_at between '#{DateTime.now.utc - 5.hours}' and '#{DateTime.now.utc}' and reserved_by is not null and checkout_by is null") + arr_booking = Array.new + if bookings + lookup_checkout_time = Lookup.collection_of("checkout_alert_time") + free_time_min = 0 + if !lookup_checkout_time.nil? + if lookup_checkout_time[0][0] == 'min' + free_time_min = (lookup_checkout_time[0][1]).to_i + else + free_time_min = 15 + end + end + + bookings.each do |booking| + now = Time.now.utc + hr = (now.strftime("%H").to_i).to_int + min = (now.strftime("%M").to_i).to_int + if !booking.checkout_at.nil? + checkout_at = booking.checkout_at.utc + checkout_at_hr = (checkout_at.strftime("%H").to_i).to_int + checkout_at_min = (checkout_at.strftime("%M").to_i).to_int + checkout_at_min -= min + if (checkout_at_hr < hr) + arr_booking.push({'table_id' => booking.dining_facility_id}) + elsif (checkout_at_hr == hr && checkout_at_min <= free_time_min) + arr_booking.push({'table_id' => booking.dining_facility_id}) + end + end + end + end + return arr_booking + end + + #send order items and send to order queue + def self.check_in_booking(table_id) + table = DiningFacility.find(table_id) + #Send to background job for processing + CheckInBookingJob.perform_later(table) + end end diff --git a/app/models/license.rb b/app/models/license.rb index 23b19aae..36ce9b29 100755 --- a/app/models/license.rb +++ b/app/models/license.rb @@ -18,127 +18,122 @@ class License if (server != "") self.class.base_uri server end - - # @secret = ENV["aes_key"] - # @params = { query: { device: "SX", token: SECRETS_CONFIG['provision_key'] } } - end - - def shop_code - if ( self.subdomain.length > 3) - return self.subdomain[0,3].upcase - else - return self.subdomain.upcase - end end - def detail_with_local_cache(lookup, key, iv) + # For Cloud + def detail_with_local_cache(lookup) + aes = MyAesCrypt.new + 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:#{key}:hostname" - - # No Needs for current - # @secret = key + cache_key = "#{lookup}:license:#{aes_key}:hostname" cache_license = nil ##Get redis connection from connection pool - Redis.current do |conn| - cache_license = conn.get(cache_key) - end + redis = Redis.new + cache_license = redis.get(cache_key) Rails.logger.info "Cache key - " + cache_key.to_s if cache_license.nil? ##change the d/e key # @options = { query: {device: "SXlite", lookup: lookup, skey: @secret, token: SECRETS_CONFIG['provision_key']} } - @params = { query: { lookup_type: self.server_mode, lookup: lookup, encrypted_key: key, iv_key: iv} } + @params = { query: { lookup_type: self.server_mode, lookup: lookup, iv_key: aes_iv} } response = self.class.get("/subdomain", @params) @license = response.parsed_response if (@license["status"] == true) - - assign() + assign(aes_key, aes_iv) Rails.logger.info "License - " + response.parsed_response.to_s - - Redis.current do |conn| - ##Remote - store the remote response in local redis cache - conn.set(cache_key, Marshal.dump(@license)) - ##ADD to List to remove later - conn.sadd("License:cache:keys", cache_key) - end + + redis = Redis.new + redis.set(cache_key, Marshal.dump(@license)) + # redis.sadd("License:cache:keys", cache_key) + # Redis.current do |conn| + # ##Remote - store the remote response in local redis cache + # conn.set(cache_key, Marshal.dump(@license)) + # ##ADD to List to remove later + # conn.sadd("License:cache:keys", cache_key) + # end return true end - - Rails.logger.info 'API License' + else + @license = Marshal.load(cache_license) + assign(aes_key, aes_iv) + Rails.logger.info 'API License' + return true end 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 + else + has_license = verify_license() - def detail_with_local_file() - has_license = true #verify_license() - - if has_license - # puts "VERIFIED" + if has_license + # return for expiring + return 2 + else + return 0 + end end + # end + end - # if cache_license.nil? - # ##change the d/e key - # @params = { query: { lookup_type: self.server_mode, lookup: lookup, encrypted_key: key, iv_key: iv} } + # 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) - # response = self.class.get("/request_license", @params) - # @license = response.parsed_response + @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 (@license["status"] == true) + if (@activate["status"]) + ##Check from local redis - if available load local otherwise get from remote + cache_key = "shop:#{@activate["shop_name"]}" - # assign() + cache_license = nil - # Rails.logger.info "License - " + response.parsed_response.to_s + ##Get redis connection from connection pool + redis = Redis.new + cache_license = redis.get(cache_key) - # Redis.current do |conn| - # ##Remote - store the remote response in local redis cache - # conn.set(cache_key, Marshal.dump(@license)) - # ##ADD to List to remove later - # conn.sadd("License:cache:keys", cache_key) - # end + Rails.logger.info "Cache key - " + cache_key.to_s - # return true - # end + 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 'API License' + Rails.logger.info "License - " + response.parsed_response.to_s - # else - # @license = Marshal.load(cache_license) if cache_license - - # Rails.logger.info 'Cache License' - - # if (@license["status"] == true) - # assign() - # return true - # end - # end - # return false + response = create_license_file(@activate) + if(response[:status]) + sym_path = "/home/yan/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 + return response end - def detail - response = self.class.get("/subdomain", @options) - @license = response.parsed_response - - Rails.logger.debug "License - " + response.parsed_response.to_s - - - if (@license["status"] == true) - assign() - - return true - end - - return false - end - - def verify_license - api_token = read_license("api_token") - @options = { query: {lookup_type: "application", token: api_token} } - response = self.class.get("/verify", @options) + def verify_license + api_token = read_license_no_decrypt("api_token") + @params = { query: {lookup_type: "application", api_token: api_token} } + response = self.class.get("/verify", @params) @varified = response.parsed_response Rails.logger.debug "License Remote Response - " + response.parsed_response.to_s @@ -152,38 +147,23 @@ class License return false end - def check_remote_license(license_key) - # @options = { query: {device: "cloud", key: license_key, skey: @secret, token: Rails.application.secrets.provision_key} } - @options = { query: {lookup_type: "application", encrypted_key: @secret, token: SECRETS_CONFIG['provision_key']} } - response = self.class.get("/license", @options) - - @license = response.parsed_response - - Rails.logger.debug "License Remote Response - " + response.parsed_response.to_s - if (@license["status"]) - assign() + # Check Expired before 30 days + def check_expiring(renewal_date_str) + if !renewal_date_str.empty? + renewal_date = DateTime.parse(renewal_date_str) + renewal_date > Date.today.advance(:days => 30) end - return @license["status"] - end - def verify_by_api_token(api_token) - @options = { query: {device: "SX", api_token: api_token, skey: @secret, token: SECRETS_CONFIG['provision_key']} } - response = self.class.get("/verify", @options) - - @license = response.parsed_response - - Rails.logger.debug "License Remote Response - " + response.parsed_response.to_s - if (@license["status"]) - assign() + # Check License expired date from PROVISION SERVER + 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) + update_license("renewable_date", renewal_date_str) end - return @license["status"] - end - #Load License is remove from the cloud license because - this license is must be validated against subdmain instead of license.data from file. - - - def check_expired(renewal_date) if (renewal_date < Date.today) return true else @@ -191,67 +171,259 @@ class License end end + # Check License File exists def self.check_license_file return File.exist?("config/license.yml") end # read line by key for license file - def read_license(key) + def read_license(key_name) + decrypted_line = "" + key, iv = get_redis_key() + + if File.exist?("config/license.yml") + File.open("config/license.yml").each do |line| + 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 + 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") File.open("config/license.yml").each do |line| if line.include? (key) - decrypted_line_array = line.split(":") - decrypted_line = AESCrypt.decrypt(decrypted_line_array[1]) + decrypted_line_array = line.split(": ") + decrypted_line = decrypted_line_array[1] end end end + return decrypted_line end - private - def assign - # self.name = @license["name"] - # self.address_1 = @license["address_1"] - # self.address_2 = @license["address_2"] - # self.township = @license["township"] - # self.city = @license["city"] - # self.country = @license["country"] - # self.email = @license["email"] - # self.phone = @license["phone"] - # self.fax = @license["fax"] - # self.logo = @license["logo"] - # self.localhost_address = @license["localhost_address"] - # self.subdomain = @license["subdomain"] - # self.plan_activation_date = Date.parse(@license["plan_activation_date"]) - # self.plan_next_renewal_date = Date.parse(@license["plan_next_renewal_date"]) + # Update license file for line + def update_license(content, new_content) + key, iv = get_redis_key() - ## self.plan_activation_date = Date.strptime(@license["plan_activation_date"], "%Y-%m-%d") - ## self.plan_next_renewal_date = Date.strptime(@license["plan_next_renewal_date"], "%Y-%m-%d") + 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") + 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 + # end + end + end - # self.plan_max_products = @license["plan_max_products"].to_i - # self.plan_max_customers = @license["plan_max_customers"].to_i - # self.plan_active_connections = @license["plan_active_connections"].to_i - salt = @license["secret_key"] + private + def get_redis_key + iv = "" + 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}" - if (@license["dbhost"] || @license["dbschema"] || @license["dbusername"] || @license["dbpassword"] ) - self.dbhost = AESCrypt.decrypt(@license["dbhost"], salt) - self.dbschema = AESCrypt.decrypt(@license["dbschema"], salt) - self.dbusername = AESCrypt.decrypt(@license["dbusername"], salt) - self.dbpassword = AESCrypt.decrypt(@license["dbpassword"], salt) + cache_shop = nil + + ##Get redis connection from connection pool + redis = Redis.new + cache_shop = redis.get(cache_key) + + if !cache_shop.nil? + @shop = Marshal.load(cache_shop) + key = @shop["key"] + iv = @shop["iv"] + end + return key, iv + end + + def encode_str(str) + return Base64.encode64(str) + end + + def decode_str(str) + return Base64.decode64(str) + end + + # License File Creation + def create_license_file(response_data) + if File.exist?("config/license.yml") + delete_license_file end - # self.exchange_unqiue_id = @license["exchange_unqiue_id"] + begin + # Licese File Creation + 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']}") + f.puts("telephone: #{response_data['telephone']}") + f.puts("fax: #{response_data['fax']}") + f.puts("address: #{response_data['address']}") + f.puts("dbhost: #{response_data['dbhost']}") + f.puts("dbschema: #{response_data['dbschema']}") + 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("plan_sku: #{response_data['plan_sku']}") + f.puts("renewable_date: #{response_data['renewable_date']}") + f.puts("plan_name: #{response_data['plan_name']}") + end + rescue IOError + response = { "status": false, "message": "Activation is success but something is wrong. \n Please contact code2lab call center!"} + end + response = { "status": true, "message": "Success Activation. License also created."} + end - # self.localqueue_host= @license["localqueue_host"] - # self.localqueue_user= @license["localqueue_user"] - # self.localqueue_password= @license["localqueue_password"] + # Symmetric Configuration + def create_symmetric_config(sym_location, db_host, db_schema, db_user, db_password) + if File.directory? (sym_location) + begin + # sx properties create + f = File.open(sym_location + "engines/sx.properties", "w") + f.write("engine.name=sx\n") + f.write("db.driver=com.mysql.jdbc.Driver\n") + f.write("db.url=jdbc:mysql://#{db_host}/#{db_schema}?tinyInt1isBit=false\n") + f.write("db.user=#{db_user}\n") + f.write("db.password=#{db_password}\n") + f.write("registration.url=\n") + f.write("sync.url=http://#{db_host}:31415/sync/sx\n") + 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("initial.load.use.extract.job.enabled=true\n") + f.close - # self.remotequeue_host = @license["remotequeue_host"] - # self.remotequeue_user = @license["remotequeue_user"] - # self.remotequeue_password = @license["remotequeue_password"] + # read from license file + shop_name = read_license_no_decrypt("shop_name") + dbhost = read_license("dbhost") + dbschema = read_license("dbschema") + dbusername = read_license("dbusername") + dbpassword = read_license("dbpassword") - # self.api_token = @license["api_token"] - # self.app_token = @license["app_token"] + # shop properties create + f = File.open(sym_location + "engines/#{shop_name}.properties", "w") + f.write("engine.name=#{shop_name}\n") + f.write("db.driver=com.mysql.jdbc.Driver\n") + f.write("db.url=jdbc:mysql://#{dbhost}/#{dbschema}?tinyInt1isBit=false\n") + f.write("db.user=#{dbusername}\n") + f.write("db.password=#{dbpassword}\n") + f.write("registration.url=http://#{db_host}:31415/sync/sx\n") + f.write("group.id=store\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.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.close + rescue IOError + response = { "status": false, "message": "Activation is success but something is wrong. \n Please contact code2lab call center!"} + end + response = { "status": true, "message": "Success Activation. License also created."} + end + end + + # 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 = `#{"service SymmetricDS status"}` + + # Check Sym Installed + # if sym_install_status[1] == "false" + # response = { "status": false, "message": "Activation is success but Symmetric service not Installed. \n Please contact code2lab call center!"} + # end + + # Run Sym Service + sym_run_status = check_sym_running(check_sym_proc_str, sym_path) + if sym_run_status + # Create Sym Table + check_sym_table = system(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(sym_path + "bin/dbimport --engine sx " + sym_sql.to_s) + stop_sym = system("service SymmetricDS stop") + run_sym = system("service SymmetricDS start") + if run_sym + response = { "status": true, "message": "Activation is success and Configuration done..."} + end + else + response = { "status": false, "message": "Activation is success but Symmetric Sql not found. \n Please contact code2lab call center!"} + end + end + else + response = { "status": false, "message": "Activation is success but Symmetric not running. \n Please contact code2lab call center!"} + end + end + + # Check Symmetric Running + def check_sym_running(status, sym_path) + # Run Sym Service + # if status.include? "Server is already running" + # return true + # elsif status.include? "false" + # sym_start_str = `#{sym_path + "bin/sym_service start"}` + # if sym_start_str.include? "Started" + # return true + # else + # check_sym_running(sym_start_status[0]) + # end + # else + # return true + # end + + if status.include? "Active: active (running)" || "Active: active (exited)" #"Server is already running" + return true + end + return false + end + + # Delete License File + def delete_license_file + File.delete("config/license.yml") if File.exist?("config/license.yml") + end + + # Assign db info for Cloud + 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"] ) + host = Base64.decode64(@license["dbhost"]) + dbschema = Base64.decode64(@license["dbschema"]) + dbusername = Base64.decode64(@license["dbusername"]) + dbpassword = Base64.decode64(@license["dbpassword"]) + + 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']) + end + end end diff --git a/app/models/membership_setting.rb b/app/models/membership_setting.rb index 89f9eb14..3b60c781 100755 --- a/app/models/membership_setting.rb +++ b/app/models/membership_setting.rb @@ -1,2 +1,3 @@ class MembershipSetting < ApplicationRecord + MembershipSetting = MembershipSetting.find_by_id(1) end diff --git a/app/models/menu_item.rb b/app/models/menu_item.rb index 9bfcdb85..67a3c823 100755 --- a/app/models/menu_item.rb +++ b/app/models/menu_item.rb @@ -13,7 +13,7 @@ class MenuItem < ApplicationRecord has_many :menu_item_sets has_many :item_sets, through: :menu_item_sets - validates_presence_of :item_code, :name, :type, :min_qty, :taxable,:account_id + validates_presence_of :item_code, :name, :type, :min_qty,:account_id validates_uniqueness_of :item_code default_scope { order('item_code asc') } diff --git a/app/models/menu_item_instance.rb b/app/models/menu_item_instance.rb index a51a94c4..baad6392 100755 --- a/app/models/menu_item_instance.rb +++ b/app/models/menu_item_instance.rb @@ -4,8 +4,9 @@ class MenuItemInstance < ApplicationRecord has_many :menu_instance_item_sets has_many :item_sets, through: :menu_instance_item_sets # before_create :generate_menu_item_instance_code - validates_presence_of :item_instance_code - # validates_uniqueness_of :item_instance_code + # validates_presence_of :item_instance_code + + validates_uniqueness_of :item_instance_code def self.findParentCategory(item) if item.menu_category_id diff --git a/app/models/my_aes_crypt.rb b/app/models/my_aes_crypt.rb index 7427a000..680d0624 100644 --- a/app/models/my_aes_crypt.rb +++ b/app/models/my_aes_crypt.rb @@ -1,3 +1,7 @@ +require 'openssl' +require 'base64' +require 'json' + class MyAesCrypt @cipher = "" @@ -7,14 +11,51 @@ class MyAesCrypt def export_key(passphrase) # We want a 256 bit key symetric key based on passphrase + # for cloud is lookup + # for local is license_key + # iv_salt = passphrase+"c2l" + passphrase = passphrase + ENV['SX_KEY'] + passphrase = passphrase.gsub(".","_") digest = Digest::SHA256.new - key = digest.update(passphrase) - key = digest.digest - ENV['AES_KEY'] = cipher_key = key # stores the key in key, and also sets the generated key on the @cipher - ENV['AES_IV'] = cipher_iv = @cipher.random_iv # stores the iv in iv, and also sets the generated iv on the @cipher + key_digest = digest.update(passphrase) + key = key_digest.digest + + # iv = iv_digest.digest + ENV['AES_KEY'] = cipher_key = Base64.encode64(key) # stores the key in key, and also sets the generated key on the @cipher + ENV['AES_IV'] = cipher_iv = Base64.encode64(@cipher.random_iv) # stores the iv in iv, and also sets the generated iv on the @cipher return cipher_key, cipher_iv end + def export_to_file(passphrase) + file_path = "config/shops.json" + aes_key, aes_iv = export_key(passphrase) + tmpHash = { + "lookup" => passphrase, + "value" => + { + "key" => aes_key, + "iv" => aes_iv + } + } + + shop_data = File.read(file_path) + + shop_json = JSON.parse(shop_data) + shop_json["data"].each do |j| + if j["lookup"] == passphrase + return j["value"]["key"], j["value"]["iv"] + end + end + + shop_json["data"] << tmpHash + + File.open(file_path, "w") { |io| + io.puts JSON.pretty_generate(shop_json) + } + + return aes_key, aes_iv + end + private def encrypt(data) cipher.encrypt diff --git a/app/models/order.rb b/app/models/order.rb index 33022eec..ba8adc8f 100755 --- a/app/models/order.rb +++ b/app/models/order.rb @@ -133,7 +133,7 @@ class Order < ApplicationRecord OrderItem.processs_item(menu_item[:item_code], item[:item_instance_code], menu_item[:name], menu_item[:alt_name], menu_item[:account_id], item[:quantity],menu_item[:price], item[:options], set_order_items, self.id, - self.employee_name) + self.employee_name, menu_item[:taxable]) #end end @@ -363,18 +363,18 @@ class Order < ApplicationRecord end - def self.search(filter,from,to,count) - if count.to_i > 0 - item_count = "and item_count = '#{count}'" + def self.search(filter,from,to) + if filter.blank? + keyword = '' else - item_count = '' + keyword = "order_id LIKE ? OR status LIKE ? OR order_type LIKE ? OR source='#{filter}'","%#{filter}%","%#{filter}%","%#{filter}%" end - if from.present? && to.present? - Order.where("DATE_FORMAT(date,'%d-%m-%Y') >= ?" + " AND DATE_FORMAT(date,'%d-%m-%Y') <= ? #{item_count}", from,to) - elsif !from.present? && !to.present? && count.present? - Order.where("item_count = '#{count}'") + + if from.present? && to.present? + order = Order.where("DATE_FORMAT(date,'%d-%m-%Y') >= ?" + " AND DATE_FORMAT(date,'%d-%m-%Y') <= ?", from,to) + query = order.where(keyword) else - Order.where("order_id LIKE ? OR status LIKE ? OR order_type LIKE ? OR source='#{filter}'","%#{filter}%","%#{filter}%","%#{filter}%",) + where("order_id LIKE ? OR status LIKE ? OR order_type LIKE ? OR source='#{filter}'","%#{filter}%","%#{filter}%","%#{filter}%") end end diff --git a/app/models/order_item.rb b/app/models/order_item.rb index 12c8c378..776bb94c 100755 --- a/app/models/order_item.rb +++ b/app/models/order_item.rb @@ -20,7 +20,7 @@ class OrderItem < ApplicationRecord # option_values : [], # sub_order_items : [], # } - def self.processs_item (item_code, instance_code, menu_name, alt_name, account_id, qty,price, options, set_menu_items, order_id, item_order_by) + def self.processs_item (item_code, instance_code, menu_name, alt_name, account_id, qty,price, options, set_menu_items, order_id, item_order_by, taxable) orderitem = OrderItem.create do |oitem| oitem.order_id = order_id @@ -31,6 +31,7 @@ class OrderItem < ApplicationRecord oitem.account_id = account_id oitem.qty = qty oitem.price = price + oitem.taxable = taxable oitem.options = options oitem.set_menu_items = set_menu_items oitem.item_order_by = item_order_by #person who order this. * If emenu - it will be login user on the app diff --git a/app/models/order_queue_station.rb b/app/models/order_queue_station.rb index fcdb4983..c8a3a552 100755 --- a/app/models/order_queue_station.rb +++ b/app/models/order_queue_station.rb @@ -116,13 +116,13 @@ class OrderQueueStation < ApplicationRecord end #Print order_item in 1 slip per item - def print_slip_item(oqs, assigned_order_item) + def print_slip_item(oqs, assigned_item) unique_code="OrderItemPdf" - + order_item = OrderItem.where("order_id='#{assigned_item.order_id}' AND item_instance_code='#{assigned_item.instance_code}'").first() # print when complete click print_settings=PrintSetting.find_by_unique_code(unique_code) order_queue_printer= Printer::OrderQueuePrinter.new(print_settings) - order_queue_printer.print_order_item(print_settings, oqs,item.order_id, item.item_code, print_status="" ) + order_queue_printer.print_order_item(print_settings, oqs,item.order_id, order_item.order_items_id, print_status="" ) # update print status for completed same order items assigned_order_item.each do |ai| diff --git a/app/models/print_setting.rb b/app/models/print_setting.rb index c326f715..a13229dc 100755 --- a/app/models/print_setting.rb +++ b/app/models/print_setting.rb @@ -1,4 +1,4 @@ class PrintSetting < ApplicationRecord # validations - validates_presence_of :name, :unique_code, :printer_name, :page_width, :page_height + validates_presence_of :name, :unique_code, :printer_name, :page_width, :page_height, :print_copies end diff --git a/app/models/printer/order_queue_printer.rb b/app/models/printer/order_queue_printer.rb index 13d8a20a..cc08f9ba 100755 --- a/app/models/printer/order_queue_printer.rb +++ b/app/models/printer/order_queue_printer.rb @@ -1,12 +1,18 @@ class Printer::OrderQueuePrinter < Printer::PrinterWorker - def print_order_item(print_settings,oqs,order_id, item_code, print_status, options="") + def print_order_item(print_settings,oqs, order_id, order_item_id, print_status, options="") #Use CUPS service #Generate PDF #Print - order_item = print_query('order_item', item_code) #OrderItem.find_by_item_code(item_code) + # Must be one print + if print_settings.print_copies == 0 + print_settings.print_copies = 1 + print_settings.save! + end - filename = "tmp/order_item.pdf" + order_item = print_query('order_item', order_item_id) #OrderItem.find_by_item_code(item_code) + + filename = "tmp/order_item_#{order_id}_#{order_item_id}" + ".pdf" # check for item not to show # if order_item[0].price != 0 @@ -14,12 +20,13 @@ class Printer::OrderQueuePrinter < Printer::PrinterWorker pdf.render_file filename if oqs.print_copy - self.print(filename, oqs.printer_name) - self.print(filename, oqs.printer_name) + self.print(filename, oqs.printer_name) #For print copy # pdf.render_file filename.gsub(".","-copy.") # self.print(filename.gsub(".","-copy."), oqs.printer_name) else + print_settings.print_copies = 1 + print_settings.save! self.print(filename, oqs.printer_name) end # end @@ -29,42 +36,51 @@ class Printer::OrderQueuePrinter < Printer::PrinterWorker def print_order_summary(print_settings,oqs, order_id, order_items, print_status) #Use CUPS service #Generate PDF - #Print - order=print_query('order_summary', order_id) + #Print + # Must be one print + if print_settings.print_copies == 0 + print_settings.print_copies = 1 + print_settings.save! + end + order=print_query('order_summary', order_id) # For Print Per Item if oqs.cut_per_item - order.each do|odi| - filename = "tmp/order_item.pdf" + + order_items.each do|odi| + odi_item=print_query('order_item', odi.order_items_id) + filename = "tmp/order_item_#{order_id}" + ".pdf" # For Item Options options = odi.options == "[]"? "" : odi.options # check for item not to show #if odi.price != 0 - pdf = OrderItemPdf.new(print_settings,odi, print_status, options, oqs.use_alternate_name) + pdf = OrderItemPdf.new(print_settings,odi_item[0], print_status, options, oqs.use_alternate_name) # pdf.render_file "tmp/order_item.pdf" pdf.render_file filename - if oqs.print_copy - self.print(filename, oqs.printer_name) + if oqs.print_copy self.print(filename, oqs.printer_name) # self.print(filename.gsub(".","-copy."), oqs.printer_name) else + print_settings.print_copies = 1 + print_settings.save! self.print(filename, oqs.printer_name) end #end end # For Print Order Summary else - filename = "tmp/order_summary.pdf" + filename = "tmp/order_summary_#{order_id}" + ".pdf" pdf = OrderSummaryPdf.new(print_settings,order, print_status, order_items, oqs.use_alternate_name) pdf.render_file filename if oqs.print_copy - self.print(filename, oqs.printer_name) - self.print(filename, oqs.printer_name) + self.print(filename, oqs.printer_name) #For print copy # pdf.render_file filename.gsub(".","-copy.") # self.print(filename.gsub(".","-copy."), oqs.printer_name) else + print_settings.print_copies = 1 + print_settings.save! self.print(filename, oqs.printer_name) end end @@ -72,11 +88,17 @@ class Printer::OrderQueuePrinter < Printer::PrinterWorker # Print for orders in booking def print_booking_summary(print_settings,oqs, booking_id, print_status) + # Must be one print + if print_settings.print_copies == 0 + print_settings.print_copies = 1 + print_settings.save! + end + order=print_query('booking_summary', booking_id) # For Print Per Item if oqs.cut_per_item order.each do|odi| - filename = "tmp/order_item.pdf" + filename = "tmp/order_item_#{booking_id}" + ".pdf" # For Item Options options = odi.options == "[]"? "" : odi.options @@ -89,25 +111,29 @@ class Printer::OrderQueuePrinter < Printer::PrinterWorker self.print(filename, oqs.printer_name) #For print copy - pdf.render_file filename.gsub(".","-copy.") - self.print(filename.gsub(".","-copy."), oqs.printer_name) + # pdf.render_file filename.gsub(".","-copy.") + # self.print(filename.gsub(".","-copy."), oqs.printer_name) else + print_settings.print_copies = 1 + print_settings.save! self.print(filename, oqs.printer_name) end #end end # For Print Order Summary else - filename = "tmp/booking_summary.pdf" + filename = "tmp/booking_summary_#{booking_id}" + ".pdf" pdf = OrderSummaryPdf.new(print_settings,order, print_status,oqs.use_alternate_name) pdf.render_file filename if oqs.print_copy self.print(filename, oqs.printer_name) #For print copy - pdf.render_file filename.gsub(".","-copy.") - self.print(filename.gsub(".","-copy."), oqs.printer_name) + # pdf.render_file filename.gsub(".","-copy.") + # self.print(filename.gsub(".","-copy."), oqs.printer_name) else + print_settings.print_copies = 1 + print_settings.save! self.print(filename, oqs.printer_name) end end @@ -117,13 +143,13 @@ class Printer::OrderQueuePrinter < Printer::PrinterWorker def print_query(type, id) if type == "order_item" OrderItem.select("order_items.order_id, order_items.item_code, order_items.item_name, order_items.qty, order_items.price, order_items.options, order_items.item_order_by as order_by, order_items.created_at as order_at, cus.name as customer, df.type, df.name as dining,item.alt_name as alt_name") - .joins("left join orders ON orders.order_id = order_items.order_id + .joins("left join orders ON orders.order_id = order_items.order_id left join booking_orders AS bo ON bo.order_id=order_items.order_id left join bookings AS b ON b.booking_id = bo.booking_id left join dining_facilities AS df ON df.id = b.dining_facility_id left join customers as cus ON cus.customer_id = orders.customer_id left join menu_items as item ON item.item_code = order_items.item_code") - .where("order_items.item_instance_code = '#{ id }'") + .where("order_items.order_items_id = '#{ id }'") .group("order_items.item_code") elsif type == "order_summary" OrderItem.select("order_items.order_id, order_items.item_code, order_items.item_name, order_items.qty, order_items.price, order_items.options, order_items.item_order_by as order_by, order_items.created_at as order_at, cus.name as customer, df.type, df.name as dining,item.alt_name as alt_name") diff --git a/app/models/printer/printer_worker.rb b/app/models/printer/printer_worker.rb index 832e24bf..ad844cfe 100755 --- a/app/models/printer/printer_worker.rb +++ b/app/models/printer/printer_worker.rb @@ -33,7 +33,6 @@ class Printer::PrinterWorker end def print(file_path,printer_destination = nil ) - if printer_destination.nil? printer_destination = self.printer_destination end diff --git a/app/models/printer/receipt_printer.rb b/app/models/printer/receipt_printer.rb index 30bd5ed8..adcb187e 100755 --- a/app/models/printer/receipt_printer.rb +++ b/app/models/printer/receipt_printer.rb @@ -65,15 +65,19 @@ class Printer::ReceiptPrinter < Printer::PrinterWorker end #Bill Receipt Print - def print_receipt_bill(printer_settings,cashier_terminal,sale_items,sale_data, customer_name, item_price_by_accounts, discount_price_by_accounts, member_info = nil,rebate_amount=nil,shop_details, printed_status) + def print_receipt_bill(printer_settings,cashier_terminal,sale_items,sale_data, customer_name, item_price_by_accounts, discount_price_by_accounts, member_info = nil,rebate_amount=nil,shop_details, printed_status,balance) #Use CUPS service #Generate PDF #Print - pdf = ReceiptBillPdf.new(printer_settings, sale_items, sale_data, customer_name, item_price_by_accounts, discount_price_by_accounts, member_info,rebate_amount,shop_details,printed_status) + pdf = ReceiptBillPdf.new(printer_settings, sale_items, sale_data, customer_name, item_price_by_accounts, discount_price_by_accounts, member_info,rebate_amount,shop_details,printed_status,balance) # print as print copies in printer setting count = printer_settings.print_copies + + # override print copies for print worker loop + print_settings.print_copies = 1 + print_settings.save! begin if count == 1 pdf.render_file "tmp/receipt_bill_#{sale_data.receipt_no}.pdf" @@ -100,7 +104,7 @@ class Printer::ReceiptPrinter < Printer::PrinterWorker #Generate PDF #Print pdf = QueueNoPdf.new(printer_settings,queue) - pdf.render_file "tmp/print_queue_no.pdf" + pdf.render_file "tmp/print_queue_no.pdf" self.print("tmp/print_queue_no.pdf") end @@ -113,4 +117,15 @@ class Printer::ReceiptPrinter < Printer::PrinterWorker pdf.render_file "tmp/print_crm_order.pdf" self.print("tmp/print_crm_order.pdf") end + + #Queue No Print + def print_call_waiter(printer_settings,table,time,shop_detail) + #Use CUPS service + #Generate PDF + #Print + pdf = CallWaiterPdf.new(printer_settings,table,time,shop_detail) + pdf.render_file "tmp/print_call_waiter.pdf" + self.print("tmp/print_call_waiter.pdf") + end + end diff --git a/app/models/sale.rb b/app/models/sale.rb index 7cacedf3..b97c529e 100755 --- a/app/models/sale.rb +++ b/app/models/sale.rb @@ -225,7 +225,11 @@ class Sale < ApplicationRecord puts "item.sales_item_id ddd" puts item.sale_item_id subtotal_price = subtotal_price + item.price - total_taxable = total_taxable + item.taxable_price + + # only calc tax when true + if(item.is_taxable) + total_taxable = total_taxable + item.taxable_price + end # total_taxable = total_taxable + (item.taxable_price * item.qty) end @@ -287,7 +291,11 @@ class Sale < ApplicationRecord if item.remark != 'void' && item.remark != 'foc' #compute each item and added to total subtotal_price = subtotal_price + item.price - total_taxable = total_taxable + item.price + + # only calc tax when true + if(item.is_taxable) + total_taxable = total_taxable + item.taxable_price + end end end @@ -449,7 +457,7 @@ class Sale < ApplicationRecord sale = Sale.where("DATE_FORMAT(receipt_date,'%d-%m-%Y') >= ?" + " AND DATE_FORMAT(receipt_date,'%d-%m-%Y') <= ? and NOT sale_status = 'void' ", from,to) query = sale.where(keyword) else - where("receipt_no LIKE ? OR cashier_name LIKE ? OR sale_status ='#{filter}'","%#{filter}%","%#{filter}%",) + where("receipt_no LIKE ? OR cashier_name LIKE ? OR sale_status ='#{filter}'","%#{filter}%","%#{filter}%") end end @@ -519,10 +527,10 @@ def self.daily_sales_list(from,to) SUM(case when (sale_payments.payment_method='jcb') then sale_payments.payment_amount else 0 end) as jcb_amount, SUM(case when (sale_payments.payment_method='paypar') then sale_payments.payment_amount else 0 end) as paypar_amount, SUM(case when (sale_payments.payment_method='cash') then sale_payments.payment_amount else 0 end) as cash_amount, - SUM(case when (sale_payments.payment_method='creditnote') then sale_payments.payment_amount else 0 end) as credit_amount, - SUM(case when (sale_payments.payment_method='foc') then sale_payments.payment_amount else 0 end) as foc_amount") + SUM(case when (sale_payments.payment_method='creditnote') then sale_payments.payment_amount else 0 end) as credit_amount, + SUM(case when (sale_payments.payment_method='foc') then sale_payments.payment_amount else 0 end) as foc_amount") .joins("join (select * from sale_payments group by sale_payments.sale_id, sale_payments.payment_method) sale_payments on sale_payments.sale_id = sales.sale_id") - .where("sale_status = ? AND sales.receipt_date between ? and ? AND total_amount != 0", 'completed', from, to) + .where("sale_status = ? AND sales.receipt_date between ? and ? ", 'completed', from, to) .group("DATE_FORMAT((CONVERT_TZ(sales.receipt_date,'+00:00','+06:30')),'%Y-%m-%d')") daily_total = Array.new @@ -562,7 +570,7 @@ def self.daily_sales_list(from,to) :grand_total => grand_total, :old_grand_total => old_grand_total, :void_amount => void_amount, - :rounding_adj => sale.rounding_adj} + :rounding_adj => sale.rounding_adj} daily_total.push(total) end @@ -591,11 +599,40 @@ def self.get_by_range_by_saleitems(from,to,status,report_type) end def self.get_by_shiftsales(from,to,shift) - if !shift.blank? - ShiftSale.where("id =?",shift.id) - else - ShiftSale.where("(shift_started_at between ? and ? OR shift_closed_at between ? and ? )", from, to, from, to) - end + if !shift.blank? + query = ShiftSale.where("shift_sales.id =?",shift.id) + else + query = ShiftSale.where("(shift_started_at between ? and ? OR shift_closed_at between ? and ? )", from, to, from, to) + end + + shift_sale_data = Hash.new + + query.each do |shift_sale| + foc = 0 + foc_data = Sale.select("SUM(sp.payment_amount) as foc_sales") + .joins("JOIN sale_payments as sp on sp.sale_id=sales.sale_id") + .where("sales.shift_sale_id=? and sp.payment_method='foc'",shift_sale.id) + .first() + + if !foc_data.foc_sales.nil? && foc_data.foc_sales > 0 + shift_sale.other_sales -= foc_data.foc_sales + foc = foc_data.foc_sales + end + + shift_sale_data[shift_sale.id] = { + :cashier_terminal_name => shift_sale.cashier_terminal.name, + :employee_name => shift_sale.employee.name, + :shift_started_at => shift_sale.shift_started_at, + :shift_closed_at => shift_sale.shift_closed_at, + :cash_sales => shift_sale.cash_sales, + :credit_sales => shift_sale.credit_sales, + :other_sales => shift_sale.other_sales.to_f, + :foc_sales => foc, + :grand_total => shift_sale.grand_total + } + end + + return shift_sale_data.values end def self.get_by_shift_sale(from,to,status) @@ -608,41 +645,38 @@ def self.get_by_shift_sale(from,to,status) end def self.get_item_query() - # query = SaleItem.select("acc.title as account_name,account_id, item_instance_code as item_code, " + - # "SUM(qty * unit_price) as grand_total,SUM(qty) as total_item," + - # " unit_price as unit_price,product_name as product_name, 'cat' as" + - # " menu_category_name,'test' as menu_category_id ") + query = Sale.select("acc.title as account_name,mi.account_id, i.item_instance_code as item_code,i.account_id as account_id, " + + "SUM(i.qty * i.unit_price) as grand_total,SUM(i.qty) as total_item,i.qty as qty," + + "i.remark as status_type,"+ + " i.unit_price as unit_price,i.product_name as product_name, mc.name as" + + " menu_category_name,mc.id as menu_category_id ") - # query = query.joins("JOIN sales s ON s.sale_id = sale_items.sale_id" + - # " JOIN shift_sales sh ON sh.`id` = sales.shift_sale_id") - # # "JOIN employee_accesses ea ON ea.`employee_id` = sales.cashier_id ") + query = query.joins("JOIN sale_items i ON i.sale_id = sales.sale_id" + + " JOIN menu_item_instances mii ON i.item_instance_code = mii.item_instance_code" + + " JOIN menu_items mi ON mi.id = mii.menu_item_id" + + " JOIN shift_sales sh ON sh.`id` = sales.shift_sale_id" + + " JOIN menu_categories mc ON mc.id = mi.menu_category_id ") + # "JOIN employee_accesses ea ON ea.`employee_id` = sales.cashier_id ") + query = query.joins(" JOIN accounts acc ON acc.id = mi.account_id") + # query = query.where("i.item_instance_code IS NOT NULL") + query = query.group("i.product_name").order("mi.account_id desc") +end - # query = query.joins(" JOIN accounts acc ON acc.id = account_id") - # query = query.where("item_instance_code is not NULL") - # query = query.group("item_instance_code").order("account_id") - - query = Sale.select("acc.title as account_name,mi.account_id, i.item_instance_code as item_code, " + - "SUM(i.qty * i.unit_price) as grand_total,SUM(i.qty) as total_item," + - "i.remark as status_type,"+ - " i.unit_price as unit_price,i.product_name as product_name, mc.name as" + - " menu_category_name,mc.id as menu_category_id ") - - query = query.joins("JOIN sale_items i ON i.sale_id = sales.sale_id" + - " JOIN menu_item_instances mii ON i.item_instance_code = mii.item_instance_code" + - " JOIN menu_items mi ON mi.id = mii.menu_item_id" + - " JOIN shift_sales sh ON sh.`id` = sales.shift_sale_id" + - " JOIN menu_categories mc ON mc.id = mi.menu_category_id ") - # "JOIN employee_accesses ea ON ea.`employee_id` = sales.cashier_id ") - - query = query.joins(" JOIN accounts acc ON acc.id = mi.account_id") - query = query.where("i.item_instance_code IS NOT NULL") - query = query.group("i.product_name").order("mi.account_id, mi.menu_category_id") +def self.get_other_charges() + query = Sale.select("i.account_id as account_id, " + + "SUM(i.qty * i.unit_price) as grand_total,SUM(i.qty) as total_item," + + "i.remark as status_type,"+ + " i.unit_price as unit_price,i.product_name as product_name") + query = query.joins("JOIN sale_items i ON i.sale_id = sales.sale_id") + query = query.where("i.item_instance_code IS NULL AND i.product_code = 'Other Charges'") + query = query.group("i.sale_item_id") end def self.get_by_shift_items(shift_sale_range, shift, from, to, status) # date_type_selection = get_sql_function_for_report_type(report_type) query = self.get_item_query() + discount_query = 0 total_card_amount = 0 total_cash_amount = 0 @@ -650,10 +684,13 @@ def self.get_by_shift_items(shift_sale_range, shift, from, to, status) total_foc_amount = 0 total_grand_total = 0 + other_charges = self.get_other_charges() + if shift.present? query = query.where("sales.shift_sale_id IN (?) and sale_status='completed'",shift.to_a) + other_charges = other_charges.where("sales.shift_sale_id IN (?) and sale_status='completed'",shift.to_a) discount_query = Sale.where("sales.shift_sale_id in (?) and sale_status= 'completed' ", shift.to_a).sum(:total_discount) - change_amount = Sale.where("sales.shift_sale_id in (?) and sale_status= 'completed' ", shift.to_a).sum(:amount_changed) + change_amount = Sale.where("sales.shift_sale_id in (?) and sale_status= 'completed' ", shift.to_a).sum(:amount_changed) sale_cash = Sale.select("SUM(case when (sale_payments.payment_method ='mpu' or sale_payments.payment_method = 'visa' or sale_payments.payment_method = 'master' or sale_payments.payment_method = 'jcb' or sale_payments.payment_method = 'paypar') then (sale_payments.payment_amount) else 0 end) as card_amount, SUM(case when (sale_payments.payment_method='cash') then (sale_payments.payment_amount) else 0 end) as cash_amount, SUM(case when (sale_payments.payment_method='creditnote') then (sale_payments.payment_amount) else 0 end) as credit_amount, @@ -671,8 +708,9 @@ def self.get_by_shift_items(shift_sale_range, shift, from, to, status) ### => get all sales range in shift_sales elsif shift_sale_range.present? query = query.where("sales.shift_sale_id IN (?) and sale_status='completed'",shift_sale_range.to_a) + other_charges = other_charges.where("sales.shift_sale_id IN (?) and sale_status='completed'",shift_sale_range.to_a) discount_query = Sale.where("sales.shift_sale_id IN (?) and sale_status ='completed'", shift_sale_range.to_a).sum(:total_discount) - change_amount = Sale.where("sales.shift_sale_id IN (?) and sale_status ='completed'", shift_sale_range.to_a).sum(:amount_changed) + change_amount = Sale.where("sales.shift_sale_id IN (?) and sale_status ='completed'", shift_sale_range.to_a).sum(:amount_changed) sale_cash = Sale.select("SUM(case when (sale_payments.payment_method = 'mpu' or sale_payments.payment_method = 'visa' or sale_payments.payment_method = 'master' or sale_payments.payment_method = 'jcb' or sale_payments.payment_method = 'paypar') then (sale_payments.payment_amount) else 0 end) as card_amount, SUM(case when (sale_payments.payment_method='cash') then (sale_payments.payment_amount) else 0 end) as cash_amount, SUM(case when (sale_payments.payment_method='creditnote') then (sale_payments.payment_amount) else 0 end) as credit_amount, @@ -685,12 +723,14 @@ def self.get_by_shift_items(shift_sale_range, shift, from, to, status) total_credit_amount += s_c.credit_amount.to_f total_foc_amount += s_c.foc_amount.to_f end + total_grand_total = total_cash_amount.to_f + total_card_amount.to_f + total_credit_amount.to_f else query = query.where("sales.receipt_date between ? and ? and sale_status='completed'",from,to) + other_charges = other_charges.where("sales.receipt_date between ? and ? and sale_status='completed'",from,to) discount_query = Sale.where("sales.receipt_date between ? and ? and sale_status ='completed'", from,to).sum(:total_discount) - change_amount = Sale.where("sales.receipt_date between ? and ? and sale_status ='completed'", from,to).sum(:amount_changed) + change_amount = Sale.where("sales.receipt_date between ? and ? and sale_status ='completed'", from,to).sum(:amount_changed) sale_cash = Sale.select("SUM(case when (sale_payments.payment_method = 'mpu' or sale_payments.payment_method = 'visa' or sale_payments.payment_method = 'master' or sale_payments.payment_method = 'jcb' or sale_payments.payment_method = 'paypar') then (sale_payments.payment_amount) else 0 end) as card_amount, SUM(case when (sale_payments.payment_method='cash') then (sale_payments.payment_amount) else 0 end) as cash_amount, SUM(case when (sale_payments.payment_method='creditnote') then (sale_payments.payment_amount) else 0 end) as credit_amount, @@ -707,7 +747,7 @@ def self.get_by_shift_items(shift_sale_range, shift, from, to, status) end - return query, discount_query , total_cash_amount , total_card_amount , total_credit_amount , total_foc_amount , total_grand_total , change_amount + return query,other_charges, discount_query , total_cash_amount , total_card_amount , total_credit_amount , total_foc_amount , total_grand_total , change_amount end def self.get_shift_sales_by_receipt_no(shift_sale_range,shift,from,to,payment_type) @@ -724,23 +764,19 @@ def self.get_shift_sales_by_receipt_no(shift_sale_range,shift,from,to,payment_ty query = Sale.all if shift.present? - - query = query.where("sales.shift_sale_id in (?) #{payment_type} and sale_status= 'completed' and sale_payments.payment_amount != 0", shift.to_a) + query = query.where("sales.shift_sale_id in (?) #{payment_type} and sale_status= 'completed' and sales.payment_status= 'paid' and sale_payments.payment_amount != 0", shift.to_a) .joins("join sale_payments on sale_payments.sale_id = sales.sale_id") .group("sales.sale_id") - elsif shift_sale_range.present? - - query = query.where("sale_status='completed' #{payment_type} and sale_payments.payment_amount != 0 and sales.shift_sale_id in (?)",shift_sale_range.to_a) + query = query.where("sale_status='completed' #{payment_type} and sale_payments.payment_amount != 0 and sales.payment_status= 'paid' and sales.shift_sale_id in (?)",shift_sale_range.to_a) .joins("join sale_payments on sale_payments.sale_id = sales.sale_id") .group("sales.sale_id") - else - - query = query.where("sale_status='completed' and sales.receipt_date between ? and ? #{payment_type} and sale_payments.payment_amount != 0",from,to) + query = query.where("sale_status='completed' and sales.receipt_date between ? and ? #{payment_type} and sales.payment_status= 'paid' and sale_payments.payment_amount != 0",from,to) .joins("join sale_payments on sale_payments.sale_id = sales.sale_id") .group("sales.sale_id") end + return query end def self.get_by_shift_sale_credit_payment(shift_sale_range,shift,from,to) @@ -795,27 +831,28 @@ def self.get_separate_tax(shift_sale_range=nil,shift,from,to,payment_type) .joins("LEFT JOIN sales ON sales.sale_id = sale_taxes.sale_id") .where("sales.shift_sale_id in (?) and sale_status= 'completed'", shift.to_a) .group("sale_taxes.tax_name") - .order("sale_taxes.sale_tax_id asc") + .order("sale_taxes.tax_name desc") elsif shift_sale_range.present? query = SaleTax.select("SUM(tax_payable_amount) AS st_amount,tax_name") .joins("LEFT JOIN sales ON sales.sale_id = sale_taxes.sale_id") .where("sales.shift_sale_id in (?) and sale_status= 'completed'", shift_sale_range.to_a) .group("sale_taxes.tax_name") - .order("sale_taxes.sale_tax_id asc") + .order("sale_taxes.tax_name desc") else query = SaleTax.select("SUM(tax_payable_amount) AS st_amount,tax_name") .joins("LEFT JOIN sales ON sales.sale_id = sale_taxes.sale_id") .where("sales.receipt_date between ? and ? and sale_status= 'completed'", from,to) .group("sale_taxes.tax_name") - .order("sale_taxes.sale_tax_id asc") + .order("sale_taxes.tax_name desc") end end def self.get_payment_method_by_shift(shift_sale_range,shift,from,to,payment_type) - sale_payment = SalePayment.select("s.receipt_no, sale_payments.*,s.receipt_date as sale_date, + sale_payment = SalePayment.select("s.amount_changed as change_amount,s.receipt_no, sale_payments.*,s.receipt_date as sale_date, s.cashier_name as cashier_name") .joins("INNER JOIN sales s ON s.sale_id = sale_payments.sale_id") + .order('s.receipt_no DESC') payments_total = SalePayment.select("CAST((CONVERT_TZ(sales.receipt_date,'+00:00','+06:30')) AS DATE) as sale_date, SUM(case when (sale_payments.payment_method='mpu') then sale_payments.payment_amount else 0 end) as mpu_amount, @@ -824,6 +861,7 @@ def self.get_payment_method_by_shift(shift_sale_range,shift,from,to,payment_type SUM(case when (sale_payments.payment_method='jcb') then sale_payments.payment_amount else 0 end) as jcb_amount, SUM(case when (sale_payments.payment_method='paypar') then sale_payments.payment_amount else 0 end) as paypar_amount, SUM(case when (sale_payments.payment_method='cash') then sale_payments.payment_amount else 0 end) as cash_amount, + SUM(case when (sale_payments.payment_method='cash') then sales.amount_changed else 0 end) as total_change_amount, SUM(case when (sale_payments.payment_method='creditnote') then sale_payments.payment_amount else 0 end) as credit_amount, SUM(case when (sale_payments.payment_method='foc') then sale_payments.payment_amount else 0 end) as foc_amount") .joins("join sales on sales.sale_id = sale_payments.sale_id") @@ -875,7 +913,7 @@ end # end def grand_total_after_rounding - return self.old_grand_total.to_f + self.rounding_adjustment.to_f + return self.grand_total.to_f + self.rounding_adjustment.to_f end def get_cash_amount @@ -941,16 +979,16 @@ end def self.hourly_sales(today) query= Sale.select("grand_total") .where('payment_status="paid" and sale_status = "completed" and DATE_FORMAT(receipt_date,"%Y-%m-%d") = ?',today) - .group("date_format(receipt_date, '%I %p')") + .group("date_format(CONVERT_TZ(receipt_date,'+00:00', 'SYSTEM'), '%I %p')") + .order('receipt_date') end def self.employee_sales(today) - query = Sale.select("e.name as employee_name,grand_total") - .where('sales.payment_status="paid" and sales.sale_status = "completed" and DATE_FORMAT(sales.receipt_date,"%Y-%m-%d") = ?',today) - .joins("join employees e on e.id=sales.cashier_id") - .joins("join sale_payments sp on sp.sale_id=sales.sale_id") - .group("sp.payment_method","e.name") - .order('e.name') + query = Sale.joins("JOIN employees as e on e.id=sales.cashier_id") + .joins("JOIN sale_payments as sp on sp.sale_id=sales.sale_id") + .where("sales.payment_status='paid' and sales.sale_status = 'completed' and DATE_FORMAT(sales.receipt_date,'%Y-%m-%d') = '#{today}'") + .group("(CASE WHEN (sp.payment_method='mpu' or sp.payment_method='visa' or sp.payment_method='master' or sp.payment_method='jcb') THEN 'card' ELSE sp.payment_method END)","e.name") + .order("e.name") end def self.total_sale(today) @@ -1000,24 +1038,31 @@ end else query = query.where("sales.sale_status = 'completed' and sp.payment_method = '#{payment_method}' and DATE_FORMAT(sales.receipt_date,'%Y-%m-%d') = ?",today) end - query.sum("sp.payment_amount") + query.select("(CASE WHEN sp.payment_method='cash' THEN (SUM(sp.payment_amount) - SUM(sales.amount_changed)) ELSE SUM(sp.payment_amount) END) as payment_amount").first() end def self.total_customer(today) - query = Sale.select("count(distinct sales.customer_id) as total_cus") - .where('sales.sale_status = "completed" and DATE_FORMAT(sales.receipt_date,"%Y-%m-%d") = ?',today) - .first() + dinein_cnt = self.total_dinein(today) + takeaway_cnt = self.total_takeaway(today) + membership_cnt = self.total_membership(today) + + total_cus = 0 + if !dinein_cnt.nil? || !takeaway_cnt.nil? || !membership_cnt.nil? + total_cus = dinein_cnt.total_dinein_cus.to_int + takeaway_cnt.total_take_cus.to_int + membership_cnt.total_memb_cus.to_int + end + + return total_cus end def self.total_dinein(today) - query = Sale.select("count(distinct sales.customer_id) as total_dinein_cus") + query = Sale.select("count(sales.customer_id) as total_dinein_cus") .joins("JOIN customers as c ON c.customer_id = sales.customer_id") .where('sales.sale_status = "completed" and DATE_FORMAT(sales.receipt_date,"%Y-%m-%d") = ? and c.customer_type = "Dinein" and c.membership_id is null',today) .first() end def self.total_takeaway(today) - query = Sale.select("count(distinct sales.customer_id) as total_take_cus") + query = Sale.select("count(sales.customer_id) as total_take_cus") .joins("JOIN customers as c ON c.customer_id = sales.customer_id") .where('sales.sale_status = "completed" and DATE_FORMAT(sales.receipt_date,"%Y-%m-%d") = ? and c.customer_type = "Takeaway" and c.membership_id is null',today) .first() @@ -1026,12 +1071,12 @@ end def self.total_membership(today) 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.sale_status = "completed" and DATE_FORMAT(sales.receipt_date,"%Y-%m-%d") = ? and c.customer_type = "Takeaway" and c.membership_id is not null',today) + .where('sales.sale_status = "completed" and DATE_FORMAT(sales.receipt_date,"%Y-%m-%d") = ? and ((c.customer_type = "Dinein" and c.membership_id is not null) or (c.customer_type = "Takeaway" and c.membership_id is not null))',today) .first() end def self.total_other_customer(today) - query = Sale.select("count(distinct sales.customer_id) as total_cus") + query = Sale.select("count(sales.customer_id) as total_cus") .joins("JOIN customers as c ON c.customer_id = sales.customer_id") .where('sales.sale_status = "completed" and DATE_FORMAT(sales.receipt_date,"%Y-%m-%d") = ? and c.customer_type is null and c.membership_id is null',today) .first() @@ -1062,16 +1107,16 @@ end def self.top_items(today) 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.sale_status = 'completed' and DATE_FORMAT(sales.receipt_date,'%Y-%m-%d') = ?",today) + .where("(a.qty > 0 and a.price > 0) and payment_status='paid' and sales.sale_status = 'completed' and DATE_FORMAT(sales.receipt_date,'%Y-%m-%d') = ?",today) .group("a.product_code") - .order("SUM(a.price) DESC") + .order("SUM(a.qty) DESC") .first() end def self.total_foc_items(today) query = Sale.joins("JOIN sale_items as a ON a.sale_id = sales.sale_id") - .where("sales.sale_status = 'completed' and a.remark='foc' and DATE_FORMAT(sales.receipt_date,'%Y-%m-%d') = ?",today) - .count() + .where("sales.sale_status = 'completed' and a.remark='foc' and a.product_name not like '%FOC%' and DATE_FORMAT(sales.receipt_date,'%Y-%m-%d') = ?",today) + .sum("a.qty") end private diff --git a/app/models/sale_audit.rb b/app/models/sale_audit.rb index 3129a4a5..55541851 100755 --- a/app/models/sale_audit.rb +++ b/app/models/sale_audit.rb @@ -78,6 +78,36 @@ class SaleAudit < ApplicationRecord sale_audit.save! end + def self.record_paymal(sale_id, remark, action_by) + sale_audit = SaleAudit.new() + sale_audit.sale_id = sale_id + sale_audit.action = "PAYMAL" + sale_audit.action_at = DateTime.now.utc + sale_audit.action_by = action_by + sale_audit.remark = remark + sale_audit.approved_by = Time.now + sale_audit.save! + end + + def self.paymal_search(sale_id) + paymal = SaleAudit.where("sale_id =? and action = 'PAYMAL'",sale_id) + remark = paymal[0].remark.split("}") + response = "["+remark[0]+'}]' + response = JSON.parse(response) + puts response + if response[0]["status"] == true + if response[0]["current_rebate_amount"].present? + amount = response[0]["current_rebate_amount"] + else + amount = response[0]["current_balance_amount"] + end + else + amount = nil + end + return amount + + end + private def generate_custom_id self.sale_audit_id = SeedGenerator.generate_id(self.class.name, "SAI") diff --git a/app/models/sale_item.rb b/app/models/sale_item.rb index a757b7fd..465af104 100755 --- a/app/models/sale_item.rb +++ b/app/models/sale_item.rb @@ -27,27 +27,32 @@ class SaleItem < ApplicationRecord end def self.update_existing_item(qty, item, sale_id, type, item_price, price) - sale_item = SaleItem.new - sale_item.product_code = item.product_code - sale_item.product_name = item.product_name + "(#{type})" - sale_item.product_alt_name = item.product_alt_name - sale_item.account_id = item.account_id - sale_item.remark = type - if type == "foc" || type == "promotion" || type == "void" - sale_item.qty = qty * (-1) - else - sale_item.qty = qty - end + # Original Item to add remark + item.remark = type + item.save - sale_item.unit_price = item_price # * (-1) - sale_item.taxable_price = (price) * (-1) - sale_item.price = (price) * (-1) + sale_item = SaleItem.new + sale_item.product_code = item.product_code + sale_item.item_instance_code = item.item_instance_code + sale_item.product_name = item.product_name + " (#{type.upcase})" + sale_item.product_alt_name = item.product_alt_name + sale_item.account_id = item.account_id + sale_item.remark = type + if type == "foc" || type == "promotion" || type == "void" + sale_item.qty = qty * (-1) + else + sale_item.qty = qty + end - sale_item.is_taxable = 1 - sale_item.sale_id = sale_id - sale_item.save - sale = Sale.find(sale_id) - sale.compute_by_sale_items(sale.id, sale.sale_items, sale.total_discount) + sale_item.unit_price = item_price # * (-1) + sale_item.taxable_price = (price) * (-1) + sale_item.price = (price) * (-1) + + sale_item.is_taxable = 1 + sale_item.sale_id = sale_id + sale_item.save + sale = Sale.find(sale_id) + sale.compute_by_sale_items(sale.id, sale.sale_items, sale.total_discount) end def self.get_order_items_details(sale_id) @@ -94,9 +99,9 @@ class SaleItem < ApplicationRecord discount_account = {:name => a.title, :price => 0} # Check for actual sale items - sale_items.where("is_taxable = false AND remark = 'Discount'").find_each do |si| + sale_items.where("remark = 'Discount'").find_each do |si| if si.account_id == a.id - discount_account[:price] = (discount_account[:price].abs + si.price.abs) * (-1) + discount_account[:price] = (discount_account[:price].abs + si.price.abs) * (1) end end discount_accounts.push(discount_account) @@ -145,17 +150,6 @@ class SaleItem < ApplicationRecord return price,type end - # Check for Card Payment - def self.get_sale_payments_by_card(sale_payments) - - # Check for Card Payment - sale_payments.each do |sp| - if sp.payment_method == "jcb" || sp.payment_method == "mpu" || sp.payment_method == "visa" || sp.payment_method == "master" - return true; - end - end - - end # def self.get_overall_discount(sale_id) # price = 0.0 # item=SaleItem.where("product_code=?", sale_id) @@ -170,6 +164,5 @@ class SaleItem < ApplicationRecord private def generate_custom_id self.sale_item_id = SeedGenerator.generate_id(self.class.name, "SLI") - end end diff --git a/app/models/sale_payment.rb b/app/models/sale_payment.rb index cb6b1249..f9d16873 100755 --- a/app/models/sale_payment.rb +++ b/app/models/sale_payment.rb @@ -97,6 +97,8 @@ class SalePayment < ApplicationRecord rescue SocketError response = { status: false} end + Rails.logger.debug "Get Paypar Account " + Rails.logger.debug response.to_json return response; end @@ -151,19 +153,40 @@ class SalePayment < ApplicationRecord else response =false; end + + Rails.logger.debug "Redeem response" + Rails.logger.debug response.to_json + return response; end + # Check for Card Payment + def self.get_sale_payments_by_card(sale_payments) + # Check for Card Payment + sale_payments.each do |sp| + if sp.payment_method == "jcb" || sp.payment_method == "mpu" || sp.payment_method == "visa" || sp.payment_method == "master" + return true; + end + end + end + private def cash_payment + status = false + sale_payments_data = SalePayment.find_by_sale_id(self.sale_id) + if sale_payments_data.nil? + status = true + end + payment_status = false self.payment_method = "cash" self.payment_amount = self.received_amount self.outstanding_amount = self.sale.grand_total.to_f - self.received_amount.to_f self.payment_status = "paid" payment_method = self.save! - sale_update_payment_status(self.received_amount) + + sale_update_payment_status(self.received_amount,status) return payment_status end @@ -171,7 +194,7 @@ class SalePayment < ApplicationRecord payment_status = false # add to sale item with foc - sale_items = SaleItem.where("sale_id='#{ self.sale.sale_id }'") + sale_items = SaleItem.where("sale_id='#{ self.sale.sale_id }' and remark is null") sale_items.each do|item| SaleItem.update_existing_item(item.qty, item, self.sale.sale_id, "foc", item.unit_price, item.price) @@ -201,16 +224,14 @@ class SalePayment < ApplicationRecord return payment_status end - def external_terminal_card_payment(method) + def external_terminal_card_payment(method) payment_status = false - self.payment_method = method self.payment_amount = self.received_amount self.payment_reference = self.card_payment_reference self.outstanding_amount = self.sale.grand_total.to_f - self.received_amount.to_f self.payment_status = "paid" payment_method = self.save! - sale_update_payment_status(self.received_amount) return payment_status end @@ -255,6 +276,10 @@ class SalePayment < ApplicationRecord membership_setting = MembershipSetting.find_by_membership_type("paypar_url") membership_data = SalePayment.redeem(membership_setting.gateway_url,membership_setting.auth_token,customer_data.membership_id,self.received_amount,self.sale.sale_id) + #record an payment in sale-audit + remark = "#{membership_data} Redeem- for Customer #{self.sale.customer_id} Sale Id [#{self.sale.sale_id}]| pay amount -> #{self.received_amount} " + sale_audit = SaleAudit.record_paymal(self.sale.sale_id, remark, 1) + if membership_data["status"]==true self.payment_method = "paypar" self.payment_amount = self.received_amount @@ -272,7 +297,7 @@ class SalePayment < ApplicationRecord end - def sale_update_payment_status(paid_amount) + def sale_update_payment_status(paid_amount,check_foc = false) #update amount_outstanding self.sale.amount_received = self.sale.amount_received.to_f + paid_amount.to_f self.sale.save! @@ -305,9 +330,13 @@ class SalePayment < ApplicationRecord self.sale.sale_status = "completed" - if MembershipSetting.find_by_rebate(1) && is_foc == 0 + if MembershipSetting.find_by_rebate(1) && is_foc == 0 && is_credit == 0 response = rebat(sObj) - + + #record an payment in sale-audit + remark = "#{response} Rebate- for Customer #{self.sale.customer_id} | Sale Id [#{self.sale.sale_id}]| pay amount -> #{self.received_amount} " + sale_audit = SaleAudit.record_paymal(self.sale.sale_id, remark, 1) + if !response.nil? if response["status"] == true self.sale.rebate_status = 'true' @@ -327,8 +356,10 @@ class SalePayment < ApplicationRecord self.sale.save! table_update_status(sObj) - - if paid_amount != "0.0" + + if check_foc + update_shift + elsif paid_amount != "0.0" update_shift end end @@ -341,12 +372,18 @@ class SalePayment < ApplicationRecord shift.update(self.sale) self.sale.shift_sale_id = shift.id self.sale.save + else + shift = ShiftSale.current_shift + shift.update(self.sale) + self.sale.shift_sale_id = shift.id + self.sale.save end end def table_update_status(sale_obj) status = true booking = Booking.find_by_sale_id(sale_obj.id) + if booking table = DiningFacility.find(booking.dining_facility_id) bookings = table.bookings @@ -355,12 +392,15 @@ class SalePayment < ApplicationRecord if tablebooking.sale_id if tablebooking.sale.sale_status != 'completed' && tablebooking.sale.sale_status != 'void' status = false + else + status = true end else status = false end end end + if status table.status = "available" table.save @@ -388,6 +428,7 @@ class SalePayment < ApplicationRecord # overall_dis = SaleItem.get_overall_discount(sObj.id) overall_dis = sObj.total_discount + if credit != 1 membership = MembershipSetting.find_by_membership_type("paypar_url") memberaction = MembershipAction.find_by_membership_type("get_member_campaign") merchant_uid = memberaction.merchant_account_id.to_s @@ -416,89 +457,93 @@ class SalePayment < ApplicationRecord rescue SocketError response = { "status": false, "message": "Can't connect server"} end - redeem_amount = payparcost + overall_dis - total_percentage = 0 + redeem_amount = payparcost + overall_dis - type_arr = [] - # Check for present response fields - if response["membership_campaign_data"].present? - response["membership_campaign_data"].each do |a| - data = {:type => a["rules_type"], :percentage => a["change_unit"].to_i * a["base_unit"].to_i} - total_percentage = total_percentage + a["change_unit"].to_i * a["base_unit"].to_i - - type_arr.push(data) - end - end + total_percentage = 0 - rebate_arr =[] - campaign_method.each do |a| - data = {:type => a[:type], :amount => a[:amount]} - type_arr.each do |si| - if si[:type] == a[:type] - if credit == 1 - data[:amount] = 0 - else - amount = (redeem_amount / total_percentage)*si[:percentage] - actual = a[:amount] - amount - data[:amount] = actual - end - + type_arr = [] + Rails.logger.debug "Get Member Campaign" + Rails.logger.debug response.to_json + # Check for present response fields + if response["membership_campaign_data"].present? + response["membership_campaign_data"].each do |a| + data = {:type => a["rules_type"], :percentage => a["change_unit"].to_i * a["base_unit"].to_i} + total_percentage = total_percentage + a["change_unit"].to_i * a["base_unit"].to_i + + type_arr.push(data) end end - rebate_arr.push(data) - end - total_amount = rebate_prices - payparcost - overall_dis - - if credit == 1 - total_amount = 0 - end - if total_amount >= 0 - receipt_no = sObj.receipt_no - membership = MembershipSetting.find_by_membership_type("paypar_url") - memberaction = MembershipAction.find_by_membership_type("rebate") - merchant_uid = memberaction.merchant_account_id.to_s - campaign_type_id = memberaction.additional_parameter["campaign_type_id"] - auth_token = memberaction.auth_token.to_s - url = membership.gateway_url.to_s + memberaction.gateway_url.to_s - - # Control for Paypar Cloud - begin - response = HTTParty.post(url, - :body => { - generic_customer_id:generic_customer_id , - total_sale_transaction_amount: sObj.grand_total, - merchant_uid:merchant_uid, - total_amount: total_amount, - campaign_type_id: campaign_type_id, - receipt_no: receipt_no, - campaign_method: rebate_arr.to_json, - auth_token:auth_token - }.to_json, - :headers => { - 'Content-Type' => 'application/json', - 'Accept' => 'application/json; version=2' - }, :timeout => 10) - rescue Net::OpenTimeout - response = { "status": false , "message": "Connect To" } - rescue OpenURI::HTTPError - response = { "status": false, "message": "Can't connect server"} - - rescue SocketError - response = { "status": false, "message": "Can't connect server"} + rebate_arr =[] + campaign_method.each do |a| + data = {:type => a[:type], :amount => a[:amount]} + type_arr.each do |si| + if si[:type] == a[:type] + if credit == 1 + data[:amount] = 0 + else + amount = (redeem_amount / total_percentage)*si[:percentage] + actual = a[:amount] - amount + data[:amount] = actual + end + + end + end + rebate_arr.push(data) + end + + total_amount = rebate_prices - payparcost - overall_dis + + if credit == 1 + total_amount = 0 + end + + if total_amount >= 0 + receipt_no = sObj.receipt_no + membership = MembershipSetting.find_by_membership_type("paypar_url") + memberaction = MembershipAction.find_by_membership_type("rebate") + merchant_uid = memberaction.merchant_account_id.to_s + campaign_type_id = memberaction.additional_parameter["campaign_type_id"] + auth_token = memberaction.auth_token.to_s + url = membership.gateway_url.to_s + memberaction.gateway_url.to_s + + # Control for Paypar Cloud + begin + response = HTTParty.post(url, + :body => { + generic_customer_id:generic_customer_id , + total_sale_transaction_amount: sObj.grand_total, + merchant_uid:merchant_uid, + total_amount: total_amount, + campaign_type_id: campaign_type_id, + receipt_no: receipt_no, + campaign_method: rebate_arr.to_json, + auth_token:auth_token + }.to_json, + :headers => { + 'Content-Type' => 'application/json', + 'Accept' => 'application/json; version=2' + }, :timeout => 10) + rescue Net::OpenTimeout + response = { "status": false , "message": "Connect To" } + rescue OpenURI::HTTPError + response = { "status": false, "message": "Can't connect server"} + + rescue SocketError + response = { "status": false, "message": "Can't connect server"} + end + Rails.logger.debug "Rebage Response" + Rails.logger.debug response.to_json + return response end - return response end else - response = { "status": "no_member", "message": "Not membership"} - + response = { "status": "no_member", "message": "Not membership"} end end - - private def generate_custom_id self.sale_payment_id = SeedGenerator.generate_id(self.class.name, "SPI") diff --git a/app/models/shift_sale.rb b/app/models/shift_sale.rb index baf11cb3..57816948 100755 --- a/app/models/shift_sale.rb +++ b/app/models/shift_sale.rb @@ -52,10 +52,10 @@ class ShiftSale < ApplicationRecord self.total_taxes = self.total_taxes + saleobj.total_tax self.grand_total = self.grand_total + saleobj.grand_total self.cash_sales = self.cash_sales.to_f + cash.to_f - self.credit_sales = self.credit_sales.to_i + credit.to_f - self.other_sales = self.other_sales.to_i + other_sales.to_f - self.nett_sales = self.nett_sales + (saleobj.total_amount.to_f - self.total_discounts) #self.grand_total.to_i - self.commercial_taxes - self.commercial_taxes = self.commercial_taxes.to_i + tax.to_f + self.credit_sales = self.credit_sales.to_f + credit.to_f + self.other_sales = self.other_sales.to_f + other_sales.to_f + self.nett_sales = self.nett_sales + (saleobj.total_amount.to_f - saleobj.total_discount) #self.grand_total.to_f - self.commercial_taxes + self.commercial_taxes = self.commercial_taxes.to_f + tax.to_f self.total_rounding = self.total_rounding + saleobj.rounding_adjustment self.total_receipt = self.total_receipt + 1 if saleobj.customer.customer_type == "Dinein" @@ -79,10 +79,10 @@ class ShiftSale < ApplicationRecord self.total_taxes = self.total_taxes - saleobj.total_tax self.grand_total = self.grand_total - saleobj.grand_total self.cash_sales = self.cash_sales.to_f - cash.to_f - self.credit_sales = self.credit_sales.to_i - credit.to_f - self.other_sales = self.other_sales.to_i - other_sales.to_f + self.credit_sales = self.credit_sales.to_f - credit.to_f + self.other_sales = self.other_sales.to_f - other_sales.to_f self.nett_sales = self.nett_sales - (saleobj.total_amount.to_f - self.total_discounts) #self.grand_total.to_i - self.commercial_taxes - self.commercial_taxes = self.commercial_taxes.to_i - tax.to_f + self.commercial_taxes = self.commercial_taxes.to_f - tax.to_f self.total_rounding = self.total_rounding - saleobj.rounding_adjustment self.total_void = self.total_void + saleobj.grand_total if saleobj.customer.customer_type == "Dinein" @@ -121,7 +121,7 @@ class ShiftSale < ApplicationRecord "JOIN accounts acc ON acc.id = i.account_id" + " JOIN shift_sales sh ON sh.`id` = sales.shift_sale_id") if type == 'discount' - query = query.where("sales.shift_sale_id =? and sale_status = 'completed' and i.is_taxable = false and i.remark = 'Discount'", shift.id) + query = query.where("sales.shift_sale_id =? and sale_status = 'completed' and i.remark = 'Discount'", shift.id) .group("acc.title").order("acc.id") else query = query.where("sales.shift_sale_id =? and sale_status = 'completed'", shift.id) diff --git a/app/models/shop.rb b/app/models/shop.rb index 9e8217df..c722adc2 100755 --- a/app/models/shop.rb +++ b/app/models/shop.rb @@ -1,3 +1,3 @@ class Shop < ApplicationRecord - + ShopDetail = Shop.find_by_id(1) end diff --git a/app/pdf/call_waiter_pdf.rb b/app/pdf/call_waiter_pdf.rb new file mode 100644 index 00000000..a1ea756b --- /dev/null +++ b/app/pdf/call_waiter_pdf.rb @@ -0,0 +1,71 @@ +class CallWaiterPdf < Prawn::Document + attr_accessor :label_width,:price_column_width,:page_width, :page_height, :margin, :price_width, :item_width, :header_font_size, :item_font_size,:item_height,:qty_width,:total_width,:item_description_width + def initialize(printer_settings, table,time,shop_detail) + self.page_width = printer_settings.page_width + self.page_height = printer_settings.page_height + self.margin = 5 + self.price_width = 35 + self.qty_width = 20 + self.total_width = 35 + self.item_width = self.page_width - ((self.price_width + self.qty_width + self.total_width)) + self.item_height = 15 + self.item_description_width = (self.page_width-20) / 2 + self.label_width = 100 + + super(:margin => [self.margin, self.margin, self.margin, self.margin], :page_size => [self.page_width, self.page_height]) + + # db font setup + if printer_settings.font != "" + font_families.update("#{printer_settings.font}" => { + :normal => "public/fonts/#{printer_settings.font}.ttf", + :italic => "public/fonts/#{printer_settings.font}.ttf", + :bold => "public/fonts/#{printer_settings.font}.ttf", + :bold_italic => "public/fonts/#{printer_settings.font}.ttf" + }) + + font "#{printer_settings.font}" + fallback_fonts ["Courier", "Helvetica", "Times-Roman"] + end + + self.header_font_size = 10 + self.item_font_size = 8 + + header( shop_detail.name, printer_settings.name) + + call_waiter(table) + stroke_horizontal_rule + + # date_info(queue) + + end + + def header (shop_name, name) + text "#{shop_name}", :left_margin => -10, :size => self.header_font_size,:align => :center + text "#{name}", :size => self.header_font_size,:align => :center + # move_down self.item_height + move_down 5 + stroke_horizontal_rule + move_down 5 + end + + def call_waiter (table) + move_down 3 + text "Table Name : #{table.name}",:align => :center + end + + # def date_info(queue) + # move_down 5 + + # y_position = cursor + # bounding_box([0,y_position], :width =>self.label_width, :height => self.item_height) do + # text "Date:", :size => self.item_font_size,:align => :left + # end + # bounding_box([self.label_width,y_position], :width => self.item_width) do + # text "#{queue.created_at.strftime('%Y-%m-%d %I:%M %p')}" , :size => self.item_font_size,:align => :left + # end + + # move_down 5 + + # end + +end diff --git a/app/pdf/close_cashier_pdf.rb b/app/pdf/close_cashier_pdf.rb index 1f456a07..93cd7ab9 100755 --- a/app/pdf/close_cashier_pdf.rb +++ b/app/pdf/close_cashier_pdf.rb @@ -5,7 +5,7 @@ class CloseCashierPdf < Prawn::Document self.page_width = printer_settings.page_width #PrintSetting.where("name = ?","Close Cashier").first.page_width self.page_height = printer_settings.page_height self.margin = 5 - self.price_width = 40 + self.price_width = 60 self.qty_width = 20 self.total_width = 40 self.item_width = self.page_width - ((self.price_width + self.qty_width + self.total_width)) @@ -133,7 +133,6 @@ class CloseCashierPdf < Prawn::Document text "#{shift_sale.cash_in}", :size => self.item_font_size, :align => :right end - y_position = cursor bounding_box([0,y_position], :width =>self.item_description_width, :height => 20) do text "Cash Out:", :size => self.item_font_size, :align => :right @@ -142,26 +141,11 @@ class CloseCashierPdf < Prawn::Document text "#{shift_sale.cash_out}", :size => self.item_font_size, :align => :right end - y_position = cursor - bounding_box([0,y_position], :width =>self.item_description_width, :height => 20) do - text "Net Sales:", :size => self.item_font_size, :align => :right - end - bounding_box([self.item_description_width,y_position], :width =>self.price_width, :height => 20) do - text "#{shift_sale.nett_sales}", :size => self.item_font_size, :align => :right - end - - y_position = cursor - bounding_box([0,y_position], :width =>self.item_description_width, :height => 20) do - text "Total Tax :", :size => self.item_font_size, :align => :right - end - bounding_box([self.item_description_width,y_position], :width =>self.price_width, :height => 20) do - text "#{shift_sale.total_taxes}", :size => self.item_font_size, :align => :right - end - move_down -5 stroke_horizontal_rule move_down 7 + @total_foc = 0 y_position = cursor bounding_box([0,y_position], :width =>self.item_description_width, :height => 20) do text "Cash Payment :", :size => self.item_font_size, :align => :right @@ -180,14 +164,7 @@ class CloseCashierPdf < Prawn::Document #start other payment details if shift_sale.other_sales > 0 other_payment.each do |other| - y_position = cursor - bounding_box([0,y_position], :width =>self.item_description_width, :height => 20) do - text "Other Payment Details", :size => self.item_font_size, :align => :right - end - bounding_box([self.item_description_width,y_position], :width =>self.price_width, :height => 20) do - text "", :size => self.item_font_size, :align => :right - end - + @total_foc = other.foc_amount.round(2) y_position = cursor bounding_box([0,y_position], :width =>self.item_description_width, :height => 20) do text "MPU Payment :", :size => self.item_font_size, :align => :right @@ -204,14 +181,6 @@ class CloseCashierPdf < Prawn::Document text "#{other.visa_amount.round(2)}", :size => self.item_font_size, :align => :right end - y_position = cursor - bounding_box([0,y_position], :width =>self.item_description_width, :height => 20) do - text "JCB Payment :", :size => self.item_font_size, :align => :right - end - bounding_box([self.item_description_width,y_position], :width =>self.price_width, :height => 20) do - text "#{other.jcb_amount.round(2)}", :size => self.item_font_size, :align => :right - end - y_position = cursor bounding_box([0,y_position], :width =>self.item_description_width, :height => 20) do text "Master Payment :", :size => self.item_font_size, :align => :right @@ -220,6 +189,14 @@ class CloseCashierPdf < Prawn::Document text "#{other.master_amount.round(2)}", :size => self.item_font_size, :align => :right end + y_position = cursor + bounding_box([0,y_position], :width =>self.item_description_width, :height => 20) do + text "JCB Payment :", :size => self.item_font_size, :align => :right + end + bounding_box([self.item_description_width,y_position], :width =>self.price_width, :height => 20) do + text "#{other.jcb_amount.round(2)}", :size => self.item_font_size, :align => :right + end + y_position = cursor bounding_box([0,y_position], :width =>self.item_description_width, :height => 20) do text "Reedem Payment :", :size => self.item_font_size, :align => :right @@ -227,15 +204,6 @@ class CloseCashierPdf < Prawn::Document bounding_box([self.item_description_width,y_position], :width =>self.price_width, :height => 20) do text "#{other.paypar_amount.round(2)}", :size => self.item_font_size, :align => :right end - - y_position = cursor - bounding_box([0,y_position], :width =>self.item_description_width, :height => 20) do - text "FOC :", :size => self.item_font_size, :align => :right - end - bounding_box([self.item_description_width,y_position], :width =>self.price_width, :height => 20) do - text "#{other.foc_amount.round(2)}", :size => self.item_font_size, :align => :right - end - end else y_position = cursor @@ -247,30 +215,63 @@ class CloseCashierPdf < Prawn::Document end end + y_position = cursor + bounding_box([0,y_position], :width =>self.item_description_width, :height => 20) do + text "Rounding Adjustments :", :size => self.item_font_size, :align => :right + end + bounding_box([self.item_description_width,y_position], :width =>self.price_width, :height => 20) do + text "#{shift_sale.total_rounding.round(2)}", :size => self.item_font_size, :align => :right + end + + y_position = cursor + bounding_box([0,y_position], :width =>self.item_description_width, :height => 20) do + text "Total :", :style => :bold, :size => self.header_font_size - 1, :align => :right + end + bounding_box([self.item_description_width,y_position], :width =>self.price_width, :height => 20) do + text "#{shift_sale.grand_total.round(2)}", :style => :bold, :size => self.header_font_size - 1, :align => :right + end + # end other payment details move_down -5 stroke_horizontal_rule move_down 7 - #start total amount by Account Like Food / Beverage /.. - total_amount_by_account.each do |amount| + + #start service charges and commercial tax + sale_taxes.each do |tax| y_position = cursor bounding_box([0,y_position], :width =>self.item_description_width, :height => 20) do - text "Total #{amount.account_name} Amount:", :size => self.item_font_size, :align => :right + text "#{tax.tax_name} :", :size => self.item_font_size, :align => :right end bounding_box([self.item_description_width,y_position], :width =>self.price_width, :height => 20) do - text "#{amount.total_price.round(2)} ", :size => self.item_font_size, :align => :right + text "#{tax.st_amount.round(2)}", :size => self.item_font_size, :align => :right end end - #end total amount by Account y_position = cursor bounding_box([0,y_position], :width =>self.item_description_width, :height => 20) do - text "Total Sale :", :size => self.item_font_size, :align => :right + text "Total Taxes :", :size => self.item_font_size, :align => :right end bounding_box([self.item_description_width,y_position], :width =>self.price_width, :height => 20) do - text "#{shift_sale.total_revenue}", :size => self.item_font_size, :align => :right + text "#{shift_sale.total_taxes}", :size => self.item_font_size, :align => :right end + y_position = cursor + bounding_box([0,y_position], :width =>self.item_description_width, :height => 20) do + text "Net Sales :", :style => :bold, :size => self.header_font_size - 1, :align => :right + end + bounding_box([self.item_description_width,y_position], :width =>self.price_width, :height => 20) do + text "#{shift_sale.nett_sales}", :style => :bold , :size => self.header_font_size - 1, :align => :right + end + #end for service charges and commercial tax +#COMMENTED FOR NO NEED AND NOT CORRECT WHEN OTHER CHARGES + # y_position = cursor + # bounding_box([0,y_position], :width =>self.item_description_width, :height => 20) do + # text "Total Sale :", :size => self.item_font_size, :align => :right + # end + # bounding_box([self.item_description_width,y_position], :width =>self.price_width, :height => 20) do + # text "#{shift_sale.total_revenue}", :size => self.item_font_size, :align => :right + # end + move_down -5 stroke_horizontal_rule move_down 7 @@ -304,47 +305,66 @@ class CloseCashierPdf < Prawn::Document y_position = cursor bounding_box([0,y_position], :width =>self.item_description_width, :height => 20) do - text "Total Overall Discount :", :size => self.item_font_size, :align => :right + text "Total Discount :", :size => self.item_font_size, :align => :right end bounding_box([self.item_description_width,y_position], :width =>self.price_width, :height => 20) do text "#{@overall}", :size => self.item_font_size, :align => :right + end + + y_position = cursor + bounding_box([0,y_position], :width =>self.item_description_width, :height => 20) do + text "Total FOC :", :size => self.item_font_size, :align => :right + end + bounding_box([self.item_description_width,y_position], :width =>self.price_width, :height => 20) do + text "(#{@total_foc})", :size => self.item_font_size, :align => :right end y_position = cursor bounding_box([0,y_position], :width =>self.item_description_width, :height => 20) do - text "Total Discount Amount :", :size => self.item_font_size, :align => :right + text "Total Void :", :size => self.item_font_size, :align => :right end bounding_box([self.item_description_width,y_position], :width =>self.price_width, :height => 20) do - text "#{shift_sale.total_discounts}", :size => self.item_font_size, :align => :right + text "(#{shift_sale.total_void})", :size => self.item_font_size, :align => :right end + + # y_position = cursor + # bounding_box([0,y_position], :width =>self.item_description_width, :height => 20) do + # text "Grand Total :", :size => self.item_font_size, :align => :right + # end + # bounding_box([self.item_description_width,y_position], :width =>self.price_width, :height => 20) do + # text "#{shift_sale.grand_total}", :size => self.item_font_size, :align => :right + # end move_down -5 stroke_horizontal_rule move_down 7 - sale_taxes.each do |tax| - + #start total amount by Account Like Food / Beverage /.. + total_amount_by_account.each do |amount| y_position = cursor bounding_box([0,y_position], :width =>self.item_description_width, :height => 20) do - text "#{tax.tax_name} :", :size => self.item_font_size, :align => :right + text "Total #{amount.account_name} Amount :", :size => self.item_font_size, :align => :right end bounding_box([self.item_description_width,y_position], :width =>self.price_width, :height => 20) do - text "#{tax.st_amount.round(2)}", :size => self.item_font_size, :align => :right + text "#{amount.total_price.round(2)} ", :size => self.item_font_size, :align => :right end end + #end total amount by Account + y_position = cursor bounding_box([0,y_position], :width =>self.item_description_width, :height => 20) do - text "Rounding Adjustment :", :size => self.item_font_size, :align => :right + text "Total Dine-in Count :", :size => self.item_font_size, :align => :right end bounding_box([self.item_description_width,y_position], :width =>self.price_width, :height => 20) do - text "#{shift_sale.total_rounding.round(2)}", :size => self.item_font_size, :align => :right + text "#{shift_sale.dining_count}", :size => self.item_font_size, :align => :right end - y_position = cursor + + y_position = cursor bounding_box([0,y_position], :width =>self.item_description_width, :height => 20) do - text "Grand Total :", :size => self.item_font_size, :align => :right + text "Total Takeaway Count :", :size => self.item_font_size, :align => :right end bounding_box([self.item_description_width,y_position], :width =>self.price_width, :height => 20) do - text "#{shift_sale.grand_total}", :size => self.item_font_size, :align => :right + text "#{shift_sale.takeaway_count}", :size => self.item_font_size, :align => :right end y_position = cursor @@ -355,31 +375,7 @@ class CloseCashierPdf < Prawn::Document text "#{shift_sale.total_receipt}", :size => self.item_font_size, :align => :right end - y_position = cursor - bounding_box([0,y_position], :width =>self.item_description_width, :height => 20) do - text "Dining Count :", :size => self.item_font_size, :align => :right - end - bounding_box([self.item_description_width,y_position], :width =>self.price_width, :height => 20) do - text "#{shift_sale.dining_count}", :size => self.item_font_size, :align => :right - end - - y_position = cursor - bounding_box([0,y_position], :width =>self.item_description_width, :height => 20) do - text "Takeaway Count :", :size => self.item_font_size, :align => :right - end - bounding_box([self.item_description_width,y_position], :width =>self.price_width, :height => 20) do - text "#{shift_sale.takeaway_count}", :size => self.item_font_size, :align => :right - end - - y_position = cursor - bounding_box([0,y_position], :width =>self.item_description_width, :height => 20) do - text "Total Void:", :size => self.item_font_size, :align => :right - end - bounding_box([self.item_description_width,y_position], :width =>self.price_width, :height => 20) do - text "(#{shift_sale.total_void})", :size => self.item_font_size, :align => :right - end - - move_down 5 + move_down 5 stroke_horizontal_rule move_down 5 move_down 5 diff --git a/app/pdf/order_item_pdf.rb b/app/pdf/order_item_pdf.rb index 4bc57878..e9887c62 100755 --- a/app/pdf/order_item_pdf.rb +++ b/app/pdf/order_item_pdf.rb @@ -40,7 +40,7 @@ class OrderItemPdf < Prawn::Document text "#{ order_item.type + '-' + order_item.dining + print_status }", :size => self.header_font_size,:align => :center, :left_margin => -20 stroke_horizontal_rule - move_down 5 + move_down 3 #order_info order_info(order_item.order_id, order_item.order_by,order_item.order_at) @@ -56,13 +56,13 @@ class OrderItemPdf < Prawn::Document text "OrderNo: #{order_no} ", :size => self.item_font_size,:align => :left end - move_down 5 + move_down 2 y_position = cursor bounding_box([0,y_position], :width => self.item_width, :height => self.item_height) do text "OrderBy: #{order_by} ", :size => self.item_font_size,:align => :left end - move_down 5 + move_down 2 y_position = cursor bounding_box([0,y_position], :width => self.item_width, :height => self.item_height) do text "Date: #{order_at.utc.getlocal.strftime("%Y-%m-%d %I:%M %p")}", :size => self.item_font_size,:align => :left @@ -105,18 +105,22 @@ class OrderItemPdf < Prawn::Document end if alt_name - move_down 4 - font("public/fonts/NotoSansCJKtc-Regular.ttf") do - text "(#{order_item.alt_name})", :size => self.item_font_size,:align => :left, :inline_format => true + if !(order_item.alt_name).empty? + move_down 4 + font("public/fonts/NotoSansCJKtc-Regular.ttf") do + text "(#{order_item.alt_name})", :size => self.item_font_size,:align => :left, :inline_format => true + end end end - move_down 5 + if !options.empty? + move_down 5 - # add option - y_position = cursor - bounding_box([0,y_position], :width => self.item_width, :height => self.item_height) do - text "#{options}", :size => self.item_font_size,:align => :left + # add option + y_position = cursor + bounding_box([0,y_position], :width => self.item_width, :height => self.item_height) do + text "#{options}", :size => self.item_font_size,:align => :left + end end move_down 5 diff --git a/app/pdf/order_item_slim_pdf.rb b/app/pdf/order_item_slim_pdf.rb new file mode 100644 index 00000000..6887d201 --- /dev/null +++ b/app/pdf/order_item_slim_pdf.rb @@ -0,0 +1,129 @@ +class OrderItemSlimPdf < Prawn::Document + include ActionView::Helpers::NumberHelper + attr_accessor :label_width,:price_column_width,:page_width, :page_height, :margin, :price_width, :item_width, :header_font_size, :item_font_size,:item_height,:qty_width,:total_width,:item_description_width + def initialize(print_settings,order_item_slim, print_status, options, alt_name) + self.page_width = print_settings.page_width + self.page_height = print_settings.page_height + self.margin = 0 + self.price_width = 40 # No Need for item + self.qty_width = 40 + self.total_width = 40 # No Need for item + self.item_width = self.page_width - (self.qty_width - self.margin) + self.item_height = 15 + self.item_description_width = self.page_width - (self.price_width + self.qty_width + self.total_width) + self.label_width=90 + + super(:margin => [print_settings.heading_space, self.margin, self.margin, self.margin], :page_size => [self.page_width, self.page_height]) + # super(:margin => [10, 5, 30, 5], :page_size => [200,400]) + + # db font setup + if print_settings.font != "" + font_families.update("#{print_settings.font}" => { + :normal => "public/fonts/#{print_settings.font}.ttf", + :italic => "public/fonts/#{print_settings.font}.ttf", + :bold => "public/fonts/#{print_settings.font}.ttf", + :bold_italic => "public/fonts/#{print_settings.font}.ttf" + }) + + font "#{print_settings.font}" + fallback_fonts ["Courier", "Helvetica", "Times-Roman"] + + self.header_font_size = 11 + self.item_font_size = 9 + else + self.header_font_size = 12 + self.item_font_size = 10 + end + # font "public/fonts/Zawgyi-One.ttf" + # font "public/fonts/padauk.ttf" + #font "public/fonts/Chinese.ttf" + + text "#{ order_item_slim.type + '-' + order_item_slim.dining + print_status }", :size => self.header_font_size,:align => :center, :left_margin => -20 + stroke_horizontal_rule + move_down 1 + + #order_info + order_info(order_item_slim.order_id, order_item_slim.order_by,order_item_slim.order_at) + + # order items slim + order_items_slim(order_item_slim, options, alt_name, print_settings.precision) + end + + # Write Order Information to PDF + def order_info(order_no, order_by, order_at) + y_position = cursor + bounding_box([0,y_position], :width => self.item_width, :height => self.item_height) do + text "OrderNo: #{order_no} ", :size => self.item_font_size,:align => :left + end + + move_down 1 + y_position = cursor + bounding_box([0,y_position], :width => self.item_width, :height => self.item_height) do + text "OrderBy: #{order_by} ", :size => self.item_font_size,:align => :left + end + + move_down 1 + y_position = cursor + bounding_box([0,y_position], :width => self.item_width, :height => self.item_height) do + text "Date: #{order_at.utc.getlocal.strftime("%Y-%m-%d %I:%M %p")}", :size => self.item_font_size,:align => :left + end + + stroke_horizontal_rule + + move_down 3 + end + + # Write Order items to PDF + def order_items_slim(order_item_slim, options, alt_name, precision) + y_position = cursor + + #Add Order Item + add_order_items_slim(order_item_slim, options, alt_name, precision) + + dash(1, :space => 1, :phase => 1) + stroke_horizontal_line 0, (self.page_width - self.margin) + move_down 1 + end + + # Add order items slim under order info + def add_order_items_slim(order_item_slim, options, alt_name, precision) + y_position = cursor + + move_down 1 + + bounding_box([0,y_position], :width => self.item_width) do + text "#{order_item_slim.item_name}", :size => self.item_font_size,:align => :left + end + + bounding_box([self.item_width,y_position], :width => self.qty_width) do + text "[#{number_with_precision(order_item_slim.qty.to_i, :precision => precision.to_i)}]", :size => self.item_font_size,:align => :left + end + + bounding_box([0,y_position], :width => self.item_width) do + text "#{order_item_slim.item_name}", :size => self.item_font_size,:align => :left + + end + + # if alt_name + # if !(order_item_slim.alt_name).empty? + # move_down 1 + # font("public/fonts/NotoSansCJKtc-Regular.ttf") do + # text "(#{order_item_slim.alt_name})", :size => self.item_font_size,:align => :left, :inline_format => true + # end + # end + # end + + if !options.empty? + move_down 1 + + # add option + y_position = cursor + bounding_box([0,y_position], :width => self.item_width, :height => self.item_height) do + text "#{options}", :size => self.item_font_size,:align => :left + end + end + move_down 1 + + end + +end diff --git a/app/pdf/order_summary_pdf.rb b/app/pdf/order_summary_pdf.rb index ea0d4502..f48564a9 100755 --- a/app/pdf/order_summary_pdf.rb +++ b/app/pdf/order_summary_pdf.rb @@ -122,19 +122,21 @@ class OrderSummaryPdf < Prawn::Document end if alt_name - move_down 4 - font("public/fonts/NotoSansCJKtc-Regular.ttf") do - text "(#{odi.alt_name})", :size => self.item_font_size,:align => :left, :inline_format => true + if !(odi.alt_name).empty? + move_down 4 + font("public/fonts/NotoSansCJKtc-Regular.ttf") do + text "(#{odi.alt_name})", :size => self.item_font_size,:align => :left, :inline_format => true + end end end - move_down 5 - # add option options = odi.options == "[]"? "" : odi.options if options != "" + move_down 5 + y_position = cursor bounding_box([0,y_position], :width => self.item_width) do text "#{options}", :size => self.item_font_size,:align => :left diff --git a/app/pdf/order_summary_slim_pdf.rb b/app/pdf/order_summary_slim_pdf.rb new file mode 100644 index 00000000..87aba403 --- /dev/null +++ b/app/pdf/order_summary_slim_pdf.rb @@ -0,0 +1,155 @@ +class OrderSummarySlimPdf < Prawn::Document + include ActionView::Helpers::NumberHelper + attr_accessor :label_width,:price_column_width,:page_width, :page_height, :margin, :price_width, :item_width, :header_font_size, :item_font_size,:item_height,:qty_width,:total_width,:item_description_width + def initialize(print_settings,order, print_status, order_items = nil,alt_name) + self.page_width = print_settings.page_width + self.page_height = print_settings.page_height + self.margin = 0 + self.price_width = 40 # No Need for item + self.qty_width = 40 + self.total_width = 40 # No Need for item + self.item_width = self.page_width - (self.qty_width - self.margin) + self.item_height = 15 + self.item_description_width = self.page_width - (self.price_width + self.qty_width + self.total_width) + self.label_width=90 + + super(:margin => [print_settings.heading_space, self.margin, self.margin, self.margin], :page_size => [self.page_width, self.page_height]) + + # db font setup + if print_settings.font != "" + font_families.update("#{print_settings.font}" => { + :normal => "public/fonts/#{print_settings.font}.ttf", + :italic => "public/fonts/#{print_settings.font}.ttf", + :bold => "public/fonts/#{print_settings.font}.ttf", + :bold_italic => "public/fonts/#{print_settings.font}.ttf" + }) + + font "#{print_settings.font}" + fallback_fonts ["Courier", "Helvetica", "Times-Roman"] + + self.header_font_size = 11 + self.item_font_size = 9 + else + self.header_font_size = 12 + self.item_font_size = 10 + end + + # font "public/fonts/Zawgyi-One.ttf" + # font "public/fonts/padauk.ttf" + + text "#{ order[0].type + '-' + order[0].dining + print_status }", :size => self.header_font_size,:align => :center, :left_margin => -20 + stroke_horizontal_rule + move_down 1 + + #order_info + order_info(order[0].order_id, order[0].order_by,order[0].order_at) + + # order items + if order_items == nil + order_items(order, alt_name, print_settings.precision) + else + order_items(order_items, alt_name, print_settings.precision) + end + end + + # Write Order Information to PDF + def order_info(order_no, order_by, order_at) + y_position = cursor + bounding_box([0,y_position], :width => self.item_width, :height => self.item_height) do + text "OrderNo: #{order_no} ", :size => self.item_font_size,:align => :left + end + + move_down 1 + y_position = cursor + bounding_box([0,y_position], :width => self.item_width, :height => self.item_height) do + text "OrderBy: #{order_by} ", :size => self.item_font_size,:align => :left + end + + move_down 1 + y_position = cursor + bounding_box([0,y_position], :width => self.item_width, :height => self.item_height) do + text "Date: #{order_at.utc.getlocal.strftime("%Y-%m-%d %I:%M %p")}", :size => self.item_font_size,:align => :left + end + + stroke_horizontal_rule + + move_down 1 + end + + # Write Order items to PDF + def order_items(order_item, alt_name, precision) + y_position = cursor + + bounding_box([0,y_position], :width => self.item_width, :height => self.item_height) do + text "Item", :size => self.item_font_size,:align => :left + end + + bounding_box([self.item_width,y_position], :width => self.qty_width, :height => self.item_height) do + text "Qty", :size => self.item_font_size,:align => :left + end + + stroke_horizontal_rule + move_down 1 + + #Add Order Item + add_order_items(order_item, alt_name, precision) + + end + + # Add order items under order info + def add_order_items(order_item, alt_name, precision) + y_position = cursor + + move_down 1 + + order_item.each do|odi| + # check for item not to show + # if odi.price != 0 + y_position = cursor + + bounding_box([0,y_position], :width => self.item_width) do + text "#{odi.item_name}", :size => self.item_font_size,:align => :left + + end + + bounding_box([self.item_width,y_position], :width => self.qty_width) do + text "#{number_with_precision(odi.qty, :precision => precision.to_i)}", :size => self.item_font_size,:align => :left + end + + bounding_box([0,y_position], :width => self.item_width) do + text "#{odi.item_name}", :size => self.item_font_size,:align => :left + + end + + if alt_name + if !(odi.alt_name).empty? + move_down 1 + font("public/fonts/NotoSansCJKtc-Regular.ttf") do + text "(#{odi.alt_name})", :size => self.item_font_size,:align => :left, :inline_format => true + end + end + end + + # add option + options = odi.options == "[]"? "" : odi.options + + if options != "" + move_down 1 + + y_position = cursor + bounding_box([0,y_position], :width => self.item_width) do + text "#{options}", :size => self.item_font_size,:align => :left + end + + move_down 1 + end + + move_down 1 + + dash(1, :space => 1, :phase => 1) + stroke_horizontal_line 0, (self.page_width - self.margin) + move_down 1 + # end + end + end +end diff --git a/app/pdf/receipt_bill_pdf.rb b/app/pdf/receipt_bill_pdf.rb index ebdfa147..ae02b22d 100755 --- a/app/pdf/receipt_bill_pdf.rb +++ b/app/pdf/receipt_bill_pdf.rb @@ -1,16 +1,16 @@ class ReceiptBillPdf < Prawn::Document include ActionView::Helpers::NumberHelper attr_accessor :label_width,:price_column_width,:page_width, :page_height, :margin, :price_width, :item_width, :header_font_size, :item_font_size,:item_height,:qty_width,:total_width,:item_description_width, :description_width, :price_num_width - def initialize(printer_settings, sale_items, sale_data, customer_name, item_price_by_accounts, discount_price_by_accounts, member_info = nil,rebate_amount = nil,shop_details, printed_status) + def initialize(printer_settings, sale_items, sale_data, customer_name, item_price_by_accounts, discount_price_by_accounts, member_info = nil,rebate_amount = nil,shop_details, printed_status,current_balance) self.page_width = printer_settings.page_width self.page_height = printer_settings.page_height - self.margin = 5 - self.price_width = 40 - self.qty_width = 20 - self.total_width = 40 - self.item_width = self.page_width - ((self.price_width + self.qty_width + self.total_width)) + self.margin = 0 + self.price_width = 60 + self.qty_width = 25 + self.total_width = 60 + self.item_width = self.page_width - ((self.qty_width + self.price_width + self.total_width)) self.item_height = 15 - self.item_description_width = (self.page_width-20) / 2 + self.item_description_width = (self.page_width-5) / 2 self.label_width = 100 self.description_width = 150 @@ -22,6 +22,11 @@ class ReceiptBillPdf < Prawn::Document #setting page margin and width super(:margin => [printer_settings.heading_space, self.margin, self.margin, self.margin], :page_size => [self.page_width, self.page_height]) + #precision checked + if printer_settings.precision.to_i > 2 + printer_settings.precision = 2 + end + # db font setup if printer_settings.font != "" font_families.update("#{printer_settings.font}" => { @@ -55,7 +60,7 @@ class ReceiptBillPdf < Prawn::Document if member_info != nil - member_info(member_info,customer_name,rebate_amount,sale_data,printer_settings.precision,delimiter) + member_info(member_info,customer_name,rebate_amount,sale_data,printer_settings.precision,delimiter,current_balance) end customer(customer_name) @@ -74,7 +79,7 @@ class ReceiptBillPdf < Prawn::Document end def header (shop_details) - move_down 7 + move_down 5 text "#{shop_details.name}", :left_margin => -10, :size => self.header_font_size,:align => :center move_down 5 text "#{shop_details.address}", :size => self.item_font_size,:align => :center @@ -124,15 +129,27 @@ class ReceiptBillPdf < Prawn::Document end def line_items(sale_items,precision,delimiter) + if precision.to_i > 0 + item_label_qty_front_width = (self.item_width+self.price_width) + 5 + item_label_qty_end_width = self.qty_width + 4 + item_label_total_front_width = (self.item_width+self.price_width) + 10 + item_label_total_end_width = self.total_width + 9 + else + self.item_width = self.item_width.to_i + 8 + item_label_qty_front_width = (self.item_width+self.price_width) + 8 + item_label_qty_end_width = self.qty_width + 7 + item_label_total_front_width = (self.item_width+self.price_width) + 5 + item_label_total_end_width = self.total_width + 4 + end move_down 5 y_position = cursor move_down 5 pad_top(15) { # @item_width.to_i + @half_qty.to_i text_box "Items", :at =>[0,y_position], :width => self.item_width, :height =>self.item_height, :size => self.item_font_size, :overflow => :shrink_to_fix - text_box "Price", :at =>[self.item_width,y_position], :width => self.price_width, :height =>self.item_height, :size => self.item_font_size, :align => :right, :overflow => :shrink_to_fix - text_box "Qty", :at =>[(self.item_width+self.price_width),y_position], :width => self.qty_width, :height =>self.item_height, :size => self.item_font_size, :align => :center, :overflow => :shrink_to_fix - text_box "Total", :at =>[(self.item_width+self.price_width+4),y_position], :width => self.total_width+3, :height =>self.item_height, :size => self.item_font_size, :align => :right, :overflow => :shrink_to_fix + text_box "Price", :at =>[(self.item_width),y_position], :width => self.price_width, :height =>self.item_height, :size => self.item_font_size, :align => :right, :overflow => :shrink_to_fix + text_box "Qty", :at =>[item_label_qty_front_width,y_position], :width => item_label_qty_end_width, :height =>self.item_height, :size => self.item_font_size, :align => :center, :overflow => :shrink_to_fix + text_box "Total", :at =>[item_label_total_front_width,y_position], :width => item_label_total_end_width, :height =>self.item_height, :size => self.item_font_size, :align => :right, :overflow => :shrink_to_fix } move_down -5 stroke_horizontal_rule @@ -140,7 +157,19 @@ class ReceiptBillPdf < Prawn::Document end def add_line_item_row(sale_items,precision,delimiter) - item_name_width = (self.item_width+self.price_width) + if precision.to_i > 0 + item_name_width = (self.item_width+self.price_width) + item_qty_front_width = (self.item_width+self.price_width) + 5 + item_qty_end_width = self.qty_width + 4 + item_total_front_width = item_name_width + 10 + item_total_end_width = self.total_width + 9 + else + item_name_width = (self.item_width+self.price_width) + item_qty_front_width = item_name_width + 8 + item_qty_end_width = self.qty_width + 7 + item_total_front_width = item_name_width + 5 + item_total_end_width = self.total_width + 4 + end y_position = cursor move_down 5 sub_total = 0.0 @@ -162,8 +191,8 @@ class ReceiptBillPdf < Prawn::Document end # text_box "#{product_name}", :at =>[0,y_position], :width => self.item_width, :size => self.item_font_size text_box "#{number_with_precision(price, :precision => precision.to_i, :delimiter => delimiter)}", :at =>[self.item_width,y_position], :width => self.price_width, :size => self.item_font_size, :align => :right, :overflow => :shrink_to_fix - text_box "#{number_with_precision(qty, :precision => precision.to_i)}", :at =>[item_name_width,y_position], :width => self.qty_width, :size => self.item_font_size, :align => :center, :overflow => :shrink_to_fix - text_box "#{number_with_precision(total_price, :precision => precision.to_i, :delimiter => delimiter)}", :at =>[(item_name_width+4),y_position], :width =>self.total_width+3, :size => self.item_font_size, :align => :right, :overflow => :shrink_to_fix + text_box "#{number_with_precision(qty, :precision => precision.to_i)}", :at =>[item_qty_front_width,y_position], :width => item_qty_end_width, :size => self.item_font_size, :align => :center, :overflow => :shrink_to_fix + text_box "#{number_with_precision(total_price, :precision => precision.to_i, :delimiter => delimiter)}", :at =>[item_total_front_width,y_position], :width =>item_total_end_width, :size => self.item_font_size, :align => :right, :overflow => :shrink_to_fix } move_down 5 end @@ -254,7 +283,8 @@ class ReceiptBillPdf < Prawn::Document def sale_payment(sale_data,precision,delimiter) stroke_horizontal_rule move_down 5 - SalePayment.where('sale_id = ?', sale_data.sale_id).each do |payment| + sale_payments = SalePayment.select("SUM(sale_payments.payment_amount) as payment_amount,sale_payments.payment_method").where('sale_id = ?', sale_data.sale_id).group("payment_method") + sale_payments.each do |payment| y_position = cursor if payment.payment_method == "paypar" bounding_box([0,y_position], :width =>self.item_description_width, :height => self.item_height) do @@ -285,7 +315,7 @@ class ReceiptBillPdf < Prawn::Document end # show member information - def member_info(member_info,customer_name,rebate_amount,sale_data,precision,delimiter) + def member_info(member_info,customer_name,rebate_amount,sale_data,precision,delimiter,current_balance) if rebate_amount != nil if rebate_amount["status"] == true stroke_horizontal_rule @@ -293,6 +323,7 @@ class ReceiptBillPdf < Prawn::Document balance = 0 rebate_balance =0 redeem = 0 + redeem_count = 0 rebate_amount["data"].each do |res| total = total + res["balance"] #total redeem amount @@ -317,7 +348,7 @@ class ReceiptBillPdf < Prawn::Document end # Total Rebate Amount if birthday - if res["receipt_no"]== sale_data.receipt_no && res["account_status"]== "RebateBonusAccount" && res["status"]== "Rebate" + if res["receipt_no"]== sale_data.receipt_no && res["account_status"]== "RebatebonusAccount" && res["status"]== "Rebate" rebate_balance = rebate_balance + res["deposit"] move_down 5 y_position = cursor @@ -331,29 +362,24 @@ class ReceiptBillPdf < Prawn::Document #end Total rebate if birthday end - move_down 5 - y_position = cursor - bounding_box([0,y_position], :width =>self.item_description_width, :height => self.item_height) do - text "Redeem Amount", :size => self.item_font_size,:align => :left - end - bounding_box([self.item_description_width,y_position], :width =>self.label_width) do - text "#{number_with_precision(redeem, :precision => precision.to_i, :delimiter => delimiter)}", :size => self.item_font_size,:align => :right - end - - - if redeem == 0 - old = total - rebate_balance - else - old = balance + redeem - end - move_down 5 y_position = cursor - bounding_box([0,y_position], :width =>self.item_description_width, :height => self.item_height) do - text "Old Balance", :size => self.item_font_size,:align => :left - end + bounding_box([0,y_position], :width =>self.item_description_width, :height => self.item_height) do + text "Redeem Amount", :size => self.item_font_size,:align => :left + end bounding_box([self.item_description_width,y_position], :width =>self.label_width) do - text "#{number_with_precision(old, :precision => precision.to_i, :delimiter => delimiter)}", :size => self.item_font_size,:align => :right + text "#{number_with_precision(redeem, :precision => precision.to_i, :delimiter => delimiter)}", :size => self.item_font_size,:align => :right + end + + if current_balance != nil + move_down 5 + y_position = cursor + bounding_box([0,y_position], :width =>self.item_description_width, :height => self.item_height) do + text "Old Balance", :size => self.item_font_size,:align => :left + end + bounding_box([self.item_description_width,y_position], :width =>self.label_width) do + text "#{number_with_precision(current_balance, :precision => precision.to_i, :delimiter => delimiter)}", :size => self.item_font_size,:align => :right + end end end @@ -367,7 +393,6 @@ class ReceiptBillPdf < Prawn::Document total_balance = total_balance + res["balance"] end - end move_down 5 y_position = cursor @@ -441,6 +466,7 @@ class ReceiptBillPdf < Prawn::Document move_down 73 text "Approved By" , :size => self.item_font_size,:align => :center end + break; end end if sale_data.payment_status == "foc" @@ -472,7 +498,7 @@ class ReceiptBillPdf < Prawn::Document text "#{printed_status}",:style => :bold, :size => header_font_size,:align => :left end bounding_box([self.item_description_width,y_position], :width =>self.item_description_width, :height => self.item_height) do - text "Thank You! See you Again", :left_margin => -10, :size => self.item_font_size,:align => :left + text "Thank You! See you Again", :left_margin => -5, :size => self.item_font_size,:align => :left end move_down 5 diff --git a/app/views/api/call_waiters/index.json.jbuilder b/app/views/api/call_waiters/index.json.jbuilder new file mode 100644 index 00000000..9173b340 --- /dev/null +++ b/app/views/api/call_waiters/index.json.jbuilder @@ -0,0 +1,6 @@ +if (@table) + json.table_id @table.id + json.name @table.name + json.type @table.type + json.time @time +end \ No newline at end of file diff --git a/app/views/api/orders/view_orders.json.jbuilder b/app/views/api/orders/view_orders.json.jbuilder index b2c960af..0ac1b92f 100755 --- a/app/views/api/orders/view_orders.json.jbuilder +++ b/app/views/api/orders/view_orders.json.jbuilder @@ -19,6 +19,13 @@ if (@booking) @total_amount = 0.00 @total_tax = 0.00 + # For YGN BBQ + adult_count = 0 + child_count = 0 + adult_spent = 0 + child_spent = 0 + # End YGN BBQ + if @booking.booking_orders order_items = [] @booking.booking_orders.each do |bo| @@ -26,21 +33,45 @@ if (@booking) if (order.status == "new") order_items = order_items + order.order_items end - end + end json.order_items order_items do |item| - json.item_instance_code item.item_code - json.item_name item.item_name - json.price item.price - json.qty item.qty - json.options item.options - json.remark item.remark - json.item_status item.order_item_status - @total_amount = @total_amount + (item.price * item.qty) + # For YGN BBQ + if item.item_code == "P00001" + adult_count += item.qty + adult_spent += (item.price * item.qty) + end + if item.item_code == "P00002" + child_count += item.qty + child_spent += (item.price * item.qty) + end + # End YGN BBQ + json.item_code item.item_code + json.item_instance_code item.item_instance_code + json.item_name item.item_name + json.price item.price + json.qty item.qty + json.options item.options + json.remark item.remark + json.item_status item.order_item_status + @total_amount = @total_amount + (item.price * item.qty) end end + # For YGN BBQ + if adult_count > 0 + json.per_adult_spent (adult_spent/adult_count) * 0.05 + else + json.per_adult_spent 0 + end + if child_count > 0 + json.per_child_spent (child_spent/child_count) * 0.05 + else + json.per_child_spent 0 + end + # End YGN BBQ + json.sub_total @total_amount json.commerical_tax @total_amount * 0.05 json.total @total_amount + (@total_amount * 0.05) diff --git a/app/views/api/restaurant/menu/_menu.json.jbuilder b/app/views/api/restaurant/menu/_menu.json.jbuilder index 29982631..8dcdf6fe 100755 --- a/app/views/api/restaurant/menu/_menu.json.jbuilder +++ b/app/views/api/restaurant/menu/_menu.json.jbuilder @@ -7,8 +7,12 @@ json.valid_time_to menu.valid_time_to.strftime("%H:%M") if (menu.menu_categories) json.categories menu.menu_categories do |category| json.id category.id + json.code category.code + json.order_by category.order_by json.name category.name json.alt_name category.alt_name + json.order_by category.order_by + json.parent_id category.menu_category_id json.is_available category.is_available if category.menu_items diff --git a/app/views/api/restaurant/zones/index.json.jbuilder b/app/views/api/restaurant/zones/index.json.jbuilder index e2d040c6..4a8666b4 100755 --- a/app/views/api/restaurant/zones/index.json.jbuilder +++ b/app/views/api/restaurant/zones/index.json.jbuilder @@ -1,42 +1,48 @@ if @zones json.array! @zones do |zone| - json.id zone.id - json.name zone.name - #List all tables - json.tables zone.tables do |table| + if zone.is_active + json.id zone.id + json.name zone.name + #List all tables + json.tables zone.tables do |table| + if table.is_active + json.id table.id + json.name table.name + json.status table.status + json.zone_id table.zone_id #Add this zone_id to keep data structure consistance + json.current_booking table.get_current_booking.booking_id rescue "" + end + end + + json.rooms zone.rooms do |room| + if room.is_active + json.id room.id + json.name room.name + json.status room.status + json.zone_id room.zone_id #Add this zone_id to keep data structure consistance + json.current_booking room.get_current_booking.booking_id rescue "" + end + end + end + end +else #list all tables and rooms with out zones + json.tables @all_tables do |table| + if table.is_active json.id table.id json.name table.name json.status table.status json.zone_id table.zone_id #Add this zone_id to keep data structure consistance json.current_booking table.get_current_booking.booking_id rescue "" end + end - json.rooms zone.rooms do |room| + json.rooms @all_rooms do |room| + if room.is_active json.id room.id json.name room.name json.status room.status json.zone_id room.zone_id #Add this zone_id to keep data structure consistance json.current_booking room.get_current_booking.booking_id rescue "" - end - end -else #list all tables and rooms with out zones - json.tables @all_tables do |table| - json.id table.id - json.name table.name - json.status table.status - json.zone_id table.zone_id #Add this zone_id to keep data structure consistance - json.current_booking table.get_current_booking.booking_id rescue "" - - end - - json.rooms @all_rooms do |room| - json.id room.id - json.name room.name - json.status room.status - json.zone_id room.zone_id #Add this zone_id to keep data structure consistance - json.current_booking room.get_current_booking.booking_id rescue "" - - end end diff --git a/app/views/crm/customers/index.html.erb b/app/views/crm/customers/index.html.erb index 091d8e51..2682f203 100755 --- a/app/views/crm/customers/index.html.erb +++ b/app/views/crm/customers/index.html.erb @@ -11,79 +11,90 @@
-
+
-
- - - - - - - - - - - - - - - - - - - <% if @crm_customers.count > 0 %> - <% @i = 0 %> - <% @crm_customers.each do |crm_customer| %> - - - - - - - - - <% end %> - <% else %> - - <% end %> - -
- -
- <%= form_tag crm_customers_path, :id => "filter_form", :method => :get do %> -
-
- - -
- - - - - +
+
+
+ <%= form_tag crm_customers_path, :id => "filter_form", :method => :get do %> +
+
+ +
- <% end %> + + + + +
-
<%= t("views.right_panel.detail.sr_no") %><%= t("views.right_panel.detail.name") %><%= t("views.right_panel.detail.card_no") %><%= t("views.right_panel.detail.contact_no") %><%= t("views.right_panel.detail.email") %><%= t("views.right_panel.detail.action") %>
- - <% if crm_customer.customer_id != "CUS-000000000001" && crm_customer.customer_id != "CUS-000000000002" %> - <%= @i += 1 %> - <%else%> - - - <% end %> - <%= crm_customer.name %><%= crm_customer.card_no rescue '-' %><%= crm_customer.contact_no %><%= crm_customer.email %><%= link_to t("views.btn.show"), crm_customer_path(crm_customer) %>

There is no data for search <%=@filter%>....

-
- <%= paginate @crm_customers %> +
+
+
+
+ + + + + + + + + + + + + + + + + <% if @crm_customers.count > 0 %> + <% @i = 0 %> + <% @crm_customers.each do |crm_customer| %> + + + + + + + + + + <% end %> + <% else %> + + <% end %> + +
<%= t("views.right_panel.detail.sr_no") %><%= t("views.right_panel.detail.name") %><%= t("views.right_panel.detail.card_no") %><%= t("views.right_panel.detail.contact_no") %><%= t("views.right_panel.detail.email") %><%= t("views.right_panel.detail.action") %>
+ + + <% if crm_customer.customer_id != "CUS-000000000001" && crm_customer.customer_id != "CUS-000000000002" %> + <%= @i += 1 %> + <%else%> + - + <% end %> + <%= crm_customer.name %><%= crm_customer.card_no rescue '-' %><%= crm_customer.contact_no %><%= crm_customer.email %><%= link_to t("views.btn.show"), crm_customer_path(crm_customer) %>

There is no data for search <%=@filter%>....

+
+ <%= paginate @crm_customers %> +
+
+
+ +
-
+
<%= render 'new_form', crm_customer: @crm_customer, taxes: @taxes %> diff --git a/app/views/crm/customers/show.html.erb b/app/views/crm/customers/show.html.erb index 338aea1d..26ce197a 100755 --- a/app/views/crm/customers/show.html.erb +++ b/app/views/crm/customers/show.html.erb @@ -77,7 +77,7 @@ - <% if @response["status"] == true %> + <% if @response["status"] == true && @response["data"].count > 0 %> <% @response["data"].each do |transaction| %> <%= transaction["date"]%> @@ -101,7 +101,7 @@ <%end%> <%else%> -

There is no transaction coz of <%=@response["data"]%> ...

+

There is no transaction coz of <%=@response["message"]%> ...

<% end %> diff --git a/app/views/crm/dining_queues/_form.html.erb b/app/views/crm/dining_queues/_form.html.erb index 7796e9a9..51e2c097 100755 --- a/app/views/crm/dining_queues/_form.html.erb +++ b/app/views/crm/dining_queues/_form.html.erb @@ -29,9 +29,9 @@
-
1
-
2
-
3
+
1
+
2
+
3
@@ -39,9 +39,9 @@
-
4
-
5
-
6
+
4
+
5
+
6
@@ -49,9 +49,9 @@
-
7
-
8
-
9
+
7
+
8
+
9
@@ -59,9 +59,9 @@
-
0
-
.
-
00
+
0
+
.
+
00
@@ -69,9 +69,9 @@
-
-
DEL
-
CLR
+
+
DEL
+
CLR
diff --git a/app/views/crm/dining_queues/index.html.erb b/app/views/crm/dining_queues/index.html.erb index 8eb9904e..a935cf38 100755 --- a/app/views/crm/dining_queues/index.html.erb +++ b/app/views/crm/dining_queues/index.html.erb @@ -100,8 +100,8 @@ <%= link_to t("views.btn.new"),new_crm_dining_queue_path,:class => 'btn bg-green btn-block btn-lg btn-block', 'data-no-turbolink' => true %>
- - + +
diff --git a/app/views/crm/home/index.html.erb b/app/views/crm/home/index.html.erb index d73a0cdc..2c8fe695 100755 --- a/app/views/crm/home/index.html.erb +++ b/app/views/crm/home/index.html.erb @@ -118,7 +118,7 @@ --> - +
diff --git a/app/views/home/dashboard.html.erb b/app/views/home/dashboard.html.erb index f6dd86b8..3ed5e068 100755 --- a/app/views/home/dashboard.html.erb +++ b/app/views/home/dashboard.html.erb @@ -56,7 +56,7 @@ <% if current_user.role == 'administrator' || current_user.role == 'manager' %>
-
+
@@ -111,32 +111,32 @@
-
+
<% if !@summ_sale.nil? %>
-
Sale
+
<%= t :sale %>
- + - + - + - + - +
Total Receipt : <%= t("views.right_panel.detail.total") %> <%= t("views.right_panel.detail.receipt") %> : <%= @summ_sale.total_receipt %>
Total Sale : <%= t("views.right_panel.detail.total") %> <%= t :sale %> : <%= @summ_sale.total_amount %>
Total Discount : <%= t("views.right_panel.detail.total") %> <%= t("views.right_panel.detail.discount") %> : <%= @summ_sale.total_discount %>
Total Tax : <%= t("views.right_panel.detail.total") %> <%= t("views.right_panel.detail.tax") %> : <%= @summ_sale.total_tax %>
Grand Total : <%= t("views.right_panel.detail.grand_total") %> : <%= @summ_sale.grand_total %>
@@ -144,16 +144,7 @@ <% if !(@total_payment_methods.nil?) %> <% @total_payment_methods.each do |payment| %> <% if !@sale_data[0].empty? %> - <% if payment.payment_method == 'mpu' || payment.payment_method == 'visa' || payment.payment_method == 'master' || payment.payment_method == 'jcb' %> - - Card Sale : - - <% @sale_data.each do |data| %> - <%= data["card"] %> - <% end %> - - - <% else %> + <% if payment.payment_method != 'mpu' && payment.payment_method != 'visa' && payment.payment_method != 'master' && payment.payment_method != 'jcb' %> <%= payment.payment_method.to_s.capitalize %> Sale : @@ -166,6 +157,17 @@ <% end %> <% end %> <% end %> + + <% total_card = @sale_data.select { |hash| hash["card"]!=nil }.first %> + <% if !total_card.nil? %> + + <%= t("views.right_panel.detail.card_sale") %> : + + <%= total_card["card"].to_f %> + + + <% end %> + <% end %>
@@ -178,35 +180,35 @@
-
Customer
+
<%= t :customer %>
<% if !@total_customer.nil? %> - - + + <% end %> <% if !@total_dinein.nil? %> - + <% end %> <% if !@total_takeaway.nil? %> - + <% end %> <% if !@total_other_customer.nil? %> - + <% end %> <% if !@total_membership.nil? %> - + <% end %> @@ -220,20 +222,20 @@
-
Order
+
<%= t("views.right_panel.detail.order") %>
Total Customer : <%= @total_customer.total_cus %><%= t("views.right_panel.detail.total") %> <%= t :customer %> : <%= @total_customer %>
Dine in : <%= t("views.right_panel.detail.dine_in") %> : <%= @total_dinein.total_dinein_cus %>
Takeaway : <%= t("views.right_panel.detail.takeaway") %> : <%= @total_takeaway.total_take_cus %>
Customer : <%= t :customer %> : <%= @total_other_customer.total_cus %>
Membership : <%= t("views.right_panel.detail.membership") %> : <%= @total_membership.total_memb_cus %>
<% if !@total_order.nil? %> - - + + <% end %> - <% if !(@total_accounts.nil?) %> + <% if !@total_accounts.nil? %> <% @total_accounts.each do |account| %> - - - + <% end %> <% if !@total_foc_items.nil? %> - - + + <% end %>
Total Order : <%= @total_order.total_order %><%= t("views.right_panel.detail.total") %> <%= t("views.right_panel.detail.order") %> : <%= @total_order.total_order %>
<%= account.title %> (Account) : + <% @account_data.each do |data| %> <% acc = account.title %> <%= data[""+acc+""] %> <% if !data[''+acc+''].nil? %> ( <%= data[''+acc+'_amount'] %> ) <% end %> @@ -244,15 +246,15 @@ <% end %> <% if !@top_items.nil? %>
Top Item : <%= @top_items.item_name %> + <%= t :top %> <%= t("views.right_panel.detail.item") %> : <%= @top_items.item_name %>
(<%= @top_items.item_total_price %>)
Total FOC Item : <%= @total_foc_items %><%= t("views.right_panel.detail.total") %> <%= t("views.btn.foc") %> <%= t("views.right_panel.detail.item") %> : <%= @total_foc_items.to_int %>
diff --git a/app/views/install/_form.html.erb b/app/views/install/_form.html.erb index 288c431a..c4520cd6 100755 --- a/app/views/install/_form.html.erb +++ b/app/views/install/_form.html.erb @@ -1,4 +1,4 @@ -
+
@@ -10,7 +10,7 @@ Add License Key from Email
-
+
+
+ + +
+
+ + +
diff --git a/app/views/layouts/_header.html.erb b/app/views/layouts/_header.html.erb index f7ca56f2..67746ba6 100755 --- a/app/views/layouts/_header.html.erb +++ b/app/views/layouts/_header.html.erb @@ -14,11 +14,16 @@ -
- +
-
- - - +
+
@@ -148,6 +145,31 @@ <% end %> <% end %>
+ +
+
+ Waiter +
+
+
+
+
+ +
+ <% @employees.each do |employee| %> + <%if employee.role == "waiter" %> +
+ + +
+
+ <%= employee.name%> +
+
+
+ <% end %> + <% end %> +
@@ -157,9 +179,7 @@ diff --git a/app/views/origami/payments/show.html.erb b/app/views/origami/payments/show.html.erb index a911acf4..b9d2cf8b 100755 --- a/app/views/origami/payments/show.html.erb +++ b/app/views/origami/payments/show.html.erb @@ -94,7 +94,7 @@ Rounding Adj: - <%=@sale_data.rounding_adjustment rescue 0%> + <%= @sale_data.rounding_adjustment rescue 0%> Grand Total @@ -109,7 +109,7 @@
- + @@ -121,7 +121,11 @@
Amount Due
-
<%= @sale_data.grand_total %>
+
+ + + <%= @sale_data.grand_total rescue 0%> +
@@ -219,7 +223,7 @@
Balance
-
<%= @sale_data.grand_total %>
+
<%= @sale_data.grand_total rescue 0 %>
@@ -276,8 +280,8 @@ reply Back - - + +
@@ -286,6 +290,21 @@ \ No newline at end of file diff --git a/app/views/reports/commission/_commission_report_filter.html.erb b/app/views/reports/commission/_commission_report_filter.html.erb index 0e2f71f8..d7d41eb6 100755 --- a/app/views/reports/commission/_commission_report_filter.html.erb +++ b/app/views/reports/commission/_commission_report_filter.html.erb @@ -1,7 +1,7 @@
-<%= form_tag report_path, :method => :get, :id => "frm_report", :class => "form" do %> + <%= form_tag report_path, :method => :get, :id => "frm_report", :class => "form" do %> <% if period_type != false %> -
+
- - - -
-
- - -
+ + + +
+
+ + +
- <% @commissioner.each do |c| %> <% if @com_id == c.id %> @@ -34,16 +34,16 @@
-
+
+
+ <% end %> + <% end %>
- <% end %> -<% end %> -
- +
- +
-
diff --git a/app/views/reports/credit_payment/index.html.erb b/app/views/reports/credit_payment/index.html.erb index 8becb13c..7c520fe3 100755 --- a/app/views/reports/credit_payment/index.html.erb +++ b/app/views/reports/credit_payment/index.html.erb @@ -65,7 +65,7 @@ $(function(){ var check_arr = []; - + search_by_period(); $('#sel_period').change(function(){ search_by_period(); @@ -83,20 +83,24 @@ // OK button is clicked $('#from').bootstrapMaterialDatePicker().on('beforeChange', function(e, date){ - $('#from').val(date) + new_date = new Date(date) ; + month = parseInt(new_date.getMonth()+1) + from = new_date.getDate() + "-" + month + "-" + new_date.getFullYear(); + $('#from').val(from) search_by_date(); }); $('#to').bootstrapMaterialDatePicker().on('beforeChange', function(e, date){ - $('#to').val(date) + new_date = new Date(date) ; + month = parseInt(new_date.getMonth()+1) + to = new_date.getDate() + "-" + month + "-" + new_date.getFullYear(); + $('#to').val(to) search_by_date(); - }); + }); function search_by_date(){ - var to_date = new Date($('#to').val()); - var to = to_date.getDate() + "-" + to_date.getMonth() + "-" + to_date.getFullYear(); - var from_date = new Date($('#from').val()); - var from = from_date.getDate() + "-" + from_date.getMonth() + "-" + from_date.getFullYear(); + from = $("#from").val(); + to = $("#to").val(); var period = 0; var period_type = 1; @@ -119,7 +123,10 @@ function show_shift_name(period,period_type,from,to,shift_item){ var shift = $('#shift_name'); - + if (from == '' && to == '') { + from = $("#from").val(); + to = $("#to").val(); + } shift.empty(); var str = ''; diff --git a/app/views/reports/credit_payment/index.xls.erb b/app/views/reports/credit_payment/index.xls.erb index 9597e3d9..ebf360a9 100755 --- a/app/views/reports/credit_payment/index.xls.erb +++ b/app/views/reports/credit_payment/index.xls.erb @@ -1,20 +1,21 @@ -
-
+ +
+
<% unless @sale_data.blank? %> <% if !params[:from].blank?%> - + <% end %> - - - - - + + + + + @@ -36,4 +37,4 @@
From Date : <%= params[:from] rescue '-'%> , To Date : <%= params[:to] rescue '-'%><%= t("views.right_panel.detail.from_date") %> : <%= params[:from] rescue '-'%> , <%= t("views.right_panel.detail.to_date") %> : <%= params[:to] rescue '-'%>
Shift Name Receive No Cashier Name Customer Name Credit Amount <%= t("views.right_panel.detail.shift_name") %> <%= t("views.right_panel.detail.receipt_no") %> <%= t :cashier %> <%= t("views.right_panel.detail.name") %> <%= t :customer %> <%= t("views.right_panel.detail.name") %> <%= t("views.right_panel.detail.credit_amount") %>
<% end %>
-
\ No newline at end of file +
diff --git a/app/views/reports/dailysale/_shift_sale_report_filter.html.erb b/app/views/reports/dailysale/_shift_sale_report_filter.html.erb index e584bbba..d3afcbfe 100755 --- a/app/views/reports/dailysale/_shift_sale_report_filter.html.erb +++ b/app/views/reports/dailysale/_shift_sale_report_filter.html.erb @@ -24,11 +24,11 @@
- +
- +

diff --git a/app/views/reports/dailysale/index.html.erb b/app/views/reports/dailysale/index.html.erb index e258f892..b8eded4f 100755 --- a/app/views/reports/dailysale/index.html.erb +++ b/app/views/reports/dailysale/index.html.erb @@ -1,5 +1,5 @@ -