require 'restclient' module Medivo class Appointment LABCORP_FORMAT = "%m/%d/%Y|%H:%M %P" unless defined? LABCORP_FORMAT MDY_FORMAT = "%m/%d/%Y" unless defined? MDY_FORMAT class << self ## # Find a labcorp appointment # # @param lab_code lab code # @param date date to seek # @param am_pm optional time of day value ( 'AM' or 'PM' ) def find(lab_code, date, am_pm='') if real_data? data = resource.get :params=>{:labcorp_id=>lab_code, :appointment_date=>date} data = JSON.parse(data) else data = build_fake_data(date) end filter_data(data, am_pm) end ## # Make the labcorp appointment # # @param lab_code lab code # @param time_id time_id formatted to string in LABCORP_FORMAT # @param user user info must include date_of_birth, first_name, last_name, # email_address, phone_number def make(lab_code, time, user) if real_data? data = resource.post :params=>{:labcorp_id=>lab_code, :time=>time, :user=>user} JSON.parse(data) else { confirmation: nil } end end def resource @resource ||= begin @config = ResourceConfig.find 'appointment_resource.yml' RestClient::Resource.new @config.href, :timeout => (@config.timeout || 12) rescue => e Rails.logger.error e.inspect # blow up later, so the server can start end end ## using real data? # the flag is set in the config/appointment_resource.yml def real_data? resource # to init the resource and config file true unless !Rails.env.test? and @config.real_data == false end def filter_data(hash, am_pm) now = Time.now hash['times'].reject! do |time| (!time.match(/#{am_pm}/) or Time.strptime(time, LABCORP_FORMAT) < now) end hash end def build_fake_data(date) date = date.is_a?(String) ? Date.strptime(date, MDY_FORMAT) : date {'times'=> [ build_date(date, "08:30 AM"), build_date(date, "10:30 AM"), build_date((date + 1), "03:30 PM"), build_date((date+1), "01:30 PM"), build_date((date + 2), "10:30 AM"), build_date((date+1), "03:00 PM"), ]} end def build_date(date, time) "#{date.strftime(MDY_FORMAT)}|#{time}" end end end end