Skip to content

Instantly share code, notes, and snippets.

@waseem
Created September 25, 2014 07:21
Show Gist options
  • Save waseem/6121b3236a5b670a68f0 to your computer and use it in GitHub Desktop.
Save waseem/6121b3236a5b670a68f0 to your computer and use it in GitHub Desktop.
# contracts_controller.rb
class ContractsController < ApplicationController
respond_to :html, :xls
# GET /contracts
# GET /contracts.json
def all
@contracts = Contract.all_items_i_can_view(current_user)
respond_to do |format|
format.html # index.html.erb
end
end
# GET /contracts/1
# GET /contracts/1.json
def show
@record = Contract.find(params[:id])
@contract = JSON.parse(@record.data)
@contract_documents = ContractDocument.find_docs(@record["contract_number"])
@contract_notes = ContractNote.all( :conditions => {:contract_id => params[:id]}, :order => "note_created_timestamp desc")
respond_to do |format|
format.html # show.html.erb
end
log_activity("Viewed contract for contract number: #{@record["contract_number"]}")
end
def new_contract
@nextContractNumber = Contract.getNextContractNumber
data = {:key => :value}
@cont = Contract.create(
:contract_number => @nextContractNumber,
:created_by => 'Place holder',
:data => data.to_json,
:status => "Draft",
:created_timestamp => DateTime.now
)
end
def submit_contract
c = Contract.find(params[:id])
c.created_timestamp = DateTime.now
c.last_updated_timestamp = DateTime.now
c.status = "Submitted"
c.save
ContractMailer.new_contract_submitted_email(c.data, c.contract_number).deliver!
log_activity("Submitted contract for contract number from draft state: #{c.contract_number}")
redirect_to "/contracts/all", :alert => "Contract Number #{c.contract_number} has been successfully submitted to MIS."
end
def new_contract_created
@data_json = params[:data]
@data = JSON.parse(@data_json)
contract_number = @data["contractNumber"]
response = validate_contract(@data)
if (response[:status] == "success")
c = Contract.unscoped.find_by_contract_number(contract_number)
c.created_by = @data["sales_manager_id"]
c.data = @data_json
c.status = params[:commit] == "Submit Contract" ? "Submitted" : "Draft Saved"
c.created_timestamp = DateTime.now
c.save
ContractMailer.new_contract_created_email(@data, contract_number).deliver!
response = {
:status => "success",
:message => "Contract Number #{contract_number} has been submitted successfully."
}
render :text => response.to_json
log_activity("Submitted contract for contract number: #{contract_number}")
return
else
render :text => response.to_json
end
end
def save_edited
@data_json = params[:data]
@data = JSON.parse(@data_json)
contract_number = @data["contractNumber"]
@data["__ko_mapping__"] = nil
response = validate_contract(@data)
if (response[:status] == "success")
c = Contract.find_by_contract_number(contract_number)
c.created_by = @data["sales_manager_id"]
c.data = @data.to_json
c.status = params[:status] if (! params[:status].nil?)
c.last_updated_timestamp = DateTime.now
c.created_timestamp = DateTime.now if (! is_mis_user?)
c.save
if (! params[:est_notes].nil?)
new_note = ContractNote.new(:contract_id => params[:contract_id], :tc_user_id => session[:current_user][:tc_user_id], :notes => params[:est_notes], :note_created_timestamp => DateTime.now)
new_note.save
end
if (! params[:users_to_notify].nil?)
users_array = params[:users_to_notify].split(",")
users_array.each { |user|
NotesMailer.new_contract_note_created_email(user.gsub("@",""), new_note, params[:contract_id]).deliver!
}
end
response = {
:status => "success",
:message => "Contract Number #{contract_number} has been updated successfully."
}
render :text => response.to_json
log_activity("Updated contract for contract number: #{contract_number}")
return
else
render :text => response.to_json
end
end
def validate_contract(data)
errors = []
if (data["contractStart"].nil? || data["contractStart"].empty?)
errors << "Contract start date cannot be blank."
end
if (data["contractEnd"].nil? || data["contractEnd"].empty?)
errors << "Contract end date cannot be blank."
elsif (Date.parse(data["contractStart"]) > Date.parse(data["contractEnd"]))
errors << "Contract start date cannot be past contract end date."
end
if (data["parent_company_name"].nil? || data["parent_company_name"].empty?)
errors << "Parent company name cannot be blank."
end
logger.debug("** 1 type #{data["contractType"]} **" )
if (data["parent_address1"].nil? || data["parent_address1"].empty?)
errors << "Parent company address 1 cannot be blank."
end
if (data["parent_address2"].nil? || data["parent_address2"].empty?)
errors << "Parent company address 2 cannot be blank."
end
if (data["parent_contact_person"].nil? || data["parent_contact_person"].empty?)
errors << "Contact person cannot be blank."
end
if (data["parent_pin"].nil? || data["parent_pin"].empty?)
errors << "PIN cannot be blank."
end
if (data["parent_pan"].nil? || data["parent_pan"].empty?)
errors << "PAN number cannot be blank."
end
if (data["parent_mobile"].nil? || data["parent_mobile"].empty?)
errors << "Mobile number cannot be blank."
elsif ! numeric?(data["parent_mobile"])
errors << "Mobile number contains non numerics characters."
end
if (data["parent_email"].nil? || data["parent_email"].empty?)
errors << "Email address cannot be blank."
elsif (! data["parent_email"].match(/^([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})$/))
errors << "Email address is invalid."
end
# check if a product exists or not
if (data["lines"][0]["product"].nil?)
errors << "You need to enter at least one product."
end
#validate product amount
data["lines"].each { |pl|
# skip if product not added
next if (pl["product"].nil?)
if (pl["size"].nil? || pl["size"].empty?)
errors << "Size cannot be blank."
end
if (! numeric?(pl["unit"]))
errors << "Unit contains non numeric values."
end
if (! numeric?(pl["discount"]))
errors << "Discount contains non numeric values."
end
if (! numeric?(pl["rate"]))
errors << "Card Rate contains non numeric values."
end
if (! numeric?(pl["subtotal"]))
errors << "Amount contains non numeric values."
end
}
#validate payment amount
data["payment_lines"].each { |pl|
# skip if product not added
next if (pl["check_amount"].nil?)
if (! numeric?(pl["check_amount"]))
errors << "Check amount contains non numeric values."
end
if (! numeric?(pl["tds"]))
errors << "TDS contains non numeric values."
end
if (pl["check_date"].nil? || pl["check_date"].empty?)
errors << "Cheque date cannot be blank."
end
if (pl["check_number"].nil? || pl["check_number"].empty?)
errors << "Cheque number cannot be blank."
end
}
if (! errors.empty?)
return {:status => "failure", :errors => errors}
else
return {:status => "success"}
end
end
# GET /contracts/1/edit
def edit
@contract = Contract.find(params[:id])
if (current_user.can_edit_contract?(@contract))
# continue okay
else
flash[:alert] = "This is an alert."
flash[:notice] = "This is a notice."
redirect_to "/"
end
@contract_notes = ContractNote.all( :conditions => {:contract_id => params[:id]}, :order => "note_created_timestamp desc")
@nextContractNumber = @contract.contract_number
@contract_documents = ContractDocument.find_docs(@contract.contract_number)
end
def edit_data
@contract = Contract.find(params[:id])
@data = JSON.parse(@contract.data)
# remove empty products
good_pr = []
@data["lines"].each { |pr|
good_pr << pr if (pr["product"])
}
@data["lines"] = good_pr
# remove empty payment lines
good_pl = []
@data["payment_lines"].each { |pl|
good_pl << pl if (pl["check_amount"])
}
@data["payment_lines"] = good_pl
@data["remarks"] = "N/A" if (@data["remarks"].nil?)
@data["parent_designation"] = "" if (@data["parent_designation"].nil?)
@data["parent_address2"] = "" if (@data["parent_address2"].nil?)
render :text => @data.to_json
end
# DELETE /contracts/1
# DELETE /contracts/1.json
def delete
@contract = Contract.find(params[:id])
@contract.destroy
log_activity("Deleted contract for contract number: #{@contract.contract_number}")
respond_to do |format|
format.html { redirect_to "/contracts/all", :alert => "Contract numbe #{@contract.contract_number} has been deleted."}
format.json { head :no_content }
end
end
def remove_doc
cd = ContractDocument.new
doc = cd.remove(params[:doc_id])
flash[:notice] = "Document has been deleted from contract."
redirect_to "/contracts/edit?id=#{params[:contract_id]}"
end
def apr_sh
@record = Contract.find(params[:id])
@contract = JSON.parse(@record.data)
end
def sh_contract_approval
@record = Contract.find(params[:id])
if (params[:contract_action] == "approved")
@record.status = "Approved by Sales Head"
@record.last_updated_timestamp = DateTime.now
@record.save
else
@record.status = "Rejected by Sales Head"
@record.last_updated_timestamp = DateTime.now
@record.save
end
@contract = JSON.parse(@record.data)
ContractMailer.sh_contract_approval_email(@contract, params[:contract_action], params[:est_notes]).deliver!
# ContractMailer.new_contract_created_email(@contract).deliver!
end
def contract
if params[:id].nil?
render :text => "Nil contract id passed."
return
end
@record = Contract.find(params[:id])
@contract = JSON.parse(@record.data)
if @contract.nil?
render :text => "Incorrect contract id."
end
log_activity("Printed contract for contract number: #{@record["contract_number"]}")
end
def upload
end
def receive_doc
uploaded_io = params[:document]
#File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'wb') do |file|
#file.write(uploaded_io.read)
contract_document = ContractDocument.new
response = contract_document.save(uploaded_io.read,uploaded_io.original_filename, params[:contractNumber],
session[:current_user][:tc_user_id]
)
#end
data = { :files => [
{
:name => uploaded_io.original_filename,
:size => response[:bytes],
:url => response[:path],
:thumbnailUrl => response[:icon]
}
]
}
render :text => data.to_json
end
def serve_doc
cd = ContractDocument.new
doc = cd.find(params[:doc_id])
send_data doc[:content], :type => doc[:metadata]["mime_type"], :filename => doc[:name], :disposition => params[:d]
end
def dump_to_excel
@records = Contract.all_items_i_can_view(current_user)
respond_with @records
log_activity("Downloaded all contracts in Excel")
end
def notes
@contract = Contract.find(params[:contract_id])
@contract_notes = ContractNote.all( :conditions => {:contract_id => params[:contract_id]}, :order => "note_created_timestamp desc")
log_activity("Viewed notes page for Contract #{@contract.contract_number} <a href='http://sales.timescity.com/contracts/notes?contract_id=#{params[:contract_id]}'>Link</a>.") if (params[:note_added].nil?)
end
def post_note
status = "fail" # default to failure
errors = []
if (params[:est_notes].size > 2000)
errors << "Note cannot be more than 2000 characters."
end
if (params[:est_notes].size < 10)
errors << "Note is too short. Enter minimum 10 characters."
end
if (errors.empty?)
status = "success"
end
data = {
:status => status,
:errors => errors
}
if (status == "success")
new_note = ContractNote.new(:contract_id => params[:contract_id], :tc_user_id => session[:current_user][:tc_user_id], :notes => params[:est_notes], :note_created_timestamp => DateTime.now)
new_note.save
flash[:alert] = "Note saved successfully."
log_activity("Note added for Contract # #{params[:contract_id]}. [#{params[:est_notes]}]<a href='/contracts/notes?contract_id=#{params[:contract_id]}'>Link</a>.")
if (! params[:users_to_notify].nil?)
users_array = params[:users_to_notify].split(",")
users_array.each { |user|
NotesMailer.new_contract_note_created_email(user.gsub("@",""), new_note, params[:contract_id]).deliver!
}
end
else
flash[:alert] = errors.join(",")
end
# send alert to users
redirect_to "/contracts/notes?contract_id=#{params[:contract_id]}&note_added=1"
end
def put_flash
flash[:alert] = "Alert"
flash[:notice] = "notice"
redirect_to "/contracts/show_flash"
end
def show_flash
render :layout => false
end
end
# application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :check_users_existence, :get_cities
helper_method :authorized_user?
helper_method :admin_user?
helper_method :logged_in?
helper_method :super_admin?
helper_method :can_give_sh_approval?
helper_method :is_mis_user?
helper_method :current_user
helper_method :can_appointment_be_edited?
alias :std_redirect_to :redirect_to
def redirect_to(*args)
flash.keep
std_redirect_to *args
end
def get_cities
@cities_list = { 'Pune' => 'Pune',
'Delhi/NCR' => 'Delhi',
'Mumbai' => 'Mumbai',
'Bangalore' => 'Bangalore',
'Chennai' => 'Chennai',
'Hyderabad' => 'Hyderabad',
'Kolkata' => 'Kolkata',
'Ahmedabad' => 'Ahmedabad',
'Chandigarh' => 'Chandigarh',
'Jaipur' => 'Jaipur',
'Goa' => 'Goa' }
@selected_city = cookies[:cityname]
end
def check_users_existence
if (cookies[:TCID].nil? || cookies[:TCID].empty? )
reset_session
redirected = redirect_to_home
@login_error = "11 - Invalid login cookie."
return if redirected
end
if cookies[:TCID].nil?
return
end
if (! session[:current_user].nil? && cookies[:TCID] != session[:current_user].tc_user_id)
reset_session
end
# check for token now if environment not development
if (! session[:current_user])
api = ApistgApi.new
encoded_token = CGI.escape(cookies[:token])
token_response = api.check_token(encoded_token, cookies[:TCID])
if (token_response == "true")
# logger.debug "token is valid"
else
@login_error = "12 - Invalid login token."
reset_session
session.clear
cookies.delete(:TCID, domain: :all)
cookies.delete(:USERNAME, domain: :all)
cookies.delete(:SSOID, domain: :all)
cookies.delete(:TCITYSESS, domain: :all)
cookies.delete(:UI, domain: :all)
cookies.delete(:token, domain: :all)
session[:current_user] = nil
redirected = redirect_to_home
return if redirected
end
end
user = User.find_by_tc_user_id(cookies[:TCID])
session[:current_user] = user
if (user.nil?)
# create user first time from cookies
new_user = User.new( :tc_user_id => cookies[:TCID],
:tc_user => cookies[:USERNAME],
:email => cookies[:LOGINID],
:sso_id => cookies[:SSOID],
:group_id => 5,
:created_timestamp => DateTime.now
)
new_user.save
session[:current_user] = new_user
end
if (not authorized_user?)
@login_error = "12 - Unauthorized user."
redirected = redirect_to_home
return if redirected
end
end
def redirect_to_home
if (! (params[:controller] == "home" && params[:action] == "index"))
redirect_to "/home/index", alert: "Unauthorized Access."
return true
end
end
def generate_column_graph(data)
data.to_yaml
end
def self.generate_data_v2 (xml_config)
@data_config = nil
@data_config = DEFAULT_DATA_CHART_CONFIGS
xml_config[:chartConfigs].each do |k, v|
@data_config[k] = v
end
return @data_config
end
def self.handle_js_function(data)
data.gsub!("\"\$\$", "")
data.gsub!("\$\$\"", "")
data.gsub!("\\n", "")
data.gsub!("\\t", "")
data
end
def log_activity(activity, est_id=nil)
if (est_id.nil?)
activity = UserActivity.new(:tc_user_id => session[:current_user][:tc_user_id], :activity => activity, :est_id => est_id, :log_timestamp => DateTime.now)
else
activity = UserActivity.new(:tc_user_id => session[:current_user][:tc_user_id], :activity => activity, :est_id => est_id, :log_timestamp => DateTime.now)
end
activity.save
end
def authorized_user?
session[:current_user].approved?
end
def admin_user?
session[:current_user].admin_user?
end
def super_admin?
session[:current_user].super_admin?
end
def logged_in?
if (session[:current_user].nil? || session[:current_user].tc_user_id.nil?)
return false
else
return true
end
end
def can_give_sh_approval?
session[:current_user].can_give_sh_approval?
end
def is_mis_user?
session[:current_user].is_mis_user?
end
def current_user
session[:current_user]
end
def self.handle_js_function(data)
data.gsub!("\"\$\$", "")
data.gsub!("\$\$\"", "")
data.gsub!("\\n", "")
data.gsub!("\\t", "")
end
def encode_url (str)
CGI.escape(str)
end
def EstIdToName(est_id)
est = Establishment.find_by_est_id(est_id)
if (est.nil?)
"N/A"
else
"#{est.est_name}, #{est.est_loc_name}"
end
end
def numeric?(number)
return true if number =~ /^\d+$/
true if Float(number) rescue false
end
def NameToUserID(name)
u = User.find_by_tc_user(name)
u.tc_user_id
end
def can_appointment_be_edited?(appointment)
return true if is_mis_user?
if appointment.appointment_timestamp < 2.days.ago
return false
else
return true
end
end
end
# show_flash.html.rb
<%= debug(flash) %>
# am doing http://sales-portal-contract.dev/put_flash
# getting output
--- !ruby/object:ActionDispatch::Flash::FlashHash
used: !ruby/object:Set
hash: {}
closed: false
flashes: {}
now:
# logs
Started GET "/contracts/put_flash" for 127.0.0.1 at 2014-09-25 11:35:49 +0530
Processing by ContractsController#put_flash as HTML
User Load (2.3ms) SELECT "users".* FROM "users" WHERE "users"."tc_user_id" = 31735 LIMIT 1
Redirected to http://sales-portal-contract.dev/contracts/show_flash
Completed 302 Found in 38596ms (ActiveRecord: 40.3ms)
Started GET "/contracts/show_flash" for 127.0.0.1 at 2014-09-25 11:36:34 +0530
Processing by ContractsController#show_flash as HTML
User Load (2.6ms) SELECT "users".* FROM "users" WHERE "users"."tc_user_id" = 31735 LIMIT 1
Rendered contracts/show_flash.html.erb (1.4ms)
Completed 200 OK in 3719ms (Views: 365.8ms | ActiveRecord: 254.9ms)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment