Skip to content

Instantly share code, notes, and snippets.

@klippx
Created July 2, 2015 06:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save klippx/2ba4e1d0300968618d19 to your computer and use it in GitHub Desktop.
Save klippx/2ba4e1d0300968618d19 to your computer and use it in GitHub Desktop.
Final result: Pouch Order
# A pouch order is ordered to a ward for a patient from a prescriber. These
# will be produces as pouches through the HD-Medi system.
class PouchOrder < ActiveRecord::Base
# Workflow is handled in library module
include PouchOrder::WorkflowManager
include DatetimeChange
belongs_to :ward
belongs_to :patient
belongs_to :file, class_name: 'MachineFile', foreign_key: 'machine_file_id'
belongs_to :transport_label
has_one :replaced, class_name: 'PouchOrder', foreign_key: 'replacement_id'
belongs_to :replacement, class_name: 'PouchOrder', foreign_key: 'replacement_id'
has_many :lines, class_name: 'PouchOrderLine', foreign_key: 'pouch_order_id', inverse_of: :order, dependent: :destroy
has_many :lines_with_half_tablet_substitutions, -> { uniq }, through: :lines, source: :substitution_for
has_many :interactions, dependent: :destroy
has_many :overdoses, dependent: :destroy
validates :ward, :patient, presence: true
validates :number, uniqueness: true
before_save :set_default_delivery_at, on: :create
before_save :calculate_and_set_lock_at, on: :create
scope :sent_to_machine, -> { where(status: 'sent_to_machine') }
delegate :ordering_deadlines, to: :ward
delegate :loading_dock, to: :ward
audited only: [:status], on: [:update], allow_mass_assignment: true
def number
super || "apoex_#{self.id}".upcase
end
def suitable_transport_label
TransportLabel.with_open_state.where(ward: ward).order(:created_at).last
end
def has_substitutions?
lines.any? { |line| line.substitutions.present? }
end
def has_licensed_item?
lines.any? { |line| line.item.license_required? }
end
def has_interactions?
interactions.present?
end
def has_dangerous_interactions?
interactions.any? { |i| i.dangerous? }
end
def has_unknown_interactions?
interactions.any? { |i| i.unknown? }
end
def has_overdoses?
overdoses.any?
end
def can_be_auto_approved?
!(has_licensed_item? || has_interactions? || has_overdoses? || has_substitutions?)
end
def sort(label)
label.orders << self
end
def set_default_delivery_at
self.delivery_at ||= loading_dock.latest_delivery_time
end
def calculate_and_set_lock_at
delivery_time = delivery_at.dup
lock_time = loading_dock.ordering_deadlines.for_delivery_time(delivery_time)
self.lock_at = datetime_change(datetime: delivery_time, time: lock_time)
end
def issued_in_time?
lock_at >= issued_at
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment