-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathjob.rb
More file actions
463 lines (394 loc) · 14.6 KB
/
job.rb
File metadata and controls
463 lines (394 loc) · 14.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
# == Schema Information
#
# Table name: jobs
#
# id :integer not null, primary key
# user_id :integer
# title :string(255)
# desc :text
# category_id :integer
# num_positions :integer
# created_at :datetime
# updated_at :datetime
# department_id :integer
# activation_code :integer
# delta :boolean default(TRUE), not null
# earliest_start_date :datetime
# latest_start_date :datetime
# end_date :datetime
# compensation :integer default(0)
# status :integer default(0)
# primary_contact_id :integer
# project_type :integer
#
require 'will_paginate/array'
class Job < ActiveRecord::Base
include AttribsHelper
module Compensation # bit flags
None = 0
Pay = 1
Credit = 2
Both = Pay | Credit
All = {
'None' => None,
'Pay' => Pay,
'Credit' => Credit,
'Pay and Credit' => Both
}
end
module Status
Open = 0
Filled = 1
All = {
'Open' => Open,
'Closed' => Filled,
}
end
acts_as_taggable
##################
# ASSOCIATIONS #
##################
belongs_to :user
belongs_to :department
has_many :pictures # unused
has_one :contacter, :class_name => 'User', :foreign_key => 'id', :primary_key => 'primary_contact_id'
has_many :owns
has_many :owners, :through => :owns, :source => :user
has_many :sponsorships, :dependent => :destroy
has_many :faculties, :through => :sponsorships
has_many :curations
has_many :orgs, :through => :curations
has_many :coursereqs, :dependent => :destroy
has_many :courses, :through => :coursereqs
has_many :proglangreqs, :dependent => :destroy
has_many :proglangs, :through => :proglangreqs
has_and_belongs_to_many :categories # TODO deprecate in favor of tags
has_many :watches
has_many :users, :through => :watches # TODO rename to watchers
has_many :applics, :dependent => :destroy
has_many :applicants, :through => :applics, :source => :user
#has_many :applicants, :class_name => 'User', :through => :applics
#################
# VALIDATIONS #
#################
validates_presence_of :title, :department, :project_type, :desc
validates_presence_of :earliest_start_date, :latest_start_date, :end_date
# Validates that end dates are no earlier than right now.
validates_each :end_date do |record, attr, value|
record.errors.add attr, 'cannot be earlier than right now' if
value.present? && (value < Time.now - 1.hour)
end
validates_numericality_of :num_positions, :greater_than_or_equal_to => 0,
:allow_nil => true
validate :earliest_start_date_must_be_before_latest
validate :latest_start_date_must_be_before_end_date
validates_inclusion_of :compensation, :in => Compensation::All.values
##########
# Scopes #
##########
attr_accessor :category_names
attr_accessor :course_names
attr_accessor :proglang_names
# If true, handle_categories, handle_courses, and handle_proglangs don't do anything.
# The purpose of this is so that in activating a job, these data aren't lost.
@skip_handlers = false
attr_accessor :skip_handlers
#############
# METHODS #
#############
def project_string
case project_type
when 1
'Undergraduate Research'
when 2
'Student Group'
when 3
'Design Project'
else # including 4: 'Other'
''
end
end
def get_all_project_strings
return [['Undergraduate Research', 1], ['Student Group', 2], ['Design Project', 3], ['Other', 4]]
end
def open?
status == Job::Status::Open
end
def pay?
(self.compensation & Compensation::Pay) > 0
end
def credit?
(self.compensation & Compensation::Credit) > 0
end
def owner?(user)
self.user == user || owners.include?(user)
end
def open_ended_end_date
end_date.blank?
end
# Returns true if the specified user has admin rights (can view applications,
# edit, etc.) for this job.
def can_admin?(user)
owner?(user) || user.admin?
end
# @return array of actions the user can take, not including curations
def actions(user)
actions = []
if can_admin?(user)
actions.push('edit')
actions.push('delete')
end
unless owner?(user)
applic = applics.find_by_user_id(user) if open?
if self.user != user && !applic
if users.include?(user)
actions.push('unwatch')
else
actions.push('watch')
end
end
if open? || applic
if !applic
actions.push('apply')
elsif applic.applied
actions.push('applied')
else
actions.push('resume')
end
end
end
actions
end
# @return hash{ org => curated }
def curations(user)
curations = {}
(user.admin? ? Org.all : user.orgs).each do |org|
curations[org] = orgs.include?(org)
end
curations
end
def self.smartmatches_for(my, limit=4) # matches for a user
list_separator = ',' # string that separates items in the stored list
query = []
[my.course_list_of_user,
my.category_list_of_user,
my.proglang_list_of_user].each do |list|
query << list.split(list_separator)
end
# magic
smartmatch_ranker = "@weight"
qu = query.join(list_separator).chomp(list_separator)
opts = {:match_mode=>:any, :limit=>limit, :custom_rank=>smartmatch_ranker,
:rank_mode=>:bm25}
puts "\n\n\n" + qu.inspect+ "\n\n\n"
puts "\n\n\n" + opts.inspect + "\n\n\n"
Job.find_jobs(qu, opts)
end
# The main search handler.
# It should be the ONLY interface between search queries and jobs;
# hopefully this will make the choice of search engine transparent
# to our app.
#
# By default, it finds an unlimited number of non-ended jobs.
# You can also restrict by query, department, faculty, paid, credit,
# and set a limit of max number of results.
#
# @param query [Array, String] search terms
# @param options [Hash]
# @option options [Boolean] :included_ended if +false+, don't include jobs with end dates in the past
# @option options [Integer] :department_id ID of department you want to search, or +0+ for all depts
# @option options [Integer] :faculty ID of faculty member you want to search, or +0+ for all
# @option options [Integer] :compensation a constant from {Compensation}. If {Compensation::Both},
# search for {Compensation::Paid paid} OR {Compensation::Credit credit}.
# @option options [Integer] :limit max. number of results, or +0+ for no limit
# @option options [Array] :tags tag strings to match (searches only tags and not body, title, etc.)
# @option options [Array] :order custom sorting conditions, besides @relevance. Conditions concatenated left to right.
# @option options [Boolean] :include_inactive if +true+, include inactive jobs
#
def self.find_jobs(query=nil, options={})
query = Job.sanitize_query(query)
tables = Job.generate_relation_tables
relation = Job.make_relation
relation = Job.filter_by_query(query, relation, tables) if query
relation = Job.filter_by_options(options, relation, tables) if options
relation = relation.where(status: Job::Status::Open).sort_by(&:updated_at).reverse
page = options[:page] || 1
per_page = options[:per_page] || 16
return relation.paginate(:page => page, :per_page => per_page)
end
# @return query for jobs joined with relevant tables
def self.make_relation
Job.all.includes(:faculties).includes(:department).includes(:tags)
.includes(:proglangs).includes(:courses).includes(:categories)
end
# @return all results with at least one field that matches the search query
def self.filter_by_query(query, relation, tables)
relation.where(tables['jobs'][:title].matches(query)
.or(tables['jobs'][:desc].matches(query))
.or(tables['faculties'][:name].matches(query))
.or(tables['departments'][:name].matches(query))
.or(tables['proglangs'][:name].matches(query))
.or(tables['courses'][:name].matches(query))
.or(tables['categories'][:name].matches(query))
)
.references(:proglangs).references(:courses).references(:categories)
end
# @return results filtered by the options
def self.filter_by_options(options, relation, tables)
relation = relation.where(tables['jobs'][:end_date].gt(Time.now).or(tables['jobs'][:end_date].eq(nil))) unless options[:include_ended]
relation = relation.where(tables['departments'][:id].eq(options[:department_id])) if options[:department_id]
relation = relation.where(tables['faculties'][:id].eq(options[:faculty_id])) if options[:faculty_id]
# Search paid, credit
if options[:compensation].present? and options[:compensation].to_i != Compensation::None
compensations = []
compensations << Compensation::Pay if (options[:compensation].to_i & Compensation::Pay) != 0
compensations << Compensation::Credit if (options[:compensation].to_i & Compensation::Credit) != 0
compensations << Compensation::Both unless compensations.empty?
relation = relation.where(tables['jobs'][:compensation].in_any(compensations))
end
if options[:post_status].present?
statuses = [options[:post_status]]
relation = relation.where(tables['jobs'][:status].in_any(statuses))
end
relation = relation.where(tables['tags'][:name].matches(options[:tags])) if options[:tags].present?
relation = relation.limit(options[:limit]) if options[:limit]
order = options[:order] || "jobs.created_at DESC"
relation = relation.order(order)
return relation
end
# Build complex queries with arel tables
def self.generate_relation_tables
{
'jobs' => Job.arel_table,
'faculties' => Faculty.arel_table,
'departments' => Department.arel_table,
'proglangs' => Proglang.arel_table,
'courses' => Course.arel_table,
'categories' => Category.arel_table,
'tags' => ActsAsTaggableOn::Tag.arel_table,
}
end
# Processes user input to send to the database
def self.sanitize_query(query)
throw "Query must be a string" unless query.nil? || query.is_a?(String)
query ||= ""
query = query.gsub(/\\/, '\\\\\\\\').gsub(/%/, '\%').gsub(/_/, '\_')
query = "%" + query + "%"
return query
end
def self.query_url(options)
params = {}
params[:query] = options[:query] if options[:query]
params[:department] = options[:department_id] if options[:department_id] and Department.exists?(options[:department_id])
params[:compensation] = options[:compensation] if options[:compensation] and Job::Compensation::All.key(options[:compensation].to_i)
url_for(:controller => 'jobs', :only_path=>true)+"?#{params.collect { |param, value| param+'='+value }.join('&')}"
end
def self.find_recently_added(n)
Job.find_jobs :extra_conditions => { order: "created_at DESC", limit: n }
end
def self.human_attribute_name(attr, options = {})
if attr == :desc
return "Description"
end
return super
end
def self.close_jobs
jobs = Job.where('latest_start_date < ?', Time.now)
jobs.each do |job|
job.update_attribute(:status, 1)
job.save(validate: false)
end
end
# Returns a string containing the category names taken by this Job
# e.g. "robotics,signal processing"
def category_list_of_job(add_spaces = false)
category_list = ''
self.categories.each do |cat|
category_list << cat.name + ','
category_list << ' ' if add_spaces
end
if add_spaces
return category_list[0..(category_list.length - 3)].downcase
else
return category_list[0..(category_list.length - 2)].downcase
end
end
# Returns a string containing the 'required course' names taken by this Job
# e.g. "CS61A,CS61B"
def course_list_of_job(add_spaces = false)
course_list = ''
self.courses.each do |c|
course_list << c.name + ','
course_list << ' ' if add_spaces
end
if add_spaces
return course_list[0..(course_list.length - 3)].upcase
else
return course_list[0..(course_list.length - 2)].upcase
end
end
# Returns a string containing the 'desired proglang' names taken by this Job
# e.g. "java,scheme,c++"
def proglang_list_of_job(add_spaces = false)
proglang_list = ''
self.proglangs.each do |pl|
proglang_list << pl.name.capitalize + ','
proglang_list << ' ' if add_spaces
end
if add_spaces
return proglang_list[0..(proglang_list.length - 3)]
else
return proglang_list[0..(proglang_list.length - 2)]
end
end
# Ensures all fields are valid
def mend
# Check for deleted/bad faculty
if not self.faculties.empty? and not Faculty.exists?(self.faculties.first.id)
self.faculties = []
end
end
# Returns a list of relevant fields used to generate tags
def field_list
[ self.department.name,
self.category_list_of_job,
self.course_list_of_job,
self.proglang_list_of_job,
('credit' if self.credit?),
('paid' if self.pay?)
].compact.reject(&:blank?)
end
# Reassigns it an activation code.
# Used when creating a job or if, when updating the job, a new
# faculty sponsor is specified.
def resend_email(send_email = false)
self.activation_code = SecureRandom.random_number(10e6.to_i)
# Save, skipping validations, so that we just change the activation code
# and leave the rest alone! (Also so that we don't encounter weird bugs with
# activating jobs whose end dates are in the past, etc.)
self.save(:validate => false)
if send_email
# Send the email for activation.
begin
email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
if !faculties.collect(&:email).select{|email| email === email_regex}.empty?
JobMailer.activate_job_email(self).deliver
end
rescue => e
Rails.logger.error "Failed to send activation mail for job##{self.id}: #{e.inspect}"
raise if Rails.development?
end
end
end
protected
#delete this?
def earliest_start_date_must_be_before_latest
errors[:start_date] << "cannot be later than the latest start date" if
latest_start_date.present? && earliest_start_date.present? && earliest_start_date > latest_start_date
end
def latest_start_date_must_be_before_end_date
errors.add(:apply_by_date, "cannot be later than the end date") if
latest_start_date.present? && !open_ended_end_date &&
latest_start_date > end_date
end
end