Class: Morpheus::Cli::ReportsCommand

Inherits:
Object
  • Object
show all
Includes:
CliCommand
Defined in:
lib/morpheus/cli/reports_command.rb

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from CliCommand

#apply_options, #build_common_options, #build_option_type_options, #build_standard_add_options, #build_standard_delete_options, #build_standard_get_options, #build_standard_list_options, #build_standard_post_options, #build_standard_put_options, #build_standard_remove_options, #build_standard_update_options, #command_description, #command_name, #default_sigdig, #default_subcommand, #establish_remote_appliance_connection, #full_command_usage, #get_subcommand_description, #handle_subcommand, included, #interactive?, #my_help_command, #my_terminal, #my_terminal=, #parse_bytes_param, #parse_id_list, #parse_list_options, #parse_list_subtitles, #parse_passed_options, #parse_payload, #parse_query_options, #print, #print_error, #println, #prog_name, #puts, #puts_error, #raise_args_error, #raise_command_error, #render_response, #run_command_for_each_arg, #subcommand_aliases, #subcommand_description, #subcommand_usage, #subcommands, #usage, #validate_outfile, #verify_args!, #visible_subcommands

Constructor Details

#initializeReportsCommand

Returns a new instance of ReportsCommand.



9
10
11
# File 'lib/morpheus/cli/reports_command.rb', line 9

def initialize()
  # @appliance_name, @appliance_url = Morpheus::Cli::Remote.active_appliance
end

Instance Method Details

#connect(opts) ⇒ Object



13
14
15
16
# File 'lib/morpheus/cli/reports_command.rb', line 13

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @reports_interface = @api_client.reports
end

#default_refresh_intervalObject



23
24
25
# File 'lib/morpheus/cli/reports_command.rb', line 23

def default_refresh_interval
  5
end

#export(args) ⇒ Object



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
# File 'lib/morpheus/cli/reports_command.rb', line 362

def export(args)
  params = {}
  report_format = 'json'
  options = {}
  outfile = nil
  do_overwrite = false
  do_mkdir = false
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[id] [file]")
    build_common_options(opts, options, [:dry_run, :remote])
    opts.on( '--format VALUE', String, "Report Format for exported file, json or csv. Default is json." ) do |val|
      report_format = val
    end
    opts.on( '-f', '--force', "Overwrite existing [local-file] if it exists." ) do
      do_overwrite = true
      # do_mkdir = true
    end
    opts.on( '-p', '--mkdir', "Create missing directories for [local-file] if they do not exist." ) do
      do_mkdir = true
    end
    opts.footer = "Export a report result as json or csv." + "\n" +
                  "[id] is required. This is id of the report result." + "\n" +
                  "[file] is required. This is local destination for the downloaded file."
  end
  optparse.parse!(args)
  if args.count != 2
    raise_command_error "wrong number of arguments, expected 2 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  end
  connect(options)
  begin
    report_result = find_report_result_by_id(args[0])
    return 1 if report_result.nil?

    outfile = args[1]
    outfile = File.expand_path(outfile)
    
    if Dir.exists?(outfile)
      print_red_alert "[file] is invalid. It is the name of an existing directory: #{outfile}"
      return 1
    end
    destination_dir = File.dirname(outfile)
    if !Dir.exists?(destination_dir)
      if do_mkdir
        print cyan,"Creating local directory #{destination_dir}",reset,"\n"
        FileUtils.mkdir_p(destination_dir)
      else
        print_red_alert "[file] is invalid. Directory not found: #{destination_dir}"
        return 1
      end
    end
    if File.exists?(outfile)
      if do_overwrite
        # uhh need to be careful wih the passed filepath here..
        # don't delete, just overwrite.
        # File.delete(outfile)
      else
        print_error Morpheus::Terminal.angry_prompt
        puts_error "[file] is invalid. File already exists: #{outfile}", "Use -f to overwrite the existing file."
        # puts_error optparse
        return 1
      end
    end

    @reports_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @reports_interface.dry.export(report_result['id'], outfile, params, report_format)
      return 0
    end
    json_response = @reports_interface.export(report_result['id'], outfile, params, report_format)
    print_green_success "Exported report result #{report_result['id']} to file #{outfile}"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#find_report_result_by_id(id) ⇒ Object



600
601
602
603
604
605
606
607
608
609
610
611
612
# File 'lib/morpheus/cli/reports_command.rb', line 600

def find_report_result_by_id(id)
  begin
    json_response = @reports_interface.get(id.to_i)
    return json_response['reportResult']
  rescue RestClient::Exception => e
    if e.response && e.response.code == 404
      print_red_alert "Report Result not found by id #{id}"
      return nil
    else
      raise e
    end
  end
end

#find_report_type_by_id(id) ⇒ Object



622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
# File 'lib/morpheus/cli/reports_command.rb', line 622

def find_report_type_by_id(id)
  @all_report_types ||= @reports_interface.types({max: 10000})['reportTypes'] || []
  report_types = @all_report_types.select { |it| id && it['id'] == id.to_i }
  if report_types.empty?
    print_red_alert "Report Type not found by id #{id}"
    return nil
  elsif report_types.size > 1
    print_red_alert "#{report_types.size} report types found by id #{id}"
    rows = report_types.collect do |it|
      {id: it['id'], code: it['code'], name: it['name']}
    end
    print "\n"
    puts as_pretty_table(rows, [:id, :code, :name], {color:red})
    return nil
  else
    return report_types[0]
  end
end

#find_report_type_by_name_or_code(name) ⇒ Object



641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
# File 'lib/morpheus/cli/reports_command.rb', line 641

def find_report_type_by_name_or_code(name)
  @all_report_types ||= @reports_interface.types({max: 10000})['reportTypes'] || []
  report_types = @all_report_types.select { |it| name && it['code'] == name || it['name'] == name }
  if report_types.empty?
    print_red_alert "Report Type not found by code #{name}"
    return nil
  elsif report_types.size > 1
    print_red_alert "#{report_types.size} report types found by code #{name}"
    rows = report_types.collect do |it|
      {id: it['id'], code: it['code'], name: it['name']}
    end
    print "\n"
    puts as_pretty_table(rows, [:id, :code, :name], {color:red})
    return nil
  else
    return report_types[0]
  end
end

#find_report_type_by_name_or_code_id(val) ⇒ Object



614
615
616
617
618
619
620
# File 'lib/morpheus/cli/reports_command.rb', line 614

def find_report_type_by_name_or_code_id(val)
  if val.to_s =~ /\A\d{1,}\Z/
    return find_report_type_by_id(val)
  else
    return find_report_type_by_name_or_code(val)
  end
end

#format_report_status(report_result, return_color = cyan) ⇒ Object



660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
# File 'lib/morpheus/cli/reports_command.rb', line 660

def format_report_status(report_result, return_color=cyan)
  out = ""
  status_string = report_result['status'].to_s
  if status_string == 'ready'
    out << "#{green}#{status_string.upcase}#{return_color}"
  elsif status_string == 'requested'
    out << "#{cyan}#{status_string.upcase}#{return_color}"
  elsif status_string == 'generating'
    out << "#{cyan}#{status_string.upcase}#{return_color}"
  elsif status_string == 'failed'
    out << "#{red}#{status_string.upcase}#{return_color}"
  else
    out << "#{yellow}#{status_string.upcase}#{return_color}"
  end
  out
end

#get(args) ⇒ Object



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
# File 'lib/morpheus/cli/reports_command.rb', line 96

def get(args)
  original_args = args.dup
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[id]")
    opts.on('--refresh [SECONDS]', String, "Refresh until status is ready,failed. Default interval is #{default_refresh_interval} seconds.") do |val|
      options[:refresh_until_status] ||= "ready,failed"
      if !val.to_s.empty?
        options[:refresh_interval] = val.to_f
      end
    end
    opts.on('--refresh-until STATUS', String, "Refresh until a specified status is reached.") do |val|
      options[:refresh_until_status] = val.to_s.downcase
    end
    opts.on('--rows', '--rows', "Print Report Data rows too.") do
      options[:show_data_rows] = true
    end
    opts.on('--view', '--view', "View report result in web browser too.") do
      options[:view_report] = true
    end
    build_common_options(opts, options, [:json, :yaml, :csv, :fields, :outfile, :dry_run, :remote])
    opts.footer = "Get details about a report result." + "\n"
                + "[id] is required. This is the id of the report result."
  end
  optparse.parse!(args)
  if args.count != 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "#{command_name} missing argument: [id]\n#{optparse}"
    return 1
  end
  connect(options)
  begin
    @reports_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @reports_interface.dry.get(args[0].to_i)
      return 0
    end

    report_result = find_report_result_by_id(args[0])
    return 1 if report_result.nil?
    json_response = {'reportResult' => report_result}  # skip redundant request
    # json_response = @reports_interface.get(report['id'])
    #report_result = json_response['reportResult']

    # if options[:json]
    #   puts as_json(json_response, options)
    #   return 0
    # end
    # render_with_format() handles json,yaml,csv,outfile,etc
    render_result = render_with_format(json_response, options, 'reportResult')
    if render_result
      #return render_result
    else
      print_h1 "Morpheus Report Details"
      print cyan
      
      description_cols = {
        "ID" => 'id',
        "Title" => lambda {|it| it['reportTitle'] },
        "Filters" => lambda {|it| it['filterTitle'] },
        "Report Type" => lambda {|it| it['type'].is_a?(Hash) ? it['type']['name'] : it['type'] },
        "Date Run" => lambda {|it| format_local_dt(it['dateCreated']) },
        "Created By" => lambda {|it| it['createdBy'].is_a?(Hash) ? it['createdBy']['username'] : it['createdBy'] },
        "Status" => lambda {|it| format_report_status(it) }
      }
      print_description_list(description_cols, report_result)

      # todo: 
      # 1. format raw output better.  
      # 2. write rendering methods for all the various types...
      if options[:show_data_rows]
        print_h2 "Report Data Rows"
        print cyan
        if report_result['rows']
          # report_result['rows'].each_with_index do |row, index|
          #   print "#{index}: ", row, "\n"
          # end
          term_width = current_terminal_width()
          data_width = term_width.to_i - 30
          if data_width < 0
            data_wdith = 10
          end
          puts as_pretty_table(report_result['rows'], options[:include_fields] || {
            "ID" => lambda {|it| it['id'] },
            "SECTION" => lambda {|it| it['section'] },
            "DATA" => lambda {|it| truncate_string(it['data'], data_width) }
          }, options.merge({:wrap => true}))
          
        else
          print yellow, "No report data found.", reset, "\n"
        end
      end
      
      print reset,"\n"
    end

    # refresh until a status is reached
    if options[:refresh_until_status]
      if options[:refresh_interval].nil? || options[:refresh_interval].to_f < 0
        options[:refresh_interval] = default_refresh_interval
      end
      statuses = options[:refresh_until_status].to_s.downcase.split(",").collect {|s| s.strip }.select {|s| !s.to_s.empty? }
      if !statuses.include?(report_result['status'])
        print cyan, "Refreshing in #{options[:refresh_interval] > 1 ? options[:refresh_interval].to_i : options[:refresh_interval]} seconds"
        sleep_with_dots(options[:refresh_interval])
        print "\n"
        get(original_args)
      end
    end
    if options[:view_report]
      view([report_result['id']])
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#get_type(args) ⇒ Object



538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
# File 'lib/morpheus/cli/reports_command.rb', line 538

def get_type(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    build_standard_get_options(opts, options)
    opts.footer = <<-EOT
Get report type
[name] is required. This is the name of a report type
EOT
  end
  optparse.parse!(args)
  connect(options)
  verify_args!(args:args, optparse:optparse, min:1)
  params.merge!(parse_query_options(options))
  params['name'] = args.join(" ")
  @reports_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @reports_interface.dry.types(params)
    return
  end
  
  # json_response = @reports_interface.types(params)
  # api does not have a show() action right now... so find by code or name only
  report_type = find_report_type_by_name_or_code_id(params['name'])
  return 1 if report_type.nil?
  
  # json_response = @reports_interface.get_type(report_type['id'])
  # report_type = json_response['reportType']
  json_response = {'reportType' => report_type}
  render_response(json_response, options, 'reportType') do
    print_h1 "Report Type Details", [], options
    
    description_cols = {
      "ID" => 'id',
      "Name" => 'name',
      "Code" => 'code',
      "Description" => 'description',
      "Category" => 'category'
    }
    print_description_list(description_cols, report_type)

    print_h2 "Option Types", options
    opt_columns = [
      {"ID" => lambda {|it| it['id'] } },
      {"NAME" => lambda {|it| it['name'] } },
      {"TYPE" => lambda {|it| it['type'] } },
      {"FIELD NAME" => lambda {|it| it['fieldName'] } },
      {"FIELD LABEL" => lambda {|it| it['fieldLabel'] } },
      {"DEFAULT" => lambda {|it| it['defaultValue'] } },
      {"REQUIRED" => lambda {|it| format_boolean it['required'] } },
    ]
    option_types = report_type['optionTypes']
    sorted_option_types = (option_types && option_types[0] && option_types[0]['displayOrder']) ? option_types.sort { |x,y| x['displayOrder'].to_i <=> y['displayOrder'].to_i } : option_types
    print as_pretty_table(sorted_option_types, opt_columns)

    print reset,"\n"
  end
  return 0, nil
  
end

#handle(args) ⇒ Object



27
28
29
# File 'lib/morpheus/cli/reports_command.rb', line 27

def handle(args)
  handle_subcommand(args)
end

#list(args) ⇒ Object



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
# File 'lib/morpheus/cli/reports_command.rb', line 31

def list(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    opts.on( '--type CODE', String, "Report Type code(s)" ) do |val|
      params['reportType'] = val.to_s.split(",").compact.collect {|it| it.strip }
    end
    build_common_options(opts, options, [:list, :query, :json, :dry_run, :remote])
    opts.footer = "List report history."
  end
  optparse.parse!(args)
  connect(options)
  begin
    params.merge!(parse_list_options(options))
    @reports_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @reports_interface.dry.list(params)
      return
    end

    json_response = @reports_interface.list(params)
    if options[:json]
      puts as_json(json_response, options)
      return 0
    end
    report_results = json_response['reportResults']
    
    title = "Morpheus Report History"
    subtitles = []
    if params['type']
      subtitles << "Type: #{params[:type]}".strip
    end
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles

    if report_results.empty?
      print cyan, "No report results found", reset, "\n"
    else
      columns = {
        "ID" => 'id',
        "TITLE" => lambda {|it| truncate_string(it['reportTitle'], 50) },
        "FILTERS" => lambda {|it| truncate_string(it['filterTitle'], 30) },
        "REPORT TYPE" => lambda {|it| it['type'].is_a?(Hash) ? it['type']['name'] : it['type'] },
        "DATE RUN" => lambda {|it| format_local_dt(it['dateCreated']) },
        "CREATED BY" => lambda {|it| it['createdBy'].is_a?(Hash) ? it['createdBy']['username'] : it['createdBy'] },
        "STATUS" => lambda {|it| format_report_status(it) }
      }
      # custom pretty table columns ...
      if options[:include_fields]
        columns = options[:include_fields]
      end
      print as_pretty_table(report_results, columns, options)
      print reset
      print_results_pagination(json_response)
    end

    print reset,"\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#list_types(args) ⇒ Object



479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
# File 'lib/morpheus/cli/reports_command.rb', line 479

def list_types(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    build_standard_list_options(opts, options)
    opts.footer = "List report types."
  end
  optparse.parse!(args)
  if args.count > 0
    options[:phrase] = args.join(" ")
  end
  connect(options)
  params.merge!(parse_list_options(options))
  
  @reports_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @reports_interface.dry.types(params)
    return
  end

  json_response = @reports_interface.types(params)
  report_types = json_response['reportTypes']
  render_response(json_response, options, 'reportTypes') do
    title = "Morpheus Report Types"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles

    report_types = json_response['reportTypes']
    
    if report_types.empty?
      print cyan,"No report types found.",reset,"\n"
    else
      columns = {
        "NAME" => 'name',
        "CODE" => 'code'
      }
      # custom pretty table columns ...
      if options[:include_fields]
        columns = options[:include_fields]
      end
      print as_pretty_table(report_types, columns, options)
      print reset
      if json_response['meta']
        print_results_pagination(json_response)
      else
        print_results_pagination({'meta'=>{'total'=>(report_types.size),'size'=>report_types.size,'max'=>(params['max']||25),'offset'=>(params['offset']||0)}})
      end
    end
    print reset,"\n"
  end
  if report_types.empty?
    return 1, "no report types found"
  else
    return 0, nil
  end
end

#prompt_metadata(options = {}) ⇒ Object

Prompts user for metadata for report filter returns array of metadata objects null, name: “MYTAG”, value: “myvalue”



679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
# File 'lib/morpheus/cli/reports_command.rb', line 679

def (options={})
  #puts "Configure Environment Variables:"
  no_prompt = (options[:no_prompt] || (options[:options] && options[:options][:no_prompt]))
   = {}
   = 0
   = options[:options] && options[:options]["metadata#{}"]
   =  || (!no_prompt && Morpheus::Cli::OptionTypes.confirm("Add a metadata tag filter?", {default: false}))
  while  do
    field_context = "metadata#{}"
     = {}
    ['id'] = nil
     =  == 0 ? "Metadata Tag" : "Metadata Tag [#{+1}]"
    v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'name', 'type' => 'text', 'fieldLabel' => "#{} Name", 'required' => true, 'description' => 'Metadata Tag Name.', 'defaultValue' => ['name']}], options[:options])
    # todo: metadata.type ?
    ['name'] = v_prompt[field_context]['name'].to_s
    v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'value', 'type' => 'text', 'fieldLabel' => "#{} Value", 'required' => true, 'description' => 'Metadata Tag Value', 'defaultValue' => ['value']}], options[:options])
    ['value'] = v_prompt[field_context]['value'].to_s
    [['name']] = ['value']
     += 1
     = options[:options] && options[:options]["metadata#{}"]
     =  || (!no_prompt && Morpheus::Cli::OptionTypes.confirm("Add another metadata tag filter?", {default: false}))
  end

  return 
end

#remove(args) ⇒ Object



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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
# File 'lib/morpheus/cli/reports_command.rb', line 439

def remove(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[id]")
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :remote])
    opts.footer = "Delete a report result." + "\n" +
                  "[id] is required. This is id of the report result."
  end
  optparse.parse!(args)
  if args.count != 1
    raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  end
  connect(options)
  begin
    report_result = find_report_result_by_id(args[0])
    return 1 if report_result.nil?

    unless options[:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to delete the report result: #{report_result['id']}?")
      return 9, "aborted command"
    end

    @reports_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @reports_interface.dry.destroy(report_result['id'])
      return
    end
    json_response = @reports_interface.destroy(report_result['id'])
    if options[:json]
      puts as_json(json_response, options)
      return 0
    end
    print_green_success "Deleted report result #{report_result['id']}"
    #list([])
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#run(args) ⇒ Object



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
# File 'lib/morpheus/cli/reports_command.rb', line 215

def run(args)
  params = {}
  do_refresh = true
  options = {:options => {}}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[type] [options]")
    opts.on( '--type CODE', String, "Report Type code" ) do |val|
      options[:options]['type'] = val
    end
    # opts.on( '--title TITLE', String, "Title for the report" ) do |val|
    #   options[:options]['reportTitle'] = val
    # end
    opts.on(nil, '--no-refresh', "Do not refresh until finished" ) do
      do_refresh = false
    end
    opts.on('--rows', '--rows', "Print Report Data rows too.") do
      options[:show_data_rows] = true
    end
    opts.on('--view', '--view', "View report result in web browser when it is finished.") do
      options[:view_report] = true
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Run a report to generate a new result." + "\n" +
                  "[type] is required. This is code of the report type."
  end
  optparse.parse!(args)
  if args.count > 1
    raise_command_error "wrong number of arguments, expected 0-1 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  end
  if args[0]
    options[:options]['type'] = args[0]
  end
  connect(options)
  begin

    # construct payload
    passed_options = options[:options] ? options[:options].reject {|k,v| k.is_a?(Symbol) } : {}
    payload = nil
    if options[:payload]
      payload = options[:payload]
      payload.deep_merge!({'report' => passed_options})  unless passed_options.empty?
    else
      # prompt for resource folder options
      payload = {
        'report' => {
        }
      }
      # allow arbitrary -O options
      payload.deep_merge!({'report' => passed_options})  unless passed_options.empty?

      # Report Type
      @all_report_types ||= @reports_interface.types({max: 1000})['reportTypes'] || []
      report_types_dropdown = @all_report_types.collect {|it| {"name" => it["name"], "value" => it["code"]} }
      v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'type', 'fieldLabel' => 'Report Type', 'type' => 'select', 'selectOptions' => report_types_dropdown, 'required' => true}], options[:options], @api_client)
      payload['report']['type'] = v_prompt['type']
      # convert name/code/id to code
      report_type = find_report_type_by_name_or_code_id(payload['report']['type'])
      return 1 if report_type.nil?
      payload['report']['type'] = report_type['code']

      # Report Types tell us what the available filters are...
      report_option_types = report_type['optionTypes'] || []
      # report_option_types = report_option_types.collect {|it|
      #   it['fieldContext'] = nil
      #   it
      # }
      # pluck out optionTypes like the UI does..
       = nil
      if report_option_types.find {|it| it['fieldName'] == 'metadata' }
         = report_option_types.delete_if {|it| it['fieldName'] == 'metadata' }
      end

      v_prompt = Morpheus::Cli::OptionTypes.prompt(report_option_types, options[:options], @api_client)
      payload.deep_merge!({'report' => v_prompt}) unless v_prompt.empty?

      # strip out fieldContext: 'config' please
      # just report.startDate instead of report.config.startDate
      if payload['report']['config'].is_a?(Hash)
        payload['report']['config']
        payload['report'].deep_merge!(payload['report'].delete('config'))
      end

      if 
        if !options[:options]['metadata']
           = (options)
          if  && !.empty?
            payload['report']['metadata'] = 
          end
        end
      end

    end

    @reports_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @reports_interface.dry.create(payload)
      return 0
    end
    json_response = @reports_interface.create(payload)
    if options[:json]
      puts as_json(json_response, options)
      return 0
    end

    print_green_success "Created report result #{json_response['reportResult']['id']}"
    print_args = [json_response['reportResult']['id']]
    print_args << "--refresh" if do_refresh
    print_args << "--rows" if options[:show_data_rows]
    print_args << "--view" if options[:view_report]
    get(print_args)
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#view(args) ⇒ Object



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
# File 'lib/morpheus/cli/reports_command.rb', line 332

def view(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[id]")
    build_common_options(opts, options, [:dry_run, :remote])
    opts.footer = "View a report result in a web browser" + "\n" +
                  "[id] is required. This is the id of the report result."
  end
  optparse.parse!(args)
  if args.count != 1
    raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  end
  connect(options)
  begin
    report_result = find_report_result_by_id(args[0])
    return 1 if report_result.nil?

    link = "#{@appliance_url}/login/oauth-redirect?access_token=#{@access_token}\\&redirectUri=/operations/reports/#{report_result['type']['code']}/reportResults/#{report_result['id']}"

    if options[:dry_run]
      puts Morpheus::Util.open_url_command(link)
      return 0
    end
    return Morpheus::Util.open_url(link)
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end