Class: Osm::Event

Inherits:
Model
  • Object
show all
Defined in:
lib/osm/event.rb

Defined Under Namespace

Classes: Attendance, BadgeLink, Column

Constant Summary collapse

LIST_ATTRIBUTES =
[:id, :section_id, :name, :start, :finish, :cost, :location, :notes, :archived, :public_notepad, :confirm_by_date, :allow_changes, :reminders, :attendance_limit, :attendance_limit_includes_leaders, :attendance_reminder, :allow_booking]
EXTRA_ATTRIBUTES =
[:notepad, :columns, :badges]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Model

#<, #<=, #>, #>=, #between?, #changed_attributes, configure, #reset_changed_attributes, #to_i

Constructor Details

#initializeObject

Initialize a new Event

Parameters:

  • attributes (Hash)

    The hash of attributes (see attributes for descriptions, use Symbol of attribute name as the key)


# File 'lib/osm/event.rb', line 93

Instance Attribute Details

#allow_bookingBoolean

Returns whether booking is allowed through My.SCOUT.

Returns:

  • (Boolean)

    whether booking is allowed through My.SCOUT


51
# File 'lib/osm/event.rb', line 51

attribute :id, :type => Integer

#allow_changesBoolean

Returns whether parent's can change their child's details.

Returns:

  • (Boolean)

    whether parent's can change their child's details


51
# File 'lib/osm/event.rb', line 51

attribute :id, :type => Integer

#archivedBoolean

Returns if the event has been archived.

Returns:

  • (Boolean)

    if the event has been archived


51
# File 'lib/osm/event.rb', line 51

attribute :id, :type => Integer

#attendance_limitFixnum

Returns the maximum number of people who can attend the event (0 = no limit).

Returns:

  • (Fixnum)

    the maximum number of people who can attend the event (0 = no limit)


51
# File 'lib/osm/event.rb', line 51

attribute :id, :type => Integer

#attendance_reminderFixnum

Returns how many days before the event to send a reminder to those attending (0 (off), 1, 3, 7, 14, 21, 28).

Returns:

  • (Fixnum)

    how many days before the event to send a reminder to those attending (0 (off), 1, 3, 7, 14, 21, 28)


51
# File 'lib/osm/event.rb', line 51

attribute :id, :type => Integer

#badgesArray<Osm::Event::BadgeLink>

Returns the badge links for the event.

Returns:


51
# File 'lib/osm/event.rb', line 51

attribute :id, :type => Integer

#columnsArray<Osm::Event::Column>

Returns the custom columns for the event.

Returns:


51
# File 'lib/osm/event.rb', line 51

attribute :id, :type => Integer

#confirm_by_dateDate

Returns the date parents can no longer add/change their child's details.

Returns:

  • (Date)

    the date parents can no longer add/change their child's details


51
# File 'lib/osm/event.rb', line 51

attribute :id, :type => Integer

#costString

Returns the cost of the event (formatted to d+.d2) or “TBC”.

Returns:

  • (String)

    the cost of the event (formatted to d+.d2) or “TBC”


51
# File 'lib/osm/event.rb', line 51

attribute :id, :type => Integer

#finishDateTime

Returns when the event ends.

Returns:

  • (DateTime)

    when the event ends


51
# File 'lib/osm/event.rb', line 51

attribute :id, :type => Integer

#idFixnum

Returns the id for the event.

Returns:

  • (Fixnum)

    the id for the event


51
# File 'lib/osm/event.rb', line 51

attribute :id, :type => Integer

#locationString

Returns where the event is.

Returns:

  • (String)

    where the event is


51
# File 'lib/osm/event.rb', line 51

attribute :id, :type => Integer

#nameString

Returns the name of the event.

Returns:

  • (String)

    the name of the event


51
# File 'lib/osm/event.rb', line 51

attribute :id, :type => Integer

#notepadString

Returns notepad for the event.

Returns:

  • (String)

    notepad for the event


51
# File 'lib/osm/event.rb', line 51

attribute :id, :type => Integer

#notesString

Returns notes about the event.

Returns:

  • (String)

    notes about the event


51
# File 'lib/osm/event.rb', line 51

attribute :id, :type => Integer

#public_notepadString

Returns public notepad (shown in My.SCOUT) for the event.

Returns:

  • (String)

    public notepad (shown in My.SCOUT) for the event


51
# File 'lib/osm/event.rb', line 51

attribute :id, :type => Integer

#remindersBoolean

Returns whether email reminders are sent for the event.

Returns:

  • (Boolean)

    whether email reminders are sent for the event


51
# File 'lib/osm/event.rb', line 51

attribute :id, :type => Integer

#section_idFixnum

Returns the id for the section.

Returns:

  • (Fixnum)

    the id for the section


51
# File 'lib/osm/event.rb', line 51

attribute :id, :type => Integer

#startDateTime

Returns when the event starts.

Returns:

  • (DateTime)

    when the event starts


51
# File 'lib/osm/event.rb', line 51

attribute :id, :type => Integer

Class Method Details

.create(api, parameters) ⇒ Osm::Event?

Create an event in OSM If something goes wrong adding badges to OSM then the event returned will have been read from OSM

Parameters:

  • api (Osm::Api)

    The api to use to make the request

Returns:

  • (Osm::Event, nil)

    the created event, nil if failed

Raises:


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
# File 'lib/osm/event.rb', line 209

def self.create(api, parameters)
  require_ability_to(api, :write, :events, parameters[:section_id])
  event = new(parameters)
  raise Osm::ObjectIsInvalid, 'event is invalid' unless event.valid?

  data = api.perform_query("events.php?action=addEvent&sectionid=#{event.section_id}", {
    'name' => event.name,
    'location' => event.location,
    'startdate' => event.start? ? event.start.strftime(Osm::OSM_DATE_FORMAT) : '',
    'enddate' => event.finish? ? event.finish.strftime(Osm::OSM_DATE_FORMAT) : '',
    'cost' => event.cost_tbc? ? '-1' : event.cost,
    'notes' => event.notes,
    'starttime' => event.start? ? event.start.strftime(Osm::OSM_TIME_FORMAT) : '',
    'endtime' => event.finish? ? event.finish.strftime(Osm::OSM_TIME_FORMAT) : '',
    'confdate' => event.confirm_by_date? ? event.confirm_by_date.strftime(Osm::OSM_DATE_FORMAT) : '',
    'allowChanges' => event.allow_changes ? 'true' : 'false',
    'disablereminders' => !event.reminders ? 'true' : 'false',
    'attendancelimit' => event.attendance_limit,
    'attendancereminder' => event.attendance_reminder,
    'limitincludesleaders' => event.attendance_limit_includes_leaders ? 'true' : 'false',
    'allowbooking' => event.allow_booking ? 'true' : 'false',
  })

  if (data.is_a?(Hash) && data.has_key?('id'))
    event.id = data['id'].to_i

    # The cached events for the section will be out of date - remove them
    cache_delete(api, ['events', event.section_id])

    # Add badge links to OSM
    badges_created = true
    event.badges.each do |badge|
      badges_created &= event.add_badge_link(api, badge)
    end

    if badges_created
      cache_write(api, ['event', event.id], event)
      return event
    else
      # Someting went wrong adding badges so return what OSM has
      return get(api, event.section_id, event.id)
    end
  else
    return nil
  end
end

.get(api, section, event_id, options = {}) ⇒ Osm::Event?

Get an event

Parameters:

  • api (Osm::Api)

    The api to use to make the request

  • section (Osm::Section, Fixnum, #to_i)

    The section (or its ID) to get the events for

  • event_id (Fixnum, #to_i)

    The id of the event to get

Returns:

  • (Osm::Event, nil)

    the event (or nil if it couldn't be found


189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/osm/event.rb', line 189

def self.get(api, section, event_id, options={})
  require_ability_to(api, :read, :events, section, options)
  section_id = section.to_i
  event_id = event_id.to_i
  cache_key = ['event', event_id]

  if !options[:no_cache] && cache_exist?(api, cache_key)
    return cache_read(api, cache_key)
  end

  event_data = api.perform_query("events.php?action=getEvent&sectionid=#{section_id}&eventid=#{event_id}")
  return self.new_event_from_data(event_data)
end

.get_for_section(api, section, options = {}) ⇒ Array<Osm::Event>

Get events for a section

Parameters:

  • api (Osm::Api)

    The api to use to make the request

  • section (Osm::Section, Fixnum, #to_i)

    The section (or its ID) to get the events for

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :include_archived (Boolean) — default: optional

    if true then archived events will also be returned

Returns:


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
# File 'lib/osm/event.rb', line 104

def self.get_for_section(api, section, options={})
  require_ability_to(api, :read, :events, section, options)
  section_id = section.to_i
  cache_key = ['events', section_id]
  events = nil

  if !options[:no_cache] && cache_exist?(api, cache_key)
    ids = cache_read(api, cache_key)
    events = get_from_ids(api, ids, 'event', section, options, :get_for_section)
  end

  if events.nil?
    data = api.perform_query("events.php?action=getEvents&sectionid=#{section_id}&showArchived=true")
    events = Array.new
    ids = Array.new
    unless data['items'].nil?
      data['items'].map { |i| i['eventid'].to_i }.each do |event_id|
        event_data = api.perform_query("events.php?action=getEvent&sectionid=#{section_id}&eventid=#{event_id}")
        event = self.new_event_from_data(event_data)
        events.push event
        ids.push event.id
        cache_write(api, ['event', event.id], event)
      end
    end
    cache_write(api, cache_key, ids)
  end

  return events if options[:include_archived]
  return events.reject do |event|
    event.archived?
  end
end

.get_list(api, section, options = {}) ⇒ Array<Hash>

Get event list for a section (not all details for each event)

Parameters:

  • api (Osm::Api)

    The api to use to make the request

  • section (Osm::Section, Fixnum, #to_i)

    The section (or its ID) to get the events for

Returns:

  • (Array<Hash>)

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
# File 'lib/osm/event.rb', line 142

def self.get_list(api, section, options={})
  require_ability_to(api, :read, :events, section, options)
  section_id = section.to_i
  cache_key = ['events_list', section_id]
  events_cache_key = ['events', section_id]
  events = nil

  unless options[:no_cache]

    # Try getting from cache
    if cache_exist?(api, cache_key)
      return cache_read(api, cache_key)
    end
  
    # Try generating from cached events
    if cache_exist?(api, events_cache_key)
      ids = cache_read(api, events_cache_key)
      events = get_from_ids(api, ids, 'event', section, options, :get_for_section).map do |e|
        e.attributes.symbolize_keys.select do |k,v|
          LIST_ATTRIBUTES.include?(k)
        end
      end
    end

  end

  # Fetch from OSM
  if events.nil?
    data = api.perform_query("events.php?action=getEvents&sectionid=#{section_id}&showArchived=true")
    events = Array.new
    unless data['items'].nil?
      data['items'].map do |event_data|
        events.push(attributes_from_data(event_data))
      end
    end
  end

  cache_write(api, cache_key, events)
  return events
end

Instance Method Details

#<=>(another) ⇒ Object

Compare Event based on start, name then id


505
506
507
508
509
510
511
# File 'lib/osm/event.rb', line 505

def <=>(another)
  return 0 if self.id == another.try(:id)
  result = self.start <=> another.try(:start)
  result = self.name <=> another.try(:name) if result == 0
  result = self.id <=> another.try(:id) if result == 0
  return result
end

Add a badge link to the event in OSM

Parameters:

  • api (Osm::Api)

    The api to use to make the request

  • link (Osm::Event::BadgeLink)

    The badge link to add, if column_id is nil then a new column is created with requirement_label as the name

Returns:

  • (Boolean)

    whether the update succedded

Raises:


426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
# File 'lib/osm/event.rb', line 426

def add_badge_link(api, link)
  raise Osm::ObjectIsInvalid, 'link is invalid' unless link.valid?

  data = api.perform_query("ext/badges/records/index.php?action=linkBadgeToItem&sectionid=#{section_id}", {
    'section' => link.badge_section,
    'sectionid' => section_id,
    'type' => 'event',
    'id' => id,
    'badge_id' => link.badge_id,
    'badge_version' => link.badge_version,
    'column_id' => link.requirement_id.to_i.eql?(0) ? -2 : link.requirement_id,
    'column_data' => link.data,
    'new_column_name' => link.requirement_id.to_i.eql?(0) ? link.requirement_label : '',
  })
  return (data.is_a?(Hash) && data['status'])
end

#add_column(api, name, label = '', required = false) ⇒ Boolean

Add a column to the event in OSM

Parameters:

  • api (Osm::Api)

    The api to use to make the request

  • label (String) (defaults to: '')

    The label for the field in OSM

  • name (String)

    The label for the field in My.SCOUT (if this is blank then parents can't edit it)

  • required (Boolean) (defaults to: false)

    Whether the parent is required to enter something

Returns:

  • (Boolean)

    whether the update succedded

Raises:


450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
# File 'lib/osm/event.rb', line 450

def add_column(api, name, label='', required=false)
  require_ability_to(api, :write, :events, section_id)
  raise Osm::ArgumentIsInvalid, 'name is invalid' if name.blank?

  data = api.perform_query("events.php?action=addColumn&sectionid=#{section_id}&eventid=#{id}", {
    'columnName' => name,
    'parentLabel' => label,
    'parentRequire' => (required ? 1 : 0),
  })

  # The cached events for the section will be out of date - remove them
  cache_delete(api, ['events', section_id])
  cache_delete(api, ['event', id])
  cache_delete(api, ['event_attendance', id])

  self.columns = self.class.new_event_from_data(data).columns

  return data.is_a?(Hash) && (data['eventid'].to_i == id)
end

#cost_free?Boolean

Whether the cost is zero

Returns:

  • (Boolean)

    whether the cost is zero


500
501
502
# File 'lib/osm/event.rb', line 500

def cost_free?
  cost.eql?('0.00')
end

#cost_tbc?Boolean

Whether the cost is to be confirmed

Returns:

  • (Boolean)

    whether the cost is TBC


494
495
496
# File 'lib/osm/event.rb', line 494

def cost_tbc?
  cost.eql?('TBC')
end

#delete(api) ⇒ Boolean

Delete event from OSM

Parameters:

  • api (Osm::Api)

    The api to use to make the request

Returns:

  • (Boolean)

    whether the delete succedded


356
357
358
359
360
361
362
363
364
365
366
# File 'lib/osm/event.rb', line 356

def delete(api)
  require_ability_to(api, :write, :events, section_id)

  data = api.perform_query("events.php?action=deleteEvent&sectionid=#{section_id}&eventid=#{id}")

  if data.is_a?(Hash) && data['ok']
    cache_delete(api, ['event', id])
    return true
  end
  return false
end

#get_attendance(api, term = nil, options = {}) ⇒ Array<Osm::Event::Attendance>

Get event attendance

Parameters:

  • api (Osm::Api)

    The api to use to make the request

  • term (Osm::Term, Fixnum, #to_i, nil) (defaults to: nil)

    The term (or its ID) to get the members for, passing nil causes the current term to be used

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :include_archived (Boolean) — default: optional

    if true then archived activities will also be returned

Returns:


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
# File 'lib/osm/event.rb', line 375

def get_attendance(api, term=nil, options={})
  require_ability_to(api, :read, :events, section_id, options)
  term_id = term.nil? ? Osm::Term.get_current_term_for_section(api, section_id).id : term.to_i
  cache_key = ['event_attendance', id, term_id]

  if !options[:no_cache] && cache_exist?(api, cache_key)
    return cache_read(api, cache_key)
  end

  data = api.perform_query("events.php?action=getEventAttendance&eventid=#{id}&sectionid=#{section_id}&termid=#{term_id}")
  data = data['items'] || []

  payment_values = {
    'Manual' => :manual,
    'Automatic' => :automatic,
  }
  attending_values = {
    'Yes' => :yes,
    'No' => :no,
    'Invited' => :invited,
    'Show in My.SCOUT' => :shown,
    'Reserved' => :reserved,
  }

  attendance = []
  data.each_with_index do |item, index|
    attendance.push Osm::Event::Attendance.new(
      :event => self,
      :member_id => Osm::to_i_or_nil(item['scoutid']),
      :grouping_id => Osm::to_i_or_nil(item['patrolid'].eql?('') ? nil : item['patrolid']),
      :first_name => item['firstname'],
      :last_name => item['lastname'],
      :date_of_birth => item['dob'].nil? ? nil : Osm::parse_date(item['dob'], :ignore_epoch => true),
      :attending => attending_values[item['attending']],
      :payment_control => payment_values[item['payment']],
      :fields => item.select { |key, value| key.to_s.match(/\Af_\d+\Z/) }
                     .inject({}){ |h,(k,v)| h[k[2..-1].to_i] = v; h },
      :payments => item.select { |key, value| key.to_s.match(/\Ap\d+\Z/) }
                       .inject({}){ |h,(k,v)| h[k[1..-1].to_i] = v; h },
      :row => index,
    )
  end

  cache_write(api, cache_key, attendance)
  return attendance
end

#limited_attendance?Boolean

Whether thete is a limit on attendance for this event

Returns:

  • (Boolean)

    whether thete is a limit on attendance for this event


472
473
474
# File 'lib/osm/event.rb', line 472

def limited_attendance?
  (attendance_limit != 0)
end

#spaces(api) ⇒ Fixnum?

Get the number of spaces left for the event

Parameters:

  • api (Osm::Api)

    The api to use to make the request

Returns:

  • (Fixnum, nil)

    the number of spaces left (nil if there is no attendance limit)


487
488
489
490
# File 'lib/osm/event.rb', line 487

def spaces(api)
  return nil unless limited_attendance?
  return attendance_limit - attendees(api)
end

#spaces?(api) ⇒ Boolean

Whether there are spaces left for the event

Parameters:

  • api (Osm::Api)

    The api to use to make the request

Returns:

  • (Boolean)

    whether there are spaces left for the event


479
480
481
482
# File 'lib/osm/event.rb', line 479

def spaces?(api)
  return true unless limited_attendance?
  return attendance_limit > attendees(api)
end

#update(api) ⇒ Boolean

Update event in OSM

Parameters:

  • api (Osm::Api)

    The api to use to make the request

Returns:

  • (Boolean)

    whether the update succedded (will return true if no updates needed to be made)


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
# File 'lib/osm/event.rb', line 259

def update(api)
  require_ability_to(api, :write, :events, section_id)
   updated = true

  # Update main attributes
  update_main_attributes = false
  %w{ id name location start finish cost cost_tbc notes confirm_by_date allow_changes reminders attendance_limit attendance_limit_includes_leaders allow_booking }.each do |a|
    if changed_attributes.include?(a)
      update_main_attributes = true
      break # no use checking the others
    end
  end
  if update_main_attributes
    data = api.perform_query("events.php?action=addEvent&sectionid=#{section_id}", {
      'eventid' => id,
      'name' => name,
      'location' => location,
      'startdate' => start? ? start.strftime(Osm::OSM_DATE_FORMAT) : '',
      'enddate' => finish? ? finish.strftime(Osm::OSM_DATE_FORMAT) : '',
      'cost' => cost_tbc? ? '-1' : cost,
      'notes' => notes,
      'starttime' => start? ? start.strftime(Osm::OSM_TIME_FORMAT) : '',
      'endtime' => finish? ? finish.strftime(Osm::OSM_TIME_FORMAT) : '',
      'confdate' => confirm_by_date? ? confirm_by_date.strftime(Osm::OSM_DATE_FORMAT) : '',
      'allowChanges' => allow_changes ? 'true' : 'false',
      'disablereminders' => !reminders ? 'true' : 'false',
      'attendancelimit' => attendance_limit,
      'attendancereminder' => attendance_reminder,
      'limitincludesleaders' => attendance_limit_includes_leaders ? 'true' : 'false',
      'allowbooking' => allow_booking ? 'true' : 'false',
    })
    updated &= data.is_a?(Hash) && (data['id'].to_i == id)
  end

  # Private notepad
  if changed_attributes.include?('notepad')
    data = api.perform_query("events.php?action=saveNotepad&sectionid=#{section_id}", {
      'eventid' => id,
      'notepad' => notepad,
    })
    updated &= data.is_a?(Hash)
  end

  # MySCOUT notepad
  if changed_attributes.include?('public_notepad')
    data = api.perform_query("events.php?action=saveNotepad&sectionid=#{section_id}", {
      'eventid' => id,
      'pnnotepad' => public_notepad,
    })
    updated &= data.is_a?(Hash)
  end

  # Badges
  if changed_attributes.include?('badges')
    original_badges = @original_attributes['badges'] || []

    # Deleted badges
    badges_to_delete = []
    original_badges.each do |badge|
      unless badges.include?(badge)
        badges_to_delete.push badge
      end
    end
    badges_to_delete.each do |badge|
      data = api.perform_query("ext/badges/records/index.php?action=deleteBadgeLink&sectionid=#{section_id}", {
        'section' => badge.badge_section,
        'sectionid' => section_id,
        'type' => 'event',
        'id' => id,
        'badge_id' => badge.badge_id,
        'badge_version' => badge.badge_version,
        'column_id' => badge.requirement_id,
      })
      updated &= data.is_a?(Hash) && data['status']
    end

    # Added badges
    badges.each do |badge|
      unless original_badges.include?(badge)
        updated &= add_badge_link(api, badge)
      end
    end
  end # includes badges

  if updated
    reset_changed_attributes
    # The cached event will be out of date - remove it
    cache_delete(api, ['event', id])
    return true
  else
    return false
  end
end