app/controllers/appointments_controller.rb
# Issues the receipt, updating also all associated Appointment instances.
#
# Since version 2.5 this action works for creating both single and multi-appointment receipts.
#
# The transaction will fall back for multi-appointment receipts if *any* of the selected appointments
# has already an issued receipt associated with it.
#
# ==Params:
# - +id+ => Appointment ID for which the Receipt must be issued.
# - +ids+ => either an Array of Appointment IDs or a String of IDs concatenated by ',', for which the Receipt must be issued. Used only when params[:id] is not specified
# - +date_receipt+ : chosen Date for the receipt; can be +nil+ to use the current date.
# - +patient_id+   : Patient id chosen for the receipt. When missing Appointment.patient_id will be used, assuming either one of :id or :ids parameters are specified and valid.
#
Issues the receipt, updating also all associated Appointment instances.
Since version 2.5 this action works for creating both single and multi-appointment receipts.

The transaction will fall back for multi-appointment receipts if *any* of the selected appointments
has already an issued receipt associated with it.

+id+ => Appointment ID for which the Receipt must be issued.
+ids+ => either an Array of Appointment IDs or a String of IDs concatenated by ',', for which the Receipt must be issued. Used only when params[:id] is not specified
+date_receipt+ : chosen Date for the receipt; can be +nil+ to use the current date.
+patient_id+   : Patient id chosen for the receipt. When missing Appointment.patient_id will be used, assuming either one of :id or :ids parameters are specified and valid.
Issues the receipt updating also all associated Appointment instances . Since version 2 . 5 this action works for creating both single and multi - appointment receipts . The transaction will fall back for multi - appointment receipts if * any * of the selected appointments has already an issued receipt associated with it . + id + = > Appointment ID for which the Receipt must be issued . + ids + = > either an Array of Appointment IDs or a String of IDs concatenated by ' ' for which the Receipt must be issued . Used only when params [ : id ] is not specified + date_receipt + : chosen Date for the receipt ; can be + nil + to use the current date . + patient_id + : Patient id chosen for the receipt . When missing Appointment . patient_id will be used assuming either one of : id or : ids parameters are specified and valid .
def issue_receipt
    return if request.xhr?                          
    logger.debug "\r\n!! ----- AppointmentsController::issue_receipt() -----"
    logger.debug "issue_receipt: params #{params.inspect}"
    id_list = []
    if params[:id].to_i > 0                         
      id_list << params[:id]
    elsif params[:data]                             
      id_list = ActiveSupport::JSON.decode( params[:data] )
    elsif params[:ids].instance_of?( Array )        
      id_list = params[:ids]
    elsif params[:ids].instance_of?( String )       
      id_list = params[:ids].split(',').compact.uniq.sort
    end
    is_ok = (id_list.size > 0)                      
    msg = '-- Unexpected error condition! --'       
    appointments = nil
    begin
      appointments = Appointment.where( :id => id_list )
    rescue
      raise ArgumentError, "AppointmentsController::issue_receipt(): no valid ID(s) found inside data parameter!", caller
    end
    logger.debug "AppointmentsController::issue_receipt(): id list: #{id_list.inspect}"
    if is_ok && (appointments.size > 0)             
      params_hash = {
        :patient_id => appointments[0].patient_id,
        :date_receipt => appointments[0].date_receipt,
        :receipt_description => appointments[0].receipt_description
      }
      receipt = Receipt.new( params_hash )
      receipt.additional_notes = ""
      receipt.price = 0
      appointments_list = []
      payed_appointments = []
      all_is_payed = true
      appointments.each { |appointment|
        receipt.additional_notes += appointment.additional_notes + "\r\n" if appointment.additional_notes
        receipt.price += appointment.price
        all_is_payed = all_is_payed && appointment.is_payed
        payed_appointments << appointment.get_date_schedule if appointment.is_payed
        appointments_list << appointment.get_date_schedule
      }
      receipt.is_payed = all_is_payed
      receipt.notes = "#{I18n.t(:appointments_payed, {:scope=>[:receipt]})}: #{payed_appointments.join(", ")}" if payed_appointments.size > 0
      receipt.additional_notes = receipt.additional_notes +
                                 "\r\n#{I18n.t(:invoiced_appointments, {:scope=>[:receipt]})}: #{appointments_list.join(", ")}" if appointments_list.size > 1
      receipt.preset_default_values()
      logger.debug "AppointmentsController::issue_receipt(): receipt: #{receipt.inspect}"
      begin
        ActiveRecord::Base.transaction do           
          if receipt.save                           
            appointments.each do |appointment|      
              if !appointment.is_receipt_issued?    
                appointment.receipt_id = receipt.id 
                unless appointment.save
                  log_error("in issue_receipt() during appointment update - APPOINTMENT: " << appointment.inspect)
                  msg = I18n.t(:something_went_wrong)
                  log_info('Rolling back transaction...')
                  is_ok = false
                  raise ActiveRecord::Rollback
                end
              else
                log_error("issue_receipt(): Receipt already issued! - APPOINTMENT: #{appointment.inspect}\r\nSome of the selected IDs had already an issued Receipt and this should (normally) never occur when the standard selection view is used.")
                msg = I18n.t(:something_went_wrong)
                log_info('Rolling back transaction...')
                is_ok = false
                raise ActiveRecord::Rollback
              end
            end                                     
          else                                      
            log_error( "in issue_receipt() during receipt save - RECEIPT: " << receipt.inspect )
            msg = I18n.t(:something_went_wrong)
            log_info('Rolling back transaction...')
            is_ok = false
            raise ActiveRecord::Rollback
          end
        end
      rescue                                        
        is_ok = false
        log_error('executing transaction rollback...')
        msg ||= $!.to_s
        msg = "#{msg} #{I18n.t(:transaction_cancelled)}"
      end
      msg = I18n.t(:new_receipt_issued, {:scope=>[:receipt]}) + " (#{receipt.get_receipt_header()})" if is_ok
    else                                            
      if ! is_ok                                    
        msg = I18n.t(:no_selection_receipt_not_issued, {:scope=>[:receipt]})
      else                                          
        log_error( "issue_receipt(): An error as occurred while retrieving some of the selected appointment data:\r\nEmpty appointment instance list - PARAMS: " << params.inspect )
        msg = I18n.t(:something_went_wrong)
      end
    end
    flash[:notice] = msg
    redirect_to( (appointments.size == 0) || (! is_ok) ? week_plan_path() : receipts_path() )
  end
def issue_receipt return if request . xhr? logger . debug "\r\n!! ----- AppointmentsController::issue_receipt() -----" logger . debug "issue_receipt: params #{params.inspect}" id_list = [ ] if params [ :id ] . to_i > 0 id_list << params [ :id ] elsif params [ :data ] id_list = ActiveSupport :: JSON . decode ( params [ :data ] ) elsif params [ :ids ] . instance_of? ( Array ) id_list = params [ :ids ] elsif params [ :ids ] . instance_of? ( String ) id_list = params [ :ids ] . split ( ',' ) . compact . uniq . sort end is_ok = ( id_list . size > 0 ) msg = '-- Unexpected error condition! --' appointments = nil begin appointments = Appointment . where ( :id => id_list ) rescue raise ArgumentError , "AppointmentsController::issue_receipt(): no valid ID(s) found inside data parameter!" , caller end logger . debug "AppointmentsController::issue_receipt(): id list: #{id_list.inspect}" if is_ok && ( appointments . size > 0 ) params_hash = { :patient_id => appointments [ 0 ] . patient_id , :date_receipt => appointments [ 0 ] . date_receipt , :receipt_description => appointments [ 0 ] . receipt_description } receipt = Receipt . new ( params_hash ) receipt . additional_notes = "" receipt . price = 0 appointments_list = [ ] payed_appointments = [ ] all_is_payed = true appointments . each { | appointment | receipt . additional_notes += appointment . additional_notes + "\r\n" if appointment . additional_notes receipt . price += appointment . price all_is_payed = all_is_payed && appointment . is_payed payed_appointments << appointment . get_date_schedule if appointment . is_payed appointments_list << appointment . get_date_schedule } receipt . is_payed = all_is_payed receipt . notes = "#{I18n.t(:appointments_payed, {:scope=>[:receipt]})}: #{payed_appointments.join(", ")}" if payed_appointments . size > 0 receipt . additional_notes = receipt . additional_notes + "\r\n#{I18n.t(:invoiced_appointments, {:scope=>[:receipt]})}: #{appointments_list.join(", ")}" if appointments_list . size > 1 receipt . preset_default_values ( ) logger . debug "AppointmentsController::issue_receipt(): receipt: #{receipt.inspect}" begin ActiveRecord :: Base . transaction do if receipt . save appointments . each do | appointment | if ! appointment . is_receipt_issued? appointment . receipt_id = receipt . id unless appointment . save log_error ( "in issue_receipt() during appointment update - APPOINTMENT: " << appointment . inspect ) msg = I18n . t ( :something_went_wrong ) log_info ( 'Rolling back transaction...' ) is_ok = false raise ActiveRecord :: Rollback end else log_error ( "issue_receipt(): Receipt already issued! - APPOINTMENT: #{appointment.inspect}\r\nSome of the selected IDs had already an issued Receipt and this should (normally) never occur when the standard selection view is used." ) msg = I18n . t ( :something_went_wrong ) log_info ( 'Rolling back transaction...' ) is_ok = false raise ActiveRecord :: Rollback end end else log_error ( "in issue_receipt() during receipt save - RECEIPT: " << receipt . inspect ) msg = I18n . t ( :something_went_wrong ) log_info ( 'Rolling back transaction...' ) is_ok = false raise ActiveRecord :: Rollback end end rescue is_ok = false log_error ( 'executing transaction rollback...' ) msg ||= $! . to_s msg = "#{msg} #{I18n.t(:transaction_cancelled)}" end msg = I18n . t ( :new_receipt_issued , { :scope => [ :receipt ] } ) + " (#{receipt.get_receipt_header()})" if is_ok else if ! is_ok msg = I18n . t ( :no_selection_receipt_not_issued , { :scope => [ :receipt ] } ) else log_error ( "issue_receipt(): An error as occurred while retrieving some of the selected appointment data:\r\nEmpty appointment instance list - PARAMS: " << params . inspect ) msg = I18n . t ( :something_went_wrong ) end end flash [ :notice ] = msg redirect_to ( ( appointments . size == 0 ) || ( ! is_ok ) ? week_plan_path ( ) : receipts_path ( ) ) end
Issues the receipt, updating also all associated Appointment instances.
Issues the receipt updating also all associated Appointment instances .
# (This is not supposed to be used with an Ajax call) # DEBUG # Parse params: # Collect all the Appointment IDs we have to process into a single array: # Single-appointment Receipt, typical case # Multi-appointment Receipt, typical case # (Backward-compatibility case) # (Backward-compatibility case) # set OK status depending on whether we have any IDs for retrieval or not # set a default flash msg to enhance the scope of the variable # Get an array of all the rows to be updated # DEBUG # Any valid row instances found and ready to be processed? Prepare data for the creation of a new receipt: # Init collected values: # Compute collect price and "all_is_payed" flag # Preset additional values # DEBUG # ----- START TRANSACTION ----- # Receipt save (possibly) sucessful?... # ...Iterate on all appointments: # Update currently processed appointment instance:     # No receipt issued yet? (This should be the norm) => Update receipt ID # (end of loop) # Receipt save failure! # ----- END TRANSACTION ----- # Set an O-K message only if everything went as expected: # Appointment instance list was empty? # User didn't select anything: # Something was selected, but nothing was retrieved: # Set the flash message and set the redirect: