Skip to content

Instantly share code, notes, and snippets.

@nplusp
Created October 19, 2015 09:43
Show Gist options
  • Save nplusp/a46b9a2000e78ebcf3a2 to your computer and use it in GitHub Desktop.
Save nplusp/a46b9a2000e78ebcf3a2 to your computer and use it in GitHub Desktop.
require 'file_size_validator'
require 'my_file_util'
class Student < ActiveRecord::Base
attr_accessible :marital_status, :community, :date_of_birth, :email, :first_name, :gender, :photo, :photo_cache, :fee_receipt_no, :program_ids, :fee_amount,
:last_attended_school_name, :surname, :lga, :middle_name, :mobile, :nationality, :phone, :registration_id, :status, :registration_number,
:registration_pin, :program_id, :attachments_attributes, :score, :admission_remark, :offered_program_id, :jamb_score, :jamb_registration_number, :batch_id, :admission_no,
:admission_date, :blood_group, :birth_place, :language, :religion, :address_attributes, :next_of_kin_attributes, :course_ids, :carry_over_course_ids, :academic_session,
:student_category_id, :country_id, :state_id, :lga_id, :answers_attributes, :user_id, :second_next_of_kin_attributes, :previous_attended_school_attributes
attr_accessor :user_id, :registration_pin, :from_csv, :returning_student, :program_ids, :carry_over_course_ids, :is_being_promoted
mount_uploader :photo, PhotoUploader
belongs_to :institution
belongs_to :registration
belongs_to :batch
belongs_to :program
belongs_to :student_category
belongs_to :country
belongs_to :state
belongs_to :lga
belongs_to :offered_program, :class_name => 'Program'
has_many :remarks, :dependent => :destroy
has_many :pins, :dependent => :destroy
has_many :skill_scores, :dependent => :destroy
has_one :address, :as => :addressable, :dependent => :destroy
has_one :next_of_kin, :as => :parentable, :dependent => :destroy
has_one :second_next_of_kin, :as => :guardianable, :dependent => :destroy
has_one :user, :as => :accountable, :dependent => :destroy
has_many :student_courses
has_many :courses, :through => :student_courses
has_many :attachments, :as => :attachable, :dependent => :destroy
has_many :assessment_results, :dependent => :destroy
has_many :answers, :dependent => :destroy
has_many :discounts, :dependent => :destroy
has_many :payment_records, :dependent => :destroy
has_many :other_fees, :dependent => :destroy
has_many :student_attendances, :dependent => :destroy
has_one :previous_attended_school, :dependent => :destroy
has_many :batch_students, :dependent => :destroy
has_many :student_invoices
has_many :invoices, :through => :student_invoices
accepts_nested_attributes_for :attachments, :allow_destroy => true, :reject_if => :all_blank
accepts_nested_attributes_for :address, :allow_destroy => true, :reject_if => :all_blank
accepts_nested_attributes_for :next_of_kin, :allow_destroy => true, :reject_if => :all_blank
accepts_nested_attributes_for :second_next_of_kin, :allow_destroy => true, :reject_if => :all_blank
accepts_nested_attributes_for :previous_attended_school, :allow_destroy => true, :reject_if => :all_blank
validates :photo, :file_size => {maximum: 100.kilobytes.to_i}
validates_presence_of [:first_name, :surname, :gender, :community, :country_id, :lga_id, :state_id]
validate :date_of_birth_validate
validates_presence_of :mobile, :if => Proc.new { |user| !user.institution.is_a?(UBE) }
validates_presence_of :photo, :if => Proc.new { |user| !user.from_csv }
validates_length_of :mobile, :is => 10, :message => 'Mobile number should be 10 digits only.', :if => Proc.new { |user| !user.institution.is_a?(UBE) && user.mobile.present? }
validates_numericality_of :mobile, :if => Proc.new { |user| !user.institution.is_a?(UBE) && user.mobile.present? }
validates_numericality_of :phone, :if => Proc.new { |user| user.phone.present? }
validates_uniqueness_of :admission_no, :scope => :institution_id, :if => Proc.new { |student| student.admission_no.present? }
validates_uniqueness_of :registration_number, :scope => :institution_id, :if => Proc.new { |student| student.registration_number.present? }
before_save :validate_courses_count_and_credit_points, :unless => Proc.new { |student| student.is_being_promoted }
before_save :record_batch_history
before_create :validate_registration_pin, :if => Proc.new { |user| !user.from_csv && registration.present? }
after_create :generate_registration_number, :consume_pin, :if => Proc.new { |user| !user.from_csv && registration.present? }
validates :email, format: {with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, message: "is not valid"}, :if => Proc.new { |student| student.email.present? }
BLOOD_GROUP = %w(A+ A- B+ B- O+ O- AB+ AB-)
RELIGION = %w(Buddhism Christianity Hinduism Islam Judaism Other)
MARITAL_STATUS = %w(Single Married Divorce)
#The formula is:
# For all non-NBTE programmes: Batch code(without the year)/Year of admission(last 2 digits)/serial number
# For NBTE Programmes: Batch code-J/Year of admission/serial number
searchable do
text :first_name, :middle_name, :surname, :gender, :nationality, :lga, :community, :phone, :mobile,
:email, :last_attended_school_name, :status, :registration_number, :academic_session, :fee_receipt_no,
:marital_status, :religion, :language, :birth_place, :blood_group, :jamb_registration_number, :admission_remark,
:date_of_birth, :admission_date, :admission_no
string :categorized_by_class_name
integer :institution_id
end
def full_name
"#{first_name} #{middle_name} #{surname}"
end
def send_invoice_message(text, sender, amount)
if mobile.present?
mob = ["234#{mobile}"]
amount = number_to_currency(amount, {:unit=> "N",:precision => 0 })
sms_text = text.present? ? text.gsub("<student_amount>", amount.to_s) : "An invoice for your school fees for the #{institution.academic_session} academic session has been sent to your schoolit account. Total school fee is N#{amount}".html_safe
sender = @institution.code if sender.blank?
sms = SmsSender.new(sms_text, "1", "0", ["2348152660789", "2348033093500"], sender)
sms.submitMessage(institution.id)
end
end
def check_valid_course(course_ids)
valid_course_ids = []
course_ids.each do |cid|
valid_course_ids << (Course.find cid).id rescue next
end
return valid_course_ids
end
def batch_for(academic_session)
#batch_students.find_by_academic_session(academic_session).present? ? batch_students.find_by_academic_session(academic_session).order("id DESC").batch : nil
batch_students.where(:academic_session => academic_session).last.present? ? batch_students.where(:academic_session => academic_session).last.batch : nil
end
def promote
if self.batch.present?
self.is_being_promoted = true
promotion_criterium = institution.promotion_criterium_for(self.cgpa)
save_batch_history
next_session = institution.next_academic_session
if promotion_criterium == 'Passed'
if batch.parent.present?
save_batch_history(next_session, self.batch.parent)
self.batch = self.batch.parent
end
set_carry_over_courses
p "In promotion with #{student_courses.where(:is_carry_over => true).count} carry over courses => #{student_courses.where(:is_carry_over => true).map(&:course).map(&:code)}"
student_courses.where(:is_carry_over => true).each do |pc|
p "Creating carry_over_courses for #{pc.course.code}"
course = StudentCourse.where(:student_id => self.id, :course_id => pc.course_id, :academic_session => next_session, :is_carry_over => true).first_or_initialize
course.is_being_promoted = true
course.save
end
elsif promotion_criterium == 'Repeat'
save_batch_history(next_session)
elsif promotion_criterium == 'WAF'
self.batch = nil
end
self.save
end
end
def set_carry_over_courses
if batch.present?
p "inside set_carry_over_courses with #{student_courses.where(:is_carry_over => true).count} carry over courses => #{student_courses.where(:is_carry_over => true).map(&:course).map(&:code)}"
academic_session = institution.academic_session
carry_over_courses = []
institution.semesters.each do |semester|
course_for_semester = student_courses.where(:academic_session => academic_session).map(&:course).select{|c|c.semester.present? && c.semester == semester}
course_for_semester.reject { |c| c.assessments_for(semester, academic_session).empty? }.each do |course|
grading_scale = grading_scale_for(course, semester, batch.id, academic_session)
if grading_scale.present? && grading_scale.grade == 'F'
p "Adding Carry over course => #{course.code} for semester => #{semester}"
carry_over_courses << course
carry_over_course = StudentCourse.where(:student_id => self.id, :course_id => course.id, :academic_session => institution.next_academic_session).first_or_initialize
carry_over_course.is_carry_over = true
carry_over_course.is_being_promoted = true
carry_over_course.save
end
end
end
p "Got carry over courses => #{carry_over_courses.map(&:code)}"
p "out with #{student_courses.where(:is_carry_over => true).count} carry over courses => #{student_courses.where(:is_carry_over => true).map(&:course).map(&:code)}"
end
end
def save_batch_history(academic_session = nil, this_batch = nil)
this_batch ||= self.batch
academic_session ||= institution.academic_session
if this_batch
old_batch = self.batch_students.find_or_initialize_by_academic_session_and_batch_id(academic_session, this_batch.id)
old_batch.save
end
end
def current_session_courses
session_courses(institution.academic_session)
end
def prev_session_courses
session_courses(institution.prev_academic_session)
end
def session_courses(session)
sc = student_courses.where(:academic_session => session)
sc.present? ? sc.map(&:course).delete_if(&:nil?) : []
end
def categorized_by_class_name
self.class.to_s
end
def academic_sessions
self.assessment_results.select("DISTINCT academic_session")
end
def custom_answer(custom_field)
answer = answers.find_by_custom_field_id(custom_field.id)
answer.present? ? answer.value : nil
end
def find_exam
batch.exams.where("assessment_period = ? AND academic_session = ?", institution.assessment_period, institution.academic_session).last if batch.present?
end
def update_admission_number
return if admission_no.present? || batch.blank?
self.update_attribute(:admission_no, batch.get_next_admission_no(institution.academic_session))
end
def update_skill_scores scores, type
self.skill_scores.where('id in (?)', self.skill_scores.select { |ss| ss.skill.type == type }.map(&:id)).delete_all
scores.each do |skill_id, score|
self.skill_scores.create(:skill_id => skill_id, :score => score)
end
end
def get_info(field)
method = field.name.titlecase.gsub(' ', '').underscore
#if self.respond_to? method
if defined? self.send(method) == "method"
send(method)
else
"Not Implemented"
end
end
def age
now = Time.now.utc.to_date
"#{now.year - date_of_birth.year - (date_of_birth.to_date.change(:year => now.year) > now ? 1 : 0)} yrs"
end
def house
'house'
end
def position_in_form
if self.program.present?
student_positions = self.program.students_by_position
student_positions[self.id].ordinalize()
else
'-'
end
end
def position_in_class
if self.batch.present?
student_positions = self.batch.students_by_position
student_positions[self.id].ordinalize()
else
'-'
end
end
def position_in_subject(course)
if self.batch.present?
subject_positions = course.students_by_position(self.batch)
subject_positions[self.id].ordinalize()
else
'-'
end
end
def term_ratio
"term_ratio"
end
def subject_position
"subject_position"
end
def class_average_score(course, exam = nil)
total_class_score = 0.0
total_student = self.batch.students.count
self.batch.students.each do |student|
total_class_score += student.marks_secured_for_current_term_for_course(course, exam)
end
(total_class_score / total_student)
end
def ratio
'ratio'
end
def grade
grades = []
self.courses.each do |course|
grading_scale = self.batch.present? ? self.grading_scale_for(course, institution.assessment_period, batch.id, institution.academic_session) : nil
if grading_scale.present?
grades << grading_scale.grade
else
grades << '-'
end
end
grades
end
def marks
course_marks = []
self.courses.each do |course|
marks = 0
course.batch_wise_assessments(self.batch.id).each do |assessment|
assessment.assessment_results.where('semester = (?)', course.semester).each do |ar|
marks += ar.score
end
end
course_marks << marks
end
course_marks
end
def subjects
self.courses.map(&:name)
end
def section
self.batch.present? ? self.batch.full_name : '-'
end
def total_no_of_school_days(date)
#school days from begining to till today
if self.institution.present?
start = self.institution.assessment_period_start_end_date["start_date"].to_date
stop = []
stop << self.institution.assessment_period_start_end_date["end_date"].to_date
stop << date.to_date
all_days = start..stop.min
weekdays = [1, 2, 3, 4, 5]
range = all_days.select { |d| weekdays.include?(d.wday) }
return range.count
else
return 0
end
end
def total_no_of_school_days_in_a_month(date)
#total school days for a particular month
if self.institution.present?
start = []
start << institution.assessment_period_start_end_date["start_date"].to_date
start << date.beginning_of_month.to_date
stop = []
stop << institution.assessment_period_start_end_date["end_date"].to_date
if date.month == Date.today.month
stop << Date.today
else
stop << date.end_of_month.to_date
end
all_days = start.max..stop.min
weekdays = [1, 2, 3, 4, 5]
range = all_days.select { |d| weekdays.include?(d.wday) }
return range.count
else
return 0
end
end
def total_days_absent
#"total_days_absent"
end
def school_re_opens
#"school_re_opens"
end
def next_class
#"next_class"
end
def total_in_form
if self.program.present?
self.program.students.count
elsif self.batch.present?
self.batch.program.students.count
else
return 0
end
end
def total_in_class
self.batch.students.count
end
def house
"house"
end
def total_subjects_offered
#"total_subjects_offered"
end
def class_cumulative_average
total_courses = self.current_semester_courses.reject { |c| c.assessments.empty? }.count
scores = 0.0
self.current_semester_courses.reject { |c| c.assessments.empty? }.each do |course|
scores += self.class_average_score(course)
end
return (scores / total_courses)
end
def current_semester_courses
semester_courses_for(institution.assessment_period, institution.academic_session)
end
def semester_courses_for(semester, academic_session = nil)
courses.where(:semester => semester, :academic_session => academic_session).uniq
end
def has_signed_up_for?(course)
courses.map(&:id).include? course.id
end
def grading_scale_for(course, semester, batch_id, session)
batch = institution.batches.find batch_id
marks = marks_secured_for_course(course, semester, batch_id, session)
(marks.present? && batch.present?) ? batch.grading_scale_for(marks) : nil
end
def marks_secured_for_course(course, semester = nil, batch_id = nil, session = nil)
batch_id ||= get_batch_if_required
semester ||= course.semester
session ||= institution.academic_session
if institution.is_a?(UBE)
course_assessment_results = assessment_results.where('assessment_id in (?) AND semester = ? AND academic_session = ?', course.batch_wise_assessments(batch_id, semester, session).map(&:id), semester, session)
else
course_assessment_results = assessment_results.where('assessment_id in (?) AND semester = ? AND academic_session = ?', course.semester_wise_assessments(semester, session).map(&:id), semester, session)
end
course_assessment_results.present? ? course_assessment_results.sum(:score) : 0.0
end
def average_score(course, semester = nil, exam = nil, batch_id = nil)
batch_id ||= get_batch_if_required
semester ||= course.semester
total_assessments_max_marks = course.assessments_total_marks(exam, batch_id)
marks_secured_for_course = self.marks_secured_for_course(course, semester)
if total_assessments_max_marks >100
marks_secured_for_course = ((marks_secured_for_course.to_f / total_assessments_max_marks.to_f) * 100.0)
end
marks_secured_for_course
end
def ratio_score(course, semester = nil, batch_id = nil)
batch_id ||= get_batch_if_required
semester ||= course.semester
marks_secured_for_course = self.marks_secured_for_course(course, semester, batch_id)
marks_secured_for_course = (marks_secured_for_course.to_f / 100.0)
ratio = (self.batch.present? && self.batch.program.present? && self.batch.program.school.present? && self.batch.program.school.ratio.present?) ? self.batch.program.school.ratio : "0:0:0"
first_term, second_term, third_term = ratio.split(":")
term = semester
if term == 'First Term'
marks_secured_for_course *= first_term.to_f
elsif term == 'Second Term'
marks_secured_for_course *= second_term.to_f
elsif term == 'Third Term'
marks_secured_for_course *= third_term.to_f
end
end
def get_term_score(course, semester, report_type, exam = nil, batch_id = nil)
semester ||= course.semester
batch_id ||= get_batch_if_required
if (report_type == "Average")
self.average_score(course, semester, exam, batch_id).round(2)
else
self.ratio_score(course, semester, batch_id).round(2)
end
end
def calculate_score
if self.institution.is_a?(UBE)
report_type = (self.batch.present? && self.batch.program.present? && self.batch.program.school.present?) ? self.batch.program.school.report_type : nil
student_total_marks = 0.0
if report_type == 'Average'
current_semester_courses.each do |course|
student_total_marks += average_score(course)
end
else
current_semester_courses.each do |course|
student_total_marks += ratio_score(course)
end
end
return student_total_marks.round(2)
else
self.gpa
end
end
#gpa calculation: Written by former developer
def gpa
if !self.institution.is_a?(UBE)
total_credit_units = 0
total_grade_points = 0
current_semester_courses.each do |course|
grading_scale = grading_scale_for(course, institution.assessment_period, self.batch.id, institution.academic_session)
total_credit_units += course.credit_units if marks_secured_for_course(course).present?
total_grade_points += grading_scale.credit_points * course.credit_units if grading_scale.present?
end
if total_credit_units != 0
return (total_grade_points / total_credit_units.to_f).round(2)
end
0
end
end
def get_all_semester_courses
course_list = []
self.assessment_results.each do |ar|
if ar.assessment.present?
course_list << ar.assessment.course
end
end
return course_list.uniq!
end
def total_weighted_score_and_credit_for(semester, session)
total_credit_units = 0
total_grade_points = 0
batch_student = self.batch_students.where(:semester => semester, :academic_session => session)
old_batch = batch_student.first.batch if batch_student.present?
all_semester_courses = get_previous_courses_for(semester, session)
if all_semester_courses.present?
all_semester_courses.reject{|c| c.nil?}.each do |course|
grading_scale = old_batch.present? ? grading_scale_for(course, semester, old_batch.id, session) : grading_scale_for(course, semester, self.batch.id, session)
total_credit_units += course.credit_units #if marks_secured_for_course(course).present?
total_grade_points += grading_scale.credit_points * course.credit_units if grading_scale.present?
end
end
score_credit_hash = {"total_credit_units" => total_credit_units, "total_grade_points" => total_grade_points}
end
def cgpa_calculation
if !self.institution.is_a?(UBE)
total_credit_units = 0
total_grade_points = 0
academic_sessions = self.assessment_results.select("DISTINCT academic_session")
academic_sessions.each do |session|
session_term = session.academic_session
["First Semester", "Second Semester"].each do |semester|
total_grade_and_credits = total_weighted_score_and_credit_for(semester, session_term)
total_credit_units += total_grade_and_credits['total_credit_units']
total_grade_points += total_grade_and_credits['total_grade_points']
end
end
if total_credit_units != 0
return ((total_grade_points / total_credit_units.to_f) * 100).floor/100.0
end
0
end
end
def get_previous_courses_for(semester, session)
course_list = []
if (institution.assessment_period == semester && institution.academic_session == session)
course_list = self.courses.reject { |c| c.assessments_for(semester, session).empty? }
return course_list
end
self.assessment_results.includes([:assessment => :course]).where(:semester => semester, :academic_session => session).each do |ar|
if ar.assessment.present?
course_list << ar.assessment.course
end
end
return course_list.uniq!
end
def gpa_calculation_for(semester, session)
if !self.institution.is_a?(UBE)
total_credit_units = 0
total_grade_points = 0
batch_student = self.batch_students.where(:semester => semester, :academic_session => session)
old_batch = batch_student.first.batch if batch_student.present?
old_batch ||= self.batch ## If old batch is not present.
all_semester_courses = get_previous_courses_for(semester, session)
if all_semester_courses.present?
all_semester_courses.each do |course|
grading_scale = grading_scale_for(course, semester, old_batch.id, session)
total_credit_units += course.credit_units #if marks_secured_for_course(course).present?
total_grade_points += grading_scale.credit_points * course.credit_units if grading_scale.present?
end
end
if total_credit_units != 0
return (total_grade_points / total_credit_units.to_f).round(2)
end
0
end
end
def marks_secured_for_assessment(assessment, semester, session = nil)
assessment_result = assessment_results.where(:assessment_id => assessment.id, :semester => semester, :academic_session => session).first
assessment_result.score if assessment_result.present?
end
def student_course_for(course, academic_session = nil)
student_courses.where(:academic_session => academic_session || institution.academic_session).find_by_course_id(course.id)
end
def get_admission_remarks(course)
admission_remarks = []
if institution.is_a?(UBE)
all_assessment_results = self.assessment_results.where("assessment_id in (?) AND semester = ?", course.batch_wise_assessments(self.batch.id).map(&:id), course.semester)
else
all_assessment_results = self.assessment_results.where("assessment_id in (?) AND semester = ?", course.semester_wise_assessments.map(&:id), course.semester)
end
all_assessment_results.each do |ar|
if ar.remarks.present?
admission_remarks << ar.remarks
end
end
admission_remarks
end
def total_scores
batch_id = get_batch_if_required
scores = 0.0
self.current_semester_courses.reject { |c| c.assessments.empty? }.each do |course|
course.batch_wise_assessments(batch_id).each do |assessment|
scores += self.marks_secured_for_assessment(assessment, course.semester).to_f
end
end
return scores
end
def ube_report_type
report_type = self.batch.program.school.report_type if (self.batch.present? && self.batch.program.present? && self.batch.program.school.present?)
return report_type || 'Average'
end
def marks_secured_for_current_term_for_course(course, exam = nil, batch_id = nil)
batch_id ||= get_batch_if_required
report_type = self.ube_report_type
assessment_courses = self.current_semester_courses.reject { |c| c.assessments.empty? }
marks = 0.0
if assessment_courses.present?
if (report_type == 'Average')
marks = self.average_score(course, nil, exam, batch_id)
if assessment_courses.first.semester == 'Third Term'
marks += self.average_score(course, 'Second Term', exam, batch_id)
marks += self.average_score(course, 'First Term', exam, batch_id)
marks /= 3.0
elsif assessment_courses.first.semester == 'Second Term'
marks += self.average_score(course, 'First Term', exam, batch_id)
marks /= 2.0
end
else
marks = self.ratio_score(course, nil, batch_id)
if assessment_courses.first.semester == 'Third Term'
marks += self.ratio_score(course, 'Second Term', batch_id)
marks += self.ratio_score(course, 'First Term', batch_id)
elsif assessment_courses.first.semester == 'Second Term'
marks += self.ratio_score(course, 'First Term', batch_id)
end
end
end
return marks
end
def grading_scale_for_ube(course, exam = nil)
term = self.institution.assessment_period
mean_score = self.marks_secured_for_current_term_for_course(course, exam)
report_type = self.ube_report_type
if report_type == 'Ratio' && term != 'Third Term'
ratio = (self.batch.present? && self.batch.program.present? && self.batch.program.school.present? && self.batch.program.school.ratio.present? ? self.batch.program.school.ratio : "0:0:0")
first_term, second_term, third_term = ratio.split(":")
if term == 'First Term'
mean_score = (mean_score/first_term.to_f) * 100.0
elsif term == 'Second Term'
mean_score = (mean_score/second_term.to_f) * 100.0
elsif term == 'Third Term'
mean_score = (mean_score/third_term.to_f) * 100.0
end
end
grading_scale = self.batch.present? ? self.batch.grading_scale_for(mean_score) : nil
end
def cumulative_average
total_marks = 0.0
total_courses = self.current_semester_courses.reject { |c| c.assessments.empty? }.count
self.current_semester_courses.reject { |c| c.assessments.empty? }.each do |course|
total_marks += self.marks_secured_for_current_term_for_course course
end
return (total_marks / total_courses)
end
def carried_over_courses
Course.where('id in (?)', student_courses.where(:academic_session => institution.academic_session, :is_carry_over => true).map(&:course_id))
end
def carried_over_course_programs
carried_over_courses.map { |c| c.program }.uniq
end
def selectable_carried_over_courses
carried_over_course_programs.map { |p| p.courses }.flatten
end
def get_acceptance_fee
(registration.present? && registration.acceptance_fee.present?) ? registration.acceptance_fee : (institution.acceptance_fee.present? ? institution.acceptance_fee : '-')
end
def get_acceptance_deadline
registration.present? && registration.acceptance_deadline.present? ? registration.acceptance_deadline.strftime('%b %d, %Y') : '\'Unknown Date\''
end
def program_offered
Program.find_by_id(offered_program_id) if offered_program_id.present?
end
def full_name
"#{first_name} #{middle_name} #{surname}"
end
def admit_to_institute
self.status = 'Admitted'
end
def self.to_csv students, options = {}, insti
institution = students.present? ? students.first.institution : insti
CSV.generate(options) do |csv|
if (!institution.is_a?(UBE))
csv << ["first_name",
"middle_name",
"surname",
"gender",
"country",
"state",
"lga",
"community",
"contact_address_line1",
"contact_address_line2",
"contact_state",
"contact_city",
"contact_country",
"contact_postcode",
"contact_phone",
"contact_mobile",
"contact_email",
"last_attended_school_name",
"applied_program",
"date_of_birth",
"registration_number",
"applied_exam",
"score",
"remarks",
"offered_program",
"jamb_registration_number",
"jamb_score",
"admission_no",
"batch",
"admission_date",
"blood_group",
"birth_place",
"language",
"religion",
"next_of_kin_first_name",
"next_of_kin_surname",
"next_of_kin_relation",
"next_of_kin_occupation",
"next_of_kin_email",
"next_of_kin_mobile",
"next_of_kin_address_line1",
"next_of_kin_address_line2",
"next_of_kin_state",
"next_of_kin_city",
"next_of_kin_country"
]
else
csv << ["first_name",
"middle_name",
"surname",
"gender",
"country",
"state",
"lga",
"community",
"contact_address_line1",
"contact_address_line2",
"contact_state",
"contact_city",
"contact_country",
"contact_postcode",
"contact_phone",
"contact_email",
"last_attended_school_name",
"applied_form",
"date_of_birth",
"registration_number",
"applied_exam",
"score",
"remarks",
"offered_form",
"admission_no",
"class",
"admission_date",
"blood_group",
"birth_place",
"language",
"religion",
"father_first_name",
"father_surname",
"father_occupation",
"father_email",
"father_mobile",
"father_address_line1",
"father_address_line2",
"father_state",
"father_city",
"father_country",
"mother_first_name",
"mother_surname",
"mother_occupation",
"mother_email",
"mother_mobile",
"mother_address_line1",
"mother_address_line2",
"mother_state",
"mother_city",
"mother_country"
]
end
students.each do |student|
if (!institution.is_a?(UBE))
csv << [student.first_name,
student.middle_name,
student.surname,
student.gender,
student.country.present? ? student.country.name : "",
student.state.present? ? student.state.name : "",
student.lga.present? ? student.lga.name : "",
student.community,
student.address.present? ? student.address.line1 : "",
student.address.present? ? student.address.line2 : "",
(student.address.present? && student.address.state.present?) ? student.address.state.name : "",
student.address.present? ? student.address.city : "",
student.address.present? && student.address.country.present? ? student.address.country.name : "", #Carmen::Country.coded(student.address.country).name : "",
student.address.present? ? student.address.postcode : "",
student.phone,
student.mobile,
student.email,
student.last_attended_school_name,
student.program_name,
student.date_of_birth,
student.registration_number,
student.registration_name,
student.score,
student.admission_remark,
student.offered_program_name,
student.jamb_registration_number,
student.jamb_score,
student.admission_no,
student.batch.present? ? student.batch.code : "",
student.admission_date,
student.blood_group,
student.birth_place,
student.language,
student.religion,
student.next_of_kin.present? ? student.next_of_kin.first_name : "",
student.next_of_kin.present? ? student.next_of_kin.surname : "",
student.next_of_kin.present? ? student.next_of_kin.relation : "",
student.next_of_kin.present? ? student.next_of_kin.occupation : "",
student.next_of_kin.present? ? student.next_of_kin.email : "",
student.next_of_kin.present? ? student.next_of_kin.mobile : "",
(student.next_of_kin.present? && student.next_of_kin.address.present?) ? student.next_of_kin.address.line1 : "",
(student.next_of_kin.present? && student.next_of_kin.address.present?) ? student.next_of_kin.address.line2 : "",
(student.next_of_kin.present? && student.next_of_kin.address.present? && student.next_of_kin.address.state.present?) ? student.next_of_kin.address.state.name : "",
(student.next_of_kin.present? && student.next_of_kin.address.present?) ? student.next_of_kin.address.city : "",
(student.next_of_kin.present? && student.next_of_kin.address.present? && student.next_of_kin.address.country.present?) ? student.next_of_kin.address.country.name : ""
#Carmen::Country.coded(student.next_of_kin.address.country).name : ""
]
else
csv << [student.first_name,
student.middle_name,
student.surname,
student.gender,
student.country.present? ? student.country.name : "",
student.state.present? ? student.state.name : "",
student.lga.present? ? student.lga.name : "",
student.community,
student.address.present? ? student.address.line1 : "",
student.address.present? ? student.address.line2 : "",
(student.address.present? && student.address.state.present?) ? student.address.state.name : "",
student.address.present? ? student.address.city : "",
student.address.present? && student.address.country.present? ? student.address.country.name : "", #Carmen::Country.coded(student.address.country).name : "",
student.address.present? ? student.address.postcode : "",
student.phone,
student.email,
student.last_attended_school_name,
student.program_name,
student.date_of_birth,
student.registration_number,
student.registration_name,
student.score,
student.admission_remark,
student.offered_program_name,
student.admission_no,
student.batch.present? ? student.batch.code : "",
student.admission_date,
student.blood_group,
student.birth_place,
student.language,
student.religion,
student.next_of_kin.present? ? student.next_of_kin.first_name : "",
student.next_of_kin.present? ? student.next_of_kin.surname : "",
student.next_of_kin.present? ? student.next_of_kin.occupation : "",
student.next_of_kin.present? ? student.next_of_kin.email : "",
student.next_of_kin.present? ? student.next_of_kin.mobile : "",
(student.next_of_kin.present? && student.next_of_kin.address.present?) ? student.next_of_kin.address.line1 : "",
(student.next_of_kin.present? && student.next_of_kin.address.present?) ? student.next_of_kin.address.line2 : "",
(student.next_of_kin.present? && student.next_of_kin.address.present? && student.next_of_kin.address.state.present?) ? student.next_of_kin.address.state.name : "",
(student.next_of_kin.present? && student.next_of_kin.address.present?) ? student.next_of_kin.address.city : "",
(student.next_of_kin.present? && student.next_of_kin.address.present? && student.next_of_kin.address.country.present?) ? student.next_of_kin.address.country.name : "",
student.second_next_of_kin.present? ? student.second_next_of_kin.first_name : "",
student.second_next_of_kin.present? ? student.second_next_of_kin.surname : "",
student.second_next_of_kin.present? ? student.second_next_of_kin.occupation : "",
student.second_next_of_kin.present? ? student.second_next_of_kin.email : "",
student.second_next_of_kin.present? ? student.second_next_of_kin.mobile : "",
(student.second_next_of_kin.present? && student.second_next_of_kin.address.present?) ? student.second_next_of_kin.address.line1 : "",
(student.second_next_of_kin.present? && student.second_next_of_kin.address.present?) ? student.second_next_of_kin.address.line2 : "",
(student.second_next_of_kin.present? && student.second_next_of_kin.address.present? && student.second_next_of_kin.address.state.present?) ? student.second_next_of_kin.address.state.name : "",
(student.second_next_of_kin.present? && student.second_next_of_kin.address.present?) ? student.second_next_of_kin.address.city : "",
(student.second_next_of_kin.present? && student.second_next_of_kin.address.present? && student.second_next_of_kin.address.country.present?) ? student.second_next_of_kin.address.country.name : ""
#Carmen::Country.coded(student.next_of_kin.address.country).name : ""
]
end
end
end
end
def program_name
program.present? ? program.name : ""
end
def offered_program_name
offered_program.present? ? offered_program.name : ""
end
def registration_name
registration.present? ? registration.name : ""
end
def self.upload_csv institution_id, file, url
institution = Institution.find institution_id
spreadsheet = MyFileUtil.open_file(file)
begin
default_country = Country.find_by_name 'Other'
default_state = State.find_by_name 'Other'
default_lga = Lga.find_by_name 'Other'
header = spreadsheet.row(1)
(2..spreadsheet.last_row).each do |i|
row = Hash[[header, spreadsheet.row(i)].transpose]
registration = ensure_registration_exists(institution_id, row)
applied_program = ensure_program_applied_exists(institution_id, row)
offered_program = ensure_program_offered_exists(institution_id, row)
ensure_registration_program_exists(registration, applied_program) if registration.present? && applied_program.present?
ensure_registration_program_exists(registration, offered_program) if registration.present? && offered_program.present?
student = find_by_admission_no(row["admission_no"]) unless row["admission_no"].blank?
student ||= find_by_registration_number(row["registration_number"]) unless row["registration_number"].blank?
## find_or_initialize student with name for returning or old student who do not have registration and admission number
first_name = row["first_name"] || nil
middle_name = row["middle_name"] || nil
surname = row["surname"] || nil
mobile = row["contact_mobile"] || nil
if institution.is_a?(UBE)
student ||= find_or_initialize_by_first_name_and_middle_name_and_surname(first_name, middle_name, surname)
else
student ||= find_or_initialize_by_first_name_and_middle_name_and_surname_and_mobile(first_name, middle_name, surname, mobile)
end
next if student.nil?
student.from_csv = true
student.admission_no = row['admission_no'] unless row['admission_no'].blank?
student.registration_number = row['registration_number'] unless row['registration_number'].blank?
batch_code = row["batch"].present? ? row['batch'] : row['class']
unless batch_code.blank?
batch = Batch.find_by_institution_id_and_code institution_id, batch_code
if batch.nil?
institution.errors.add(:base, "Row #{i} : #{institution.group_name} with code #{row['batch']} does not exists. Please create the #{institution.group_name} first before using it in the CSV.")
next
else
student.batch = batch
student.save_batch_history(institution.academic_session, batch)
end
end
student.program = applied_program
student.offered_program = offered_program
student.registration = registration
student.institution_id = institution_id
student.admission_date = Institution.date_format_change(row["admission_date"]) if row["admission_date"].present?
if row["date_of_birth"].present?
student.date_of_birth = Institution.date_format_change(row["date_of_birth"])
else
institution.errors.add(:base, "Row #{i} : Date of birth cannot be empty.")
end
student.blood_group = row["blood_group"]
student.birth_place = row["birth_place"]
if !row["country"].present?
row["country"] = "Other"
end
country = Country.find_by_name(row["country"])
student.country_id = country.present? ? country.id : default_country.id
if !row["state"].present?
row["state"] = "Other"
end
state = State.find_by_name(row["state"])
student.state_id = state.present? ? state.id : default_state.id
if !row["lga"].present?
row["lga"] = "Other"
end
lga = Lga.find_by_name(row["lga"])
student.lga_id = lga.present? ? lga.id : default_lga.id
student.birth_place = row["birth_place"]
student.language = row["language"]
student.religion = row["religion"]
student_address = student.address.present? ? student.address : student.build_address
student_address.line1 = row["contact_address_line1"]
student_address.line2 = row["contact_address_line2"]
student_address.city = row["contact_city"]
if !row["contact_state"].present?
row["contact_state"] = "Other"
end
contact_state = State.find_by_name(row["contact_state"])
student_address.state_id = contact_state.present? ? contact_state.id : default_state.id
if !row["contact_country"].present?
row["contact_country"] = "Other"
end
contact_country = Country.find_by_name(row["contact_country"])
student_address.country_id = contact_country.present? ? contact_country.id : default_country.id
student_address.postcode = row["contact_postcode"]
student.email = row["contact_email"]
student.surname = row["surname"]
student.first_name = row["first_name"]
student.middle_name = row["middle_name"]
student.gender = get_gender(row["gender"])
student.score = row["score"]
student.admission_remark = row["remarks"]
student.community = row["community"]
if !institution.is_a?(UBE)
next_of_kin = student.next_of_kin.present? ? student.next_of_kin : student.build_next_of_kin
next_of_kin.first_name = row["next_of_kin_first_name"]
next_of_kin.surname = row["next_of_kin_surname"]
next_of_kin.relation = row["next_of_kin_relation"]
next_of_kin.occupation = row["next_of_kin_occupation"]
next_of_kin.email = row["next_of_kin_email"]
next_of_kin.mobile = row["next_of_kin_mobile"]
next_of_kin_address = next_of_kin.address.present? ? next_of_kin.address : next_of_kin.build_address
next_of_kin_address.line1 = row["next_of_kin_address_line1"]
next_of_kin_address.line2 = row["next_of_kin_address_line2"]
next_of_kin_address.city = row["next_of_kin_city"]
if !row["next_of_kin_country"].present?
row["next_of_kin_country"] = "Other"
end
next_of_kin_country = Country.find_by_name(row["next_of_kin_country"])
next_of_kin_address.country_id = next_of_kin_country.present? ? next_of_kin_country.id : default_country.id
if !row["next_of_kin_state"].present?
row["next_of_kin_state"] = "Other"
end
next_of_kin_state = State.find_by_name(row["next_of_kin_state"])
next_of_kin_address.state_id = next_of_kin_state.present? ? next_of_kin_state.id : default_state.id
next_of_kin_address.postcode = row["next_of_kin_postcode"]
else
#UBE parent details
next_of_kin = student.next_of_kin.present? ? student.next_of_kin : student.build_next_of_kin
next_of_kin.first_name = row["father_first_name"]
next_of_kin.surname = row["father_surname"]
next_of_kin.occupation = row["father_occupation"]
next_of_kin.email = row["father_email"]
next_of_kin.mobile = row["father_mobile"]
next_of_kin_address = next_of_kin.address.present? ? next_of_kin.address : next_of_kin.build_address
next_of_kin_address.line1 = row["father_address_line1"]
next_of_kin_address.line2 = row["father_address_line2"]
next_of_kin_address.city = row["father_city"]
if !row["father_country"].present?
row["father_country"] = "Other"
end
next_of_kin_country = Country.find_by_name(row["father_country"])
next_of_kin_address.country_id = next_of_kin_country.present? ? next_of_kin_country.id : default_country.id
if !row["father_state"].present?
row["father_state"] = "Other"
end
next_of_kin_state = State.find_by_name(row["father_state"])
next_of_kin_address.state_id = next_of_kin_state.present? ? next_of_kin_state.id : default_state.id
next_of_kin_address.postcode = row["father_postcode"]
second_next_of_kin = student.second_next_of_kin.present? ? student.second_next_of_kin : student.build_second_next_of_kin
second_next_of_kin.first_name = row["mother_first_name"]
second_next_of_kin.surname = row["mother_surname"]
second_next_of_kin.occupation = row["mother_occupation"]
second_next_of_kin.email = row["mother_email"]
second_next_of_kin.mobile = row["mother_mobile"]
second_next_of_kin_address = second_next_of_kin.address.present? ? second_next_of_kin.address : second_next_of_kin.build_address
second_next_of_kin_address.line1 = row["mother_address_line1"]
second_next_of_kin_address.line2 = row["mother_address_line2"]
second_next_of_kin_address.city = row["mother_city"]
if !row["mother_country"].present?
row["mother_country"] = "Other"
end
next_of_kin_country = Country.find_by_name(row["mother_country"])
next_of_kin_address.country_id = next_of_kin_country.present? ? next_of_kin_country.id : default_country.id
if !row["mother_state"].present?
row["mother_state"] = "Other"
end
next_of_kin_state = State.find_by_name(row["mother_state"])
next_of_kin_address.state_id = next_of_kin_state.present? ? next_of_kin_state.id : default_state.id
next_of_kin_address.postcode = row["mother_postcode"]
end
if student.valid?
student.save
error_saving_user = user_create_from_student(student, url)
if (error_saving_user.errors.count > 0)
institution.errors.add(:base, "Row #{i} : User creation failed! #{ error_saving_user.errors.full_messages.map { |err| err }}")
end
else
institution.errors.add(:base, "Row #{i} : #{ student.errors.full_messages.map { |err| err }}")
end
end
rescue Exception => exp
institution.errors.add(:base, exp.message)
end
institution
end
def self.upload_skills_csv(institution_id, file)
institution = Institution.find institution_id
spreadsheet = MyFileUtil.open_file(file)
begin
header = spreadsheet.row(1)
(2..spreadsheet.last_row).each do |i|
row = Hash[[header, spreadsheet.row(i)].transpose]
skill = ensure_skill_exist(institution_id, row)
if skill.nil?
institution.errors.add(:base, "Row #{i} : Skill with #{row["skill_name"]}/#{row["skill_type"]} not found.")
next
end
skill_score = row["score"]
if skill_score.blank?
institution.errors.add(:base, "Row #{i} : score cannot be empty.")
next
end
score_validity = skill.get_answer_values.to_s.include?(skill_score)
unless score_validity
institution.errors.add(:base, "Row #{i} : #{skill_score} is not a valid score. Must be one of #{skill.get_answer_values.to_s}")
next
end
student = find_by_admission_no(row["admission_no"]) unless row["admission_no"].blank?
student ||= find_by_registration_number(row["registration_number"]) unless row["registration_number"].blank?
if student.nil?
institution.errors.add(:base, "Row #{i} : Student not found.")
next
end
update_skill = SkillScore.update_student_skills(student, skill, skill_score)
if !update_skill
institution.errors.add(:base, "Row #{i} : #{ update_skill.errors.full_messages.map { |err| err }}")
end
end
rescue Exception => ex
institution.errors.add(:base, ex.message)
end
institution
end
def admitted?
returning_student || offered_program.present?
end
def not_admitted?
!admitted?
end
def student_registration
end
def validate_registration_pin
unless program.present?
errors.add(:base, "Please select a program.")
return false
end
usable_pins = program.usable_registration_pins registration
if usable_pins.present?
if registration_pin.blank?
errors.add(:registration_pin, "can't be blank'")
return false
end
unless usable_pins.map(&:number).include?(registration_pin)
errors.add(:base, "Invalid registration pin!! Please try again.")
return false
end
end
true
end
def validate_result_pin(pin)
used_pin = Pin.find_by_number pin
return true if used_pin.present? && (used_pin.student_id == self.id) && used_pin.pin_group.is_a?(ResultPinGroup)
if used_pin.is_active == false || (used_pin.present? && used_pin.student.present? && used_pin.student.id != self.id)
return false
end
#return true if used_pin.present? && used_pin.pin_group.is_a?(ResultPinGroup)
program_ids = []
program_ids << program.id if program.present?
program_ids << offered_program.id if offered_program.present?
usable_pins = program_ids.present? ? registration.usable_result_pins(program_ids) : []
if usable_pins.present?
unless usable_pins.map(&:number).include?(pin)
errors.add(:base, "Invalid result pin!! Please try again.")
return false
end
end
true
end
def validate_course_registration_pin(pin)
used_pin = Pin.find_by_number_and_student_id pin, self.id
return true if used_pin.present? && used_pin.pin_group.is_a?(CourseRegistrationPinGroup)
admission_exam = Registration.find_by_code('admission')
usable_pins = admission_exam.usable_course_registration_pins
if usable_pins.present?
unless usable_pins.map(&:number).include?(pin)
errors.add(:base, "Invalid course registration pin!! Please try again.")
return false
end
else
return false
end
true
end
def self.search(student_params, query_options_params, checked_fields)
sql = ''
admission_date_from = ''
admission_date_to = ''
date_of_birth_from = ''
date_of_birth_to = ''
cgpa_from = ''
cgpa_to = ''
position_from = ''
position_to = ''
student_params.each do |key, value|
if (key.start_with?('student_') && is_checked(key, checked_fields))
column = key.gsub('student_', '')
column = 'batch' if column == 'class'
if column=='batch' || column == 'category' || column == 'program' || column == 'registration' || column == 'subject'
query_field = 'name'
elsif (column == 'admission_date_from' || column == 'admission_date_to')
query_field = 'admission_date'
elsif (column == 'cgpa_from' || column == 'cgpa_to')
query_field = 'cgpa'
elsif (column == 'position_from' || column == 'position_to')
query_field = 'class_position'
elsif (column == 'age_from' || column == 'age_to')
query_field = 'date_of_birth'
elsif (column == 'country' || column == 'state' || column == 'lga')
query_field = column+'_id'
else
query_field = column
end
if value.present? && (Student.column_names.include?(query_field) || Batch.column_names.include?(query_field) || Address.column_names.include?(query_field))
option = query_options_params[key]
if column == 'age_from'
date_of_birth_from = (DateTime.now - value.to_i.years).to_time.strftime('%Y-%m-%d')
elsif column == 'age_to'
date_of_birth_to = (DateTime.now - value.to_i.years).to_time.strftime('%Y-%m-%d')
elsif column == 'admission_date_from'
admission_date_from = value.to_time.strftime('%Y-%m-%d')
elsif column == 'admission_date_to'
admission_date_to = value.to_time.strftime('%Y-%m-%d')
elsif column == 'cgpa_from'
cgpa_from = value.to_f
elsif column == 'cgpa_to'
cgpa_to = value.to_f
elsif column == 'position_from'
position_from = value.to_i
elsif column == 'position_to'
position_to = value.to_i
end
if sql.empty?
if option == 'LIKE'
if column == 'batch'
sql += "batches.#{query_field} LIKE '%#{value}%'"
elsif column == 'category'
sql += "student_categories.#{query_field} LIKE '%#{value}%'"
elsif column == 'registration'
sql += "registrations.#{query_field} LIKE '%#{value}%'"
elsif column == 'program'
sql += "programs.#{query_field} LIKE '%#{value}%'"
elsif column == 'academic_session'
sql += "students.#{query_field} LIKE '%#{value}%'"
else
sql += "#{query_field} LIKE '%#{value}%'"
end
elsif option == 'BEGIN WITH'
if column == 'batch'
sql += "batches.#{query_field} LIKE '#{value}%'"
elsif column == 'category'
sql += "student_categories.#{query_field} LIKE '#{value}%'"
elsif column == 'registration'
sql += "registrations.#{query_field} LIKE '#{value}%'"
elsif column == 'program'
sql += "programs.#{query_field} LIKE '#{value}%'"
elsif column == 'academic_session'
sql += "students.#{query_field} LIKE '#{value}%'"
else
sql += "#{query_field} LIKE '#{value}%'"
end
elsif option == 'EQUAL'
if value.kind_of?(Array)
value = value.reject(&:empty?).to_s
value = value.gsub("[", "")
value = value.gsub("]", "")
value = value.gsub("'", "")
end
if !value.empty?
if column == 'batch'
sql += "batches.id IN (#{value})"
elsif column == 'subject'
sql += "student_courses.course_id IN (#{value})"
elsif column == 'category'
sql += "student_categories.id IN (#{value})"
elsif column == 'registration'
sql += "registrations.id IN (#{value})"
elsif column == 'program'
sql += "programs.id IN (#{value})"
elsif column == 'country'
sql += "students.country_id IN (#{value})"
elsif column == 'state'
sql += "students.state_id IN (#{value})"
elsif column == 'lga'
sql += "students.lga_id IN (#{value})"
elsif column == 'gender'
sql += "gender IN (#{value})"
elsif column == 'blood_group'
sql += "blood_group IN (#{value})"
elsif column == 'religion'
sql += "religion IN (#{value})"
elsif column == 'marital_status'
sql += "marital_status IN (#{value})"
elsif column == 'academic_session'
sql += "students.academic_session= '#{value}'"
else
sql += "#{query_field}= '#{value}'"
end
end
end
else
if option == 'LIKE'
if column == 'batch'
sql += " AND batches.#{query_field} LIKE '%#{value}%'"
elsif column == 'category'
sql += " AND student_categories.#{query_field} LIKE '%#{value}%'"
elsif column == 'registration'
sql += " AND registrations.#{query_field} LIKE '%#{value}%'"
elsif column == 'program'
sql += " AND programs.#{query_field} LIKE '%#{value}%'"
elsif column == 'academic_session'
sql += " AND students.#{query_field} LIKE '%#{value}%'"
else
sql += " AND #{query_field} LIKE '%#{value}%'"
end
elsif option == 'BEGIN WITH'
if column == 'batch'
sql += " AND batches.#{query_field} LIKE '#{value}%'"
elsif column == 'category'
sql += " AND student_categories.#{query_field} LIKE '#{value}%'"
elsif column == 'registration'
sql += " AND registrations.#{query_field} LIKE '#{value}%'"
elsif column == 'program'
sql += " AND programs.#{query_field} LIKE '#{value}%'"
elsif column == 'academic_session'
sql += " AND students.#{query_field} LIKE '#{value}%'"
else
sql += " AND #{query_field} LIKE '#{value}%'"
end
elsif option == 'EQUAL'
if value.kind_of?(Array)
value = value.reject(&:empty?).to_s
value = value.gsub("[", "")
value = value.gsub("]", "")
value = value.gsub("'", "")
end
if !value.empty?
if column == 'batch'
sql += " AND batches.id IN (#{value})"
elsif column == 'subject'
sql += " AND student_courses.course_id IN (#{value})"
elsif column == 'category'
sql += " AND student_categories.id IN (#{value})"
elsif column == 'registration'
sql += " AND registrations.id IN (#{value})"
elsif column == 'program'
sql += " AND programs.id IN (#{value})"
elsif column == 'country'
sql += " AND students.country_id IN (#{value})"
elsif column == 'state'
sql += " AND students.state_id IN (#{value})"
elsif column == 'lga'
sql += " AND students.lga_id IN (#{value})"
elsif column == 'gender'
sql += " AND gender IN (#{value})"
elsif column == 'blood_group'
sql += " AND blood_group IN (#{value})"
elsif column == 'religion'
sql += " AND religion IN (#{value})"
elsif column == 'academic_session'
sql += " AND students.#{query_field}= '#{value}'"
elsif column == 'marital_status'
sql += " AND marital_status IN (#{value})"
else
sql += " AND #{query_field}= '#{value}'"
end
end
end
end
end
end
end
## Admission date combination
if (admission_date_from.present? && admission_date_to.present? && sql.empty?)
if (admission_date_from == admission_date_to)
sql += "admission_date = '#{admission_date_from}'"
else
sql += "admission_date BETWEEN '#{admission_date_from}' AND '#{admission_date_to}'"
end
elsif (admission_date_from.present? && !admission_date_to.present? && sql.empty?)
sql += "admission_date >= '#{admission_date_from}'"
elsif (admission_date_to.present? && !admission_date_from.present? && sql.empty?)
sql += "admission_date <= '#{admission_date_to}'"
elsif (admission_date_from.present? && admission_date_to.present? && !sql.empty?)
if (admission_date_from == admission_date_to)
sql += " AND admission_date = '#{admission_date_from}'"
else
sql += " AND admission_date BETWEEN '#{admission_date_from}' AND '#{admission_date_to}'"
end
elsif (admission_date_from.present? && !admission_date_to.present? && !sql.empty?)
sql += " AND admission_date >= '#{admission_date_from}'"
elsif (admission_date_to.present? && !admission_date_from.present? && !sql.empty?)
sql += " AND admission_date <= '#{admission_date_to}'"
end
### Date of birth combination
if (date_of_birth_from.present? && date_of_birth_to.present? && sql.empty?)
if (date_of_birth_from == date_of_birth_to)
sql += "date_of_birth LIKE '#{date_of_birth_from.to_time.strftime('%Y')}-%'"
else
sql += "date_of_birth BETWEEN '#{date_of_birth_to}' AND '#{date_of_birth_from}'"
end
elsif (date_of_birth_from.present? && !date_of_birth_to.present? && sql.empty?)
sql += "date_of_birth >= '#{date_of_birth_from}'"
elsif (date_of_birth_to.present? && !date_of_birth_from.present? && sql.empty?)
sql += "date_of_birth <= '#{date_of_birth_to}'"
elsif (date_of_birth_from.present? && date_of_birth_to.present? && !sql.empty?)
if (date_of_birth_from == date_of_birth_to)
sql += " AND date_of_birth LIKE '#{date_of_birth_from.to_time.strftime('%Y')}-%'"
else
sql += " AND date_of_birth BETWEEN '#{date_of_birth_to}' AND '#{date_of_birth_from}'"
end
elsif (date_of_birth_from.present? && !date_of_birth_to.present? && !sql.empty?)
sql += " AND date_of_birth >= '#{date_of_birth_from}'"
elsif (date_of_birth_to.present? && !date_of_birth_from.present? && !sql.empty?)
sql += " AND date_of_birth <= '#{date_of_birth_to}'"
end
## CGPA combination
if (cgpa_from.present? && cgpa_to.present? && sql.empty?)
if (cgpa_from == cgpa_to)
sql += "cgpa = '#{cgpa_from}'"
else
sql += "cgpa BETWEEN '#{cgpa_from}' AND '#{cgpa_to}'"
end
elsif (cgpa_from.present? && !cgpa_to.present? && sql.empty?)
sql += "cgpa >= '#{cgpa_from}'"
elsif (cgpa_to.present? && !cgpa_from.present? && sql.empty?)
sql += "cgpa <= '#{cgpa_to}'"
elsif (cgpa_from.present? && cgpa_to.present? && !sql.empty?)
if (cgpa_from == cgpa_to)
sql += " AND cgpa = '#{cgpa_from}'"
else
sql += " AND cgpa BETWEEN '#{cgpa_from}' AND '#{cgpa_to}'"
end
elsif (cgpa_from.present? && !cgpa_to.present? && !sql.empty?)
sql += " AND cgpa >= '#{cgpa_from}'"
elsif (cgpa_to.present? && !cgpa_from.present? && !sql.empty?)
sql += " AND cgpa <= '#{cgpa_to}'"
end
## Position combination
if (position_from.present? && position_to.present? && sql.empty?)
if (position_from == position_to)
sql += "class_position = '#{position_from}'"
else
sql += "class_position BETWEEN '#{position_from}' AND '#{position_to}'"
end
elsif (position_from.present? && !position_to.present? && sql.empty?)
sql += "class_position >= '#{position_from}'"
elsif (position_to.present? && !position_from.present? && sql.empty?)
sql += "class_position <= '#{position_to}'"
elsif (position_from.present? && position_to.present? && !sql.empty?)
if (position_from == position_to)
sql += " AND class_position = '#{position_from}'"
else
sql += " AND class_position BETWEEN '#{position_from}' AND '#{position_to}'"
end
elsif (position_from.present? && !position_to.present? && !sql.empty?)
sql += " AND class_position >= '#{position_from}'"
elsif (position_to.present? && !position_from.present? && !sql.empty?)
sql += " AND class_position <= '#{position_to}'"
end
sql
end
def self.user_create_from_student student, url
institution = student.institution
uname = student.admission_no.present? ? student.admission_no : student.registration_number
username = uname.present? ? uname : "#{student.first_name}#{student.middle_name}#{student.surname}"
password = "#{username}123"
user = User.find_or_initialize_by_accountable_type_and_accountable_id(student.class.name.to_s, student.id)
user.institution_id = student.institution.id
user.username = username
user.email = student.email if student.email.present?
user.password = password
user.password_confirmation = password
unless user.save
#student.destroy if student.created_at > 1.day.ago # delete student if user creation failed
institution.errors.add(:base, user.errors.full_messages.map { |err| err.to_s })
end
student_role = Role.find_by_name('Student')
user.roles << student_role
user.save
# TODO REMOVE THE FOLLOWING COMMENTED BLOCK OF CODES AFTER IMPLEMENTING DELAYED_JOB
#if student.email.present?
# UserMailer.registration_info(student, username, password, url).deliver()
#end
#
# TODO IF You want to send SMS to student upon admission, uncommen below code
#admission_sms = institution.other_sms_settings.find_by_name('SMS on Admission')
#if(admission_sms.present? && admission_sms.is_active && student.mobile.present?)
# sms_text = admission_sms.sms_text
# sms_text = sms_text.gsub(/<student_username>/, username)
# sms_text = sms_text.gsub(/<student_password>/, password)
#
# mobile_numbers = []
# mobile_numbers << student.mobile
# #sms_text = "You have been successfully admitted to #{institution.name}. Your username is #{username} and password is #{password}"
# sender = admission_sms.sender
# send_sms(mobile_numbers, sms_text, sender)
#
#end
institution
end
def check_assessment_remarks
current_semester_courses.reject { |c| c.assessments.empty? }.each do |course|
assessment_remarks = get_admission_remarks(course)
if assessment_remarks.present?
return true
break
end
end
return false
end
def get_registration_number
registration_num = self.program_registration_students
#check_student = Student.find_by_registration_number reg_num_with_format
valid_reg__number = loop do
reg_num_with_format = "#{institution.code}#{Date.today.year}#{self.program.code}#{(registration_num).to_s.rjust(3, '0')}"
break reg_num_with_format unless self.class.exists?(registration_number: reg_num_with_format)
registration_num += 1
end
return valid_reg__number
end
def program_registration_students
prog = self.program
students = self.registration.students.select { |s| s.program == prog }
last_reg_numb = ''
if (students.count > 1)
length = students.count
(2..length).each do |i|
index = ((-1)*i)
last_reg_numb = students[index].registration_number
break if last_reg_numb.present?
end
return 1 unless last_reg_numb.present?
last_reg_text_token = "#{self.institution.code}#{students[-2].created_at.year}#{self.program.code}"
last_reg_numb.slice! last_reg_text_token
if last_reg_numb[-1] != '0'
numb = ((last_reg_numb.to_i)+1)
return numb
else
last_reg_numb[-1] = '1'
return last_reg_numb.to_i
end
else # if this registration is 1st for this program
return 1
end
end
def attendences_by_batch(batch_id = nil, month_year = nil)
self.student_attendances.where("month_date LIKE '#{month_year}%' AND batch_id = #{batch_id}")
end
def total_attendences_by_batch
if self.batch.present?
student_attendances.where("batch_id = #{self.batch.id}")
else
return []
end
end
def has_assessment?
courses.each do |c|
next if c.assessments.blank?
return true
end
return false
end
def student_assessments
assessments = []
current_semester_courses.each do |c|
assessments << c.assessments if c.assessments.present?
end
return assessments.flatten!
end
def upload_assessment_score(assessments)
assessments.each do |assessment_id, details|
assessment = Assessment.find assessment_id
if assessment
unless details[:score].present?
self.errors.add(:base, "Score cannot be blank for course #{assessment.course.code} assessment #{assessment.name}")
next
end
semester = assessment.assessment_period
student_assessment_result = assessment.assessment_results.find_or_initialize_by_student_id_and_semester_and_academic_session(:student_id => self.id, :semester => semester, :academic_session => institution.academic_session)
student_assessment_result.score = details[:score]
student_assessment_result.remarks = details[:admission_remark]
unless student_assessment_result.save
self.errors.add(:base, "Could not save score for #{assessment.name} : #{student_assessment_result.errors.full_messages.flatten}")
else
if (!institution.is_a?(UBE))
self.cgpa = self.cgpa_calculation
self.save(:validate => false)
else
class_position = self.position_in_class
self.class_position = class_position
self.save(:validate => false)
end
end
else
self.errors.add(:base, "Assessment not found.")
end
end
end
private
def record_batch_history
if self.batch_id_changed?
save_batch_history
end
end
def self.send_sms(mobile_numbers, sms_text, sender)
institution_id = Institution.find_by_name(sender).id
unless mobile_numbers.empty?
begin
sms = SmsSender.new(sms_text, "1", "0", mobile_numbers, sender)
sms.submitMessage(institution_id)
status_message = "SMS was successfully sent"
rescue
status_message = "SMS was not sent. Try again later."
end
else
status_message = "SMS was not sent. No destination number found."
end
status_message
end
def validate_courses_count_and_credit_points
if institution.is_a?(UBE)
if batch.present? && self.current_session_courses.count > batch.max_course_count
errors.add(:base, "You are only allowed to select (#{batch.max_course_count}) courses.")
return false
end
else
if batch.present? && self.batch.max_credit_units.present? && self.current_session_courses.present? &&
(self.current_session_courses.inject(0){|sum, c| sum+= c.credit_units if c.present? && c.credit_units.present?} > self.batch.max_credit_units || self.current_session_courses.count > self.batch.max_course_count)
errors.add(:base, "Credit units is exceeding the max credit unit allowed (#{batch.max_credit_units}).") if self.current_session_courses.inject(0){|sum, c| sum += c.credit_units} > batch.max_credit_units
errors.add(:base, "You are only allowed to select (#{batch.max_course_count}) courses.") if self.current_session_courses.count > batch.max_course_count
return false
end
end
true
end
def self.get_gender(gender_str)
return nil if gender_str.blank?
return "Male" if %w(male m).include? gender_str.downcase
return "Female" if %w(female f).include? gender_str.downcase
end
def self.ensure_registration_program_exists(registration, program)
registration_program = RegistrationProgram.find_or_initialize_by_registration_id_and_program_id(registration.id, program.id)
if registration_program.new_record?
registration_program.save!
end
end
def self.ensure_program_exists(institution_id, name)
program = Program.find_or_initialize_by_institution_id_and_name institution_id, name
program.from_csv = true
if program.new_record?
logger.debug "Got new program #{program.inspect}"
code_from_name = get_code_from_name(name)
code_from_name += "#{Program.count}" if Program.all.map(&:code).include?(code_from_name)
program.code = code_from_name
program.save!
end
program
end
def self.ensure_program_applied_exists(institution_id, row)
name = row["applied_program"].present? ? row["applied_program"] : row["applied_form"]
return nil if name.blank?
ensure_program_exists(institution_id, name)
end
def self.ensure_program_offered_exists(institution_id, row)
name = row["offered_program"].present? ? row["offered_program"] : row["offered_form"]
return nil if name.blank?
ensure_program_exists(institution_id, name)
end
def self.ensure_registration_exists(institution_id, row)
name = row["applied_exam"]
return nil if name.blank?
registration = Registration.find_or_initialize_by_institution_id_and_name institution_id, name
if registration.new_record?
logger.debug "Got new exam #{registration.inspect}"
code_from_name = get_code_from_name(name)
code_from_name += "#{Registration.count}" if Registration.all.map(&:code).include?(code_from_name)
registration.code = code_from_name
registration.is_active = true
registration.from_csv = true
registration.save!
end
registration
end
def self.ensure_skill_exist(institution_id, row)
skill_name = row["skill_name"]
skill_type = row["skill_type"]
return nil if (skill_name.blank? || skill_type.blank?)
skill = Skill.find_by_institution_id_and_name_and_type(institution_id, skill_name, skill_type)
return nil unless skill.present?
skill
end
# If the name of the School is 'College of Health Science & Technology'
# and the student registers for a registration called 'Biomedical Medical Technology''
# we can have an Exam. No.CHST2013REGBMT001
def generate_registration_number
self.status = 'Pending'
if !institution.is_a?(UBE)
#registration_num = self.program_registration_students
self.registration_number = self.get_registration_number
else
self.registration_number = "#{institution.code}#{Date.today.year}#{self.registration.code}#{(self.registration.students.count+1).to_s.rjust(3, '0')}"
end
self.save!
end
def consume_pin
Pin.find_by_number(registration_pin).consume(self) if registration_pin.present?
end
def self.get_code_from_name(name)
(name.split.map { |w| w.chr }).join
end
def self.is_checked(key, checked_fields)
if (key == "student_age_from" || key == "student_age_to")
if (checked_fields['age_student'] == "1")
return true
else
return false
end
end
if (key == "student_admission_date_from" || key == "student_admission_date_to")
if (checked_fields['admission_date_student'] == "1")
return true
else
return false
end
end
if (key == 'student_cgpa_from' || key == 'student_cgpa_to')
if (checked_fields['cgpa_student'] == "1")
return true
else
return false
end
end
if (key == 'student_position_from' || key == 'student_position_to')
if (checked_fields['position_student'] == "1")
return true
else
return false
end
end
if (checked_fields[key.gsub('student_', '')+"_student"] == "1")
return true
else
return false
end
end
def username
user.username if user.present?
end
def role?(role)
if user.present?
return !!user.roles.find_by_name(role.to_s.camelize)
end
false
end
def get_batch_if_required
self.batch.id if self.batch.present?
end
def date_of_birth_validate
if self.date_of_birth.blank?
errors.add(:base, 'Please confirm your Date of Birth')
return false
end
return true
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment