Class: Morpheus::Cli::CatalogCommand

Inherits:
Object
  • Object
show all
Includes:
CliCommand, OptionSourceHelper, ProvisioningHelper
Defined in:
lib/morpheus/cli/service_catalog_command.rb

Overview

CLI command for the Service Catalog (Persona): Dashboard / Catalog / Inventory Inventory Items are the main actions, list, get, remove The add command adds to the cart and checkout places an order with the cart. The add-order command allows submitting a new order at once.

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from OptionSourceHelper

#find_available_user_option, #find_cloud_option, #find_group_option, #find_tenant_option, #get_available_user_options, #get_cloud_options, #get_group_options, #get_tenant_options, included, #load_option_source_data, #options_interface, #parse_cloud_id_list, #parse_group_id_list, #parse_option_source_id_list, #parse_project_id_list, #parse_tenant_id_list, #parse_user_id_list

Methods included from ProvisioningHelper

#accounts_interface, #add_perms_options, #api_client, #apps_interface, #cloud_datastores_interface, #clouds_interface, #datastores_interface, #find_app_by_id, #find_app_by_name, #find_app_by_name_or_id, #find_cloud_by_id_for_provisioning, #find_cloud_by_name_for_provisioning, #find_cloud_by_name_or_id_for_provisioning, #find_cloud_resource_pool_by_name_or_id, #find_group_by_id_for_provisioning, #find_group_by_name_for_provisioning, #find_group_by_name_or_id_for_provisioning, #find_host_by_id, #find_host_by_name, #find_host_by_name_or_id, #find_instance_by_id, #find_instance_by_name, #find_instance_by_name_or_id, #find_instance_type_by_code, #find_instance_type_by_id, #find_instance_type_by_name, #find_instance_type_by_name_or_id, #find_instance_type_layout_by_id, #find_server_by_id, #find_server_by_name, #find_server_by_name_or_id, #find_workflow_by_id, #find_workflow_by_name, #find_workflow_by_name_or_id, #format_app_status, #format_blueprint_type, #format_container_connection_string, #format_container_status, #format_instance_connection_string, #format_instance_container_display_name, #format_instance_status, #format_metadata, #format_snapshot_status, #get_available_accounts, #get_available_clouds, #get_available_environments, #get_available_groups, #get_available_plans, #get_provision_type_for_zone_type, #get_static_environments, included, #instance_type_layouts_interface, #instance_types_interface, #instances_interface, #load_balance_protocols_dropdown, #options_interface, #parse_blueprint_type, #parse_host_id_list, #parse_instance_id_list, #parse_metadata, #parse_resource_id_list, #parse_server_id_list, #print_permissions, #prompt_evars, #prompt_exposed_ports, #prompt_instance_load_balancer, #prompt_metadata, #prompt_network_interfaces, #prompt_new_instance, #prompt_permissions, #prompt_resize_volumes, #prompt_security_groups, #prompt_volumes, #provision_types_interface, #reject_service_plan_option_types, #servers_interface

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_refresh_interval, #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

Instance Method Details

#_get(id, params, options) ⇒ Object



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
438
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
478
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
# File 'lib/morpheus/cli/service_catalog_command.rb', line 411

def _get(id, params, options)
  catalog_item = find_catalog_item_by_name_or_id(id)
  return 1, "catalog item not found for name or id '#{id}'" if catalog_item.nil?
  @service_catalog_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @service_catalog_interface.dry.get_inventory(catalog_item['id'], params)
    return
  end
  # skip redundant request
  json_response = {catalog_item_object_key => catalog_item}
  # if id !~ /\A\d{1,}\Z/
  #   json_response = @service_catalog_interface.get_inventory(catalog_item['id'], params)
  # end
  catalog_item = json_response[catalog_item_object_key]
  item_config = catalog_item['config']
  item_type_code = catalog_item['type']['type'].to_s.downcase rescue nil
  item_instance = catalog_item['instance']
  item_app = catalog_item['app']
  item_execution = catalog_item['execution']
  render_response(json_response, options, catalog_item_object_key) do
    print_h1 "Catalog Item Details", [], options
    print cyan
    show_columns = catalog_item_column_definitions
    # show_columns.delete("Status") if catalog_item['status'].to_s.lowercase == 'ORDERED'
    show_columns.delete("Status") if item_instance || item_app || item_execution
    print_description_list(show_columns, catalog_item)

    if item_config && !item_config.empty?
      # print_h2 "Configuration", options
      # print cyan
      # print as_description_list(item_config, item_config.keys, options)
      # print "\n", reset
    end

    if item_type_code == 'instance'
      if item_instance
        print_h2 "Instance", options
        print cyan
        item_instance_columns = [
            {"ID" => lambda {|it| it['id'] } },
            {"NAME" => lambda {|it| it['name'] } },
            {"STATUS" => lambda {|it| format_instance_status(it) } },
          ]
          #print as_description_list(item_instance, item_instance_columns, options)
          print as_pretty_table([item_instance], item_instance_columns, options)
        # print "\n", reset
      else
        print "\n"
        print yellow, "No instance found", reset, "\n"
      end
    end

    if item_type_code == 'app' || item_type_code == 'blueprint' || item_type_code == 'apptemplate'
      if item_app
        print_h2 "App", options
        print cyan
        item_app_columns = [
            {"ID" => lambda {|it| it['id'] } },
            {"NAME" => lambda {|it| it['name'] } },
            {"STATUS" => lambda {|it| format_app_status(it) } },
          ]
          #print as_description_list(item_app, item_app_columns, options)
          print as_pretty_table([item_app], item_app_columns, options)
        # print "\n", reset
      else
        print "\n"
        print yellow, "No app found", reset, "\n"
      end
    end

    if item_type_code == 'workflow' || item_type_code == 'operationalworkflow' || item_type_code == 'taskset'
      if item_execution
        print_h2 "Workflow Results", options
        print cyan
        item_workflow_columns = [
            {"EXECUTION ID" => lambda {|it| item_execution ? item_execution['id'] : '' } },
            {"CONTEXT TYPE" => lambda {|it| it['name'] } },
            {"RESOURCE" => lambda {|it| (it['targets'] ? it['targets'].collect { |target| target['name'] }.join(', ') : '') rescue '' } },
            {"STATUS" => lambda {|it| item_execution ? format_job_execution_status(item_execution) : 'N/A' } },
          ]
          #print as_description_list(catalog_item, item_workflow_columns, options)
          print as_pretty_table([catalog_item], item_workflow_columns, options)
        # print "\n", reset
      else
        print "\n"
        print yellow, "No execution found", reset, "\n"
      end
    end

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

#_get_type(id, params, options) ⇒ Object



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

def _get_type(id, params, options)
  catalog_item_type = nil
  if id.to_s !~ /\A\d{1,}\Z/
    catalog_item_type = find_catalog_item_type_by_name(id)
    return 1, "catalog item type not found for #{id}" if catalog_item_type.nil?
    id = catalog_item_type['id']
  end
  @service_catalog_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @service_catalog_interface.dry.get_type(id, params)
    return
  end
  json_response = @service_catalog_interface.get_type(id, params)
  catalog_item_type = json_response[catalog_item_type_object_key]
  # need to load by id to get optionTypes
  # maybe do ?name=foo&includeOptionTypes=true 
  if catalog_item_type['optionTypes'].nil?
    catalog_item_type = find_catalog_item_type_by_id(catalog_item_type['id'])
    return [1, "catalog item type not found"] if catalog_item_type.nil?
  end
  render_response(json_response, options, catalog_item_type_object_key) do
    print_h1 "Catalog Type Details", [], options
    print cyan
    show_columns = catalog_item_type_column_definitions
    print_description_list(show_columns, catalog_item_type)

    if catalog_item_type['optionTypes'] && catalog_item_type['optionTypes'].size > 0
      print_h2 "Configuration Options"
      print as_pretty_table(catalog_item_type['optionTypes'], {
        "LABEL" => lambda {|it| it['fieldLabel'] },
        "NAME" => lambda {|it| it['fieldName'] },
        "TYPE" => lambda {|it| it['type'] },
        "REQUIRED" => lambda {|it| format_boolean it['required'] },
      })
    else
      # print cyan,"No option types found for this catalog item.","\n",reset
    end

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

#add(args) ⇒ Object



590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
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
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
# File 'lib/morpheus/cli/service_catalog_command.rb', line 590

def add(args)
  options = {}
  params = {}
  payload = {}
  type_id = nil
  workflow_context = nil
  workflow_target = nil
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[type] [options]")
    opts.on('-t', '--type TYPE', String, "Catalog Item Type Name or ID") do |val|
      type_id = val.to_s
    end
    opts.on('--validate','--validate', "Validate Only. Validates the configuration and skips adding the item.") do
      options[:validate_only] = true
    end
    opts.on('--context [instance|server]', String, "Context Type for operational workflow types") do |val|
      workflow_context = val.to_s
    end
    opts.on('--target ID', String, "Target Resource (Instance or Server) for operational workflow types") do |val|
      workflow_target = val.to_s
    end
    opts.add_hidden_option('--sigdig')
    build_standard_update_options(opts, options, [:sigdig])
    opts.footer = <<-EOT
Add an item to your cart
[type] is required, this is name or id of a catalog item type.
Catalog item types may require additional configuration.
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, min:0)
  connect(options)
  if args.count > 0
    type_id = args.join(" ")
  end
  payload = {}
  add_item_object_key = 'item'
  payload = {add_item_object_key => {} }
  if options[:payload]
    payload = options[:payload]
    payload.deep_merge!({add_item_object_key => parse_passed_options(options)})
  else
    payload.deep_merge!({add_item_object_key => parse_passed_options(options)})
    # prompt for Type
    if type_id
      catalog_item_type = find_catalog_item_type_by_name_or_id(type_id)
      return [1, "catalog item type not found"] if catalog_item_type.nil?
    elsif
      catalog_type_option_type = {'fieldName' => 'type', 'fieldLabel' => 'Type', 'type' => 'select', 'optionSource' => lambda { |api_client, api_params| 
        # @options_interface.options_for_source("licenseTypes", {})['data']
        @service_catalog_interface.list_types({max:10000})['catalogItemTypes'].collect {|it|
          {'name' => it['name'], 'value' => it['id']}
        } }, 'required' => true, 'description' => 'Catalog Item Type name or id'}
      type_id = Morpheus::Cli::OptionTypes.prompt([catalog_type_option_type], options[:options], @api_client, options[:params])['type']
      catalog_item_type = find_catalog_item_type_by_name_or_id(type_id.to_s)
      return [1, "catalog item type not found"] if catalog_item_type.nil?
    end
    # use name instead of id
    payload[add_item_object_key]['type'] = {'name' => catalog_item_type['name']}
    #payload[add_item_object_key]['type'] = {'id' => catalog_item_type['id']}

    # this is silly, need to load by id to get optionTypes
    # maybe do ?name=foo&includeOptionTypes=true 
    if catalog_item_type['optionTypes'].nil?
      catalog_item_type = find_catalog_item_type_by_id(catalog_item_type['id'])
      return [1, "catalog item type not found"] if catalog_item_type.nil?
    end
    catalog_option_types = catalog_item_type['optionTypes']
    # instead of config.customOptions just use config...
    catalog_option_types = catalog_option_types.collect {|it|
      it['fieldContext'] = 'config'
      it
    }
    if catalog_option_types && !catalog_option_types.empty?
      config_prompt = Morpheus::Cli::OptionTypes.prompt(catalog_option_types, options[:options], @api_client, {})['config']
      payload[add_item_object_key].deep_merge!({'config' => config_prompt})
    end
    if workflow_context
      payload[add_item_object_key]['context'] = workflow_context
    else
      # the catalog item type determines if context selection is required
      # only blank string means you can choose? err
      if catalog_item_type['context'] == ''
        context_option_type = {'fieldName' => 'context', 'fieldLabel' => 'Context Type', 'type' => 'select', 'optionSource' => lambda { |api_client, api_params| 
          [{'name' => "none", 'value' => "appliance"}, {'name' => "Instance", 'value' => "instance"}, {'name' => "Server", 'value' => "server"}]
          }, 'required' => true, 'description' => 'Context for operational workflow, determines target type', 'defaultValue' => 'instance'}
        workflow_context = Morpheus::Cli::OptionTypes.prompt([context_option_type], options[:options], @api_client, options[:params])['context']
      elsif !catalog_item_type['context'].nil?
        workflow_context = catalog_item_type['context']
      end
      payload[add_item_object_key]['context'] = workflow_context
    end

    if workflow_target
      payload[add_item_object_key]['targets'] = [{id: workflow_target}]
    else
      # prompt for Resource (target)
      if workflow_context == 'instance' 
        target_option_type = {'fieldName' => 'target', 'fieldLabel' => 'Resource (Instance)', 'type' => 'select', 'optionSource' => lambda { |api_client, api_params| 
          # todo: @instances_interface should not be required here
          # @options_interface.options_for_source("instances", {})['data']
          @instances_interface.list({max:10000})['instances'].collect {|it|
            {'name' => it['name'], 'value' => it['id']}
          } }, 'required' => true, 'description' => 'Target Instance'}
        workflow_target = Morpheus::Cli::OptionTypes.prompt([target_option_type], options[:options], @api_client, options[:params])['target']
        payload[add_item_object_key]['targets'] = [{id: workflow_target}]
        payload[add_item_object_key].delete('target')
      elsif workflow_context == 'server'
        target_option_type = {'fieldName' => 'target', 'fieldLabel' => 'Resource (Server)', 'type' => 'select', 'optionSource' => lambda { |api_client, api_params| 
          # todo: @servers_interface should not be required here
          # @options_interface.options_for_source("searchServers", {})['data']
          @servers_interface.list({max:10000})['servers'].collect {|it|
            {'name' => it['name'], 'value' => it['id']}
          } }, 'required' => true, 'description' => 'Target Server'}
        workflow_target = Morpheus::Cli::OptionTypes.prompt([target_option_type], options[:options], @api_client, options[:params])['target']
        payload[add_item_object_key]['targets'] = [{id: workflow_target}]
        payload[add_item_object_key].delete('target')
      end
    end
  end
  if options[:validate_only]
    params['validate'] = true
  end
  @service_catalog_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @service_catalog_interface.dry.create_cart_item(payload, params)
    return
  end
  json_response = @service_catalog_interface.create_cart_item(payload, params)
  cart_item = json_response['item']
  render_response(json_response, options) do
    if options[:validate_only]
      if json_response['success']
        print_h2 "Validated Cart Item", [], options
        cart_item_columns = {
          "Type" => lambda {|it| it['type']['name'] rescue '' },
          #"Qty" => lambda {|it| it['quantity'] },
          "Price" => lambda {|it| it['price'] ? format_money(it['price'] , it['currency'], {sigdig:options[:sigdig] || default_sigdig}) : "No pricing configured" },
          "Status" => lambda {|it| 
            status_string = format_catalog_item_status(it)
            if it['errorMessage'].to_s != ""
              status_string << " - #{it['errorMessage']}"
            end
            status_string
          },
          #"Config" => lambda {|it| truncate_string(format_name_values(it['config']), 50) }
        }
        print as_pretty_table([cart_item], cart_item_columns.upcase_keys!)
        print reset, "\n"
        print_green_success(json_response['msg'] || "Item is valid")
        print reset, "\n"
      else
        # not needed because it will be http 400
        print_rest_errors(json_response, options)
      end
    else
      print_green_success "Added item to cart"
      get_cart([] + (options[:remote] ? ["-r",options[:remote]] : []))
    end
  end
  if json_response['success']
    return 0, nil
  else
    # not needed because it will be http 400
    return 1, json_response['msg'] || 'request failed'
  end
end

#add_order(args) ⇒ Object



921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
# File 'lib/morpheus/cli/service_catalog_command.rb', line 921

def add_order(args)
  options = {}
  params = {}
  payload = {}
  type_id = nil
  workflow_context = nil
  workflow_target = nil
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[type] [options]")
    opts.on('-t', '--type TYPE', String, "Catalog Item Type Name or ID") do |val|
      type_id = val.to_s
    end
    opts.on('--validate','--validate', "Validate Only. Validates the configuration and skips creating the order.") do
      options[:validate_only] = true
    end
    opts.on('-a', '--details', "Display all details: item configuration." ) do
      options[:details] = true
    end
    opts.on('--context [instance|server]', String, "Context Type for operational workflow types") do |val|
      workflow_context = val.to_s
    end
    opts.on('--target ID', String, "Target Resource (Instance or Server) for operational workflow types") do |val|
      workflow_target = val.to_s
    end
    build_standard_add_options(opts, options, [:sigdig])
    opts.footer = <<-EOT
Place an order for new inventory.
This allows creating a new order without using the cart.
The order must contain one or more items, each with a valid type and configuration.
By default the order is placed right away.
Use the --validate option to validate and review the order without actually placing it.
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, min:0)
  connect(options)
  if args.count > 0
    type_id = args.join(" ")
  end
  payload = {}
  order_object_key = 'order'
  payload = {order_object_key => {} }
  passed_options = parse_passed_options(options)
  if options[:payload]
    payload = options[:payload]
    payload.deep_merge!({order_object_key => passed_options}) unless passed_options.empty?
  else
    payload.deep_merge!({order_object_key => passed_options}) unless passed_options.empty?

    # Prompt for 1-N Types
    # still_prompting = options[:no_prompt] != true
    still_prompting = true
    available_catalog_item_types = @service_catalog_interface.list_types({max:10000})['catalogItemTypes'].collect {|it|
      {'name' => it['name'], 'value' => it['id']}
    }
    type_cache = {} # prevent repeat lookups
    while still_prompting do
      item_payload = {}
      # prompt for Type
      if type_id
        catalog_item_type = type_cache[type_id.to_s] || find_catalog_item_type_by_name_or_id(type_id)
        return [1, "catalog item type not found"] if catalog_item_type.nil?
      elsif
        type_id = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'type', 'fieldLabel' => 'Type', 'type' => 'select', 'selectOptions' => available_catalog_item_types, 'required' => true, 'description' => 'Catalog Item Type name or id'}], options[:options], @api_client, options[:params])['type']
        catalog_item_type = type_cache[type_id.to_s] || find_catalog_item_type_by_name_or_id(type_id.to_s)
        return [1, "catalog item type not found"] if catalog_item_type.nil?
      end
      type_cache[type_id.to_s] = catalog_item_type
      # use name instead of id
      item_payload['type'] = {'name' => catalog_item_type['name']}
      #payload[add_item_object_key]['type'] = {'id' => catalog_item_type['id']}

      # this is silly, need to load by id to get optionTypes
      # maybe do ?name=foo&includeOptionTypes=true 
      if catalog_item_type['optionTypes'].nil?
        catalog_item_type = find_catalog_item_type_by_id(catalog_item_type['id'])
        return [1, "catalog item type not found"] if catalog_item_type.nil?
      end
      catalog_option_types = catalog_item_type['optionTypes']
      # instead of config.customOptions just use config...
      catalog_option_types = catalog_option_types.collect {|it|
        it['fieldContext'] = 'config'
        it
      }
      if catalog_option_types && !catalog_option_types.empty?
        config_prompt = Morpheus::Cli::OptionTypes.prompt(catalog_option_types, options[:options], @api_client, {})['config']
        item_payload.deep_merge!({'config' => config_prompt})
      end
      
      if workflow_context
        item_payload['context'] = workflow_context
      else
        # the catalog item type determines if context selection is required
        # only blank string means you can choose? err
        if catalog_item_type['context'] == ''
          context_option_type = {'fieldName' => 'context', 'fieldLabel' => 'Context Type', 'type' => 'select', 'optionSource' => lambda { |api_client, api_params| 
            [{'name' => "Instance", 'value' => "instance"}, {'name' => "Server", 'value' => "server"}]
            }, 'required' => true, 'description' => 'Context for operational workflow, determines target type', 'defaultValue' => 'instance'}
          workflow_context = Morpheus::Cli::OptionTypes.prompt([context_option_type], options[:options], @api_client, options[:params])['context']
        elsif !catalog_item_type['context'].nil?
          workflow_context = catalog_item_type['context']
        end
        item_payload['context'] = workflow_context if workflow_context
      end

      if workflow_target
        item_payload['targets'] = [{id: workflow_target}]
      else
        # prompt for Resource (target)
        if workflow_context == 'instance' 
          target_option_type = {'fieldName' => 'target', 'fieldLabel' => 'Resource (Instance)', 'type' => 'select', 'optionSource' => lambda { |api_client, api_params| 
            # todo: @instances_interface should not be required here
            # @options_interface.options_for_source("instances", {})['data']
            @instances_interface.list({max:10000})['instances'].collect {|it|
              {'name' => it['name'], 'value' => it['id']}
            } }, 'required' => true, 'description' => 'Target Instance'}
          workflow_target = Morpheus::Cli::OptionTypes.prompt([target_option_type], options[:options], @api_client, options[:params])['target']
          item_payload['targets'] = [{id: workflow_target}]
          item_payload.delete('target')
        elsif workflow_context == 'server'
          target_option_type = {'fieldName' => 'target', 'fieldLabel' => 'Resource (Server)', 'type' => 'select', 'optionSource' => lambda { |api_client, api_params| 
            # todo: @servers_interface should not be required here
            # @options_interface.options_for_source("searchServers", {})['data']
            @servers_interface.list({max:10000})['servers'].collect {|it|
              {'name' => it['name'], 'value' => it['id']}
            } }, 'required' => true, 'description' => 'Target Server'}
          workflow_target = Morpheus::Cli::OptionTypes.prompt([target_option_type], options[:options], @api_client, options[:params])['target']
          item_payload['targets'] = [{id: workflow_target}]
          item_payload.delete('target')
        end
      end

      payload[order_object_key]['items'] ||= []
      payload[order_object_key]['items'] << item_payload

      if options[:no_prompt]
        still_prompting = false
      else
        if Morpheus::Cli::OptionTypes.confirm("Add another item?", {default: false})
          still_prompting = true
          # clear values for subsequent items, should just use for a different fieldContext instead..
          type_id = nil
          options[:options] = {}
        else
          still_prompting = false
        end
      end

    end
    
    
  end
  if options[:validate_only]
    params['validate'] = true
    #payload['validate'] = true
  end
  @service_catalog_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @service_catalog_interface.dry.create_order(payload, params)
    return
  end
  json_response = @service_catalog_interface.create_order(payload, params)
  order = json_response['order'] || json_response['cart']
  render_response(json_response, options) do
    if options[:validate_only]
      if json_response['success']
        print_h2 "Review Order", [], options
        print_order_details(order, options)
        print_green_success(json_response['msg'] || "Order is valid")
        print reset, "\n"
      else
        # not needed because it will be http 400
        print_rest_errors(json_response, options)
      end
    else
      print_green_success "Order placed"
      print_h2 "Order Details", [], options
      print_order_details(order, options)
    end
  end
  if json_response['success']
    return 0, nil
  else
    # not needed because it will be http 400
    return 1, json_response['msg'] || 'request failed'
  end
end

#checkout(args) ⇒ Object



867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
# File 'lib/morpheus/cli/service_catalog_command.rb', line 867

def checkout(args)
  options = {}
  params = {}
  payload = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    build_standard_add_options(opts, options, [:auto_confirm, :sigdig])
    opts.footer = <<-EOT
Checkout to complete your cart and place an order.
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:0)
  connect(options)
  # fetch current cart
  # cart = @service_catalog_interface.get_cart()['cart']
  params.merge!(parse_query_options(options))
  payload = {}
  if options[:payload]
    payload = options[:payload]
  end
  update_cart_object_key = 'order'
  passed_options = parse_passed_options(options)
  payload.deep_merge!({update_cart_object_key => passed_options}) unless passed_options.empty?
  
  @service_catalog_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @service_catalog_interface.dry.checkout(payload)
    return
  end

  # checkout
  print_h1 "Checkout"

  # review cart
  # should load this first, but do this to avoid double load
  cmd_result, cmd_err = get_cart(["--thin"] + (options[:remote] ? ["-r",options[:remote]] : []))
  if cmd_result != 0
    print_red_alert "You must add items before you can checkout. Try `catalog add`"
    return cmd_result, cmd_err
  end
      
  unless options[:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to checkout and place an order?")
    return 9, "aborted command"
  end
  json_response = @service_catalog_interface.checkout(payload, params)
  render_response(json_response, options) do
    print_green_success "Order placed"
    # ok so this is delayed because list does not return all statuses right now..
    #list([] + (options[:remote] ? ["-r",options[:remote]] : []))
  end
  return 0, nil
end

#clear_cart(args) ⇒ Object



834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
# File 'lib/morpheus/cli/service_catalog_command.rb', line 834

def clear_cart(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("--name [name]")
    build_standard_remove_options(opts, options, [:sigdig])
    opts.footer = <<-EOT
Clear your cart.
This will empty the cart, deleting all items.
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:0)
  connect(options)
  # fetch current cart
  # cart = @service_catalog_interfaceg.get_cart()['cart']
  params.merge!(parse_query_options(options))
  @service_catalog_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @service_catalog_interface.dry.clear_cart(params)
    return
  end
  unless options[:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to clear your cart?")
    return 9, "aborted command"
  end
  json_response = @service_catalog_interface.clear_cart(params)
  render_response(json_response, options, 'cart') do
    print_green_success "Cleared cart"
    get_cart([] + (options[:remote] ? ["-r",options[:remote]] : []))
  end
  return 0, nil
end

#connect(opts) ⇒ Object



43
44
45
46
47
48
49
# File 'lib/morpheus/cli/service_catalog_command.rb', line 43

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @service_catalog_interface = @api_client.catalog
  @instances_interface = @api_client.instances
  @servers_interface = @api_client.servers # should not be required here!
  @option_types_interface = @api_client.option_types
end

#dashboard(args) ⇒ Object



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
95
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/morpheus/cli/service_catalog_command.rb', line 55

def dashboard(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    opts.add_hidden_option('--sigdig')
    build_standard_get_options(opts, options, [:sigdig] || default_sigdig)
    opts.footer = <<-EOT
View service catalog dashboard.
Provides an overview of available catalog item types, recent orders and inventory.
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, max:0)
  connect(options)

  params.merge!(parse_list_options(options))
  @service_catalog_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @service_catalog_interface.dry.dashboard(params)
    return
  end
  json_response = @service_catalog_interface.dashboard(params)
  catalog_item_types = json_response['catalogItemTypes']
  catalog_meta = json_response['catalogMeta'] || {}
  recent_items = json_response['recentItems'] || {}
  featured_items = json_response['featuredItems'] || []
  inventory_items = json_response['inventoryItems'] || []
  inventory_meta = json_response['inventoryMeta'] || {}
  cart = json_response['cart'] || {}
  cart_items = cart['items'] || []
  cart_stats = cart['stats'] || {}
  current_invoice = json_response['currentInvoice']
  
  render_response(json_response, options, catalog_item_type_object_key) do
    print_h1 "Catalog Dashboard", [], options
    print cyan
    
    # dashboard_columns = [
    #   {"TYPES" => lambda {|it| catalog_meta['total'] } },
    #   {"INVENTORY" => lambda {|it| inventory_items.size rescue '' } },
    #   {"CART" => lambda {|it| it['cart']['items'].size rescue '' } },
    # ]
    # print as_pretty_table([json_response], dashboard_columns, options)

    print_h2 "Catalog Items"
    print as_pretty_table(catalog_item_types, {
      "NAME" => lambda {|it| it['name'] },
      "DESCRIPTION" => lambda {|it| it['description'] },
      "FEATURED" => lambda {|it| format_boolean it['featured'] },
    }, options)
    # print reset,"\n"

    if recent_items && recent_items.size() > 0
      print_h2 "Recently Ordered"
      print as_pretty_table(recent_items, {
        #"ID" => lambda {|it| it['id'] },
        #"NAME" => lambda {|it| it['name'] },
        "TYPE" => lambda {|it| it['type']['name'] rescue '' },
        #"QTY" => lambda {|it| it['quantity'] },
        "ORDER DATE" => lambda {|it| format_local_dt(it['orderDate']) },
        # "STATUS" => lambda {|it| format_catalog_item_status(it) },
        # "CONFIG" => lambda {|it| truncate_string(format_name_values(it['config']), 50) },
      }, options)
      # print reset,"\n"
    end

    if recent_items && recent_items.size() > 0
      print_h2 "Inventory"
      print as_pretty_table(inventory_items, {
        "ID" => lambda {|it| it['id'] },
        "NAME" => lambda {|it| it['name'] },
        "TYPE" => lambda {|it| it['type']['name'] rescue '' },
        #"QTY" => lambda {|it| it['quantity'] },
        "ORDER DATE" => lambda {|it| format_local_dt(it['orderDate']) },
        "STATUS" => lambda {|it| format_catalog_item_status(it) },
        # "CONFIG" => lambda {|it| format_name_values(it['config']) },
      }, options)
      print_results_pagination(inventory_meta)
    else
      # print_h2 "Inventory"
      # print cyan, "Inventory is empty", reset, "\n"
    end
    
    # print reset,"\n"

    # problematic right now, invoice has all user activity, not just catalog
    show_invoice = false
    if current_invoice && show_invoice
      print_h2 "Current Invoice"
      print cyan
      invoice_columns = {
        # todo: invoice needs to return a currency!!!
        "Compute" => lambda {|it| format_money(it['computePrice'], cart_stats['currency'], {sigdig:options[:sigdig] || default_sigdig}) },
        "Storage" => lambda {|it| format_money(it['storagePrice'], cart_stats['currency'], {sigdig:options[:sigdig] || default_sigdig}) },
        "Memory" => lambda {|it| format_money(it['memoryPrice'], cart_stats['currency'], {sigdig:options[:sigdig] || default_sigdig}) },
        "Network" => lambda {|it| format_money(it['networkPrice'], cart_stats['currency'], {sigdig:options[:sigdig] || default_sigdig}) },
        "Extra" => lambda {|it| format_money(it['extraPrice'], cart_stats['currency'], {sigdig:options[:sigdig] || default_sigdig}) },
        "MTD" => lambda {|it| format_money(it['runningPrice'], cart_stats['currency'], {sigdig:options[:sigdig] || default_sigdig}) },
        "Total (Projected)" => lambda {|it| format_money(it['totalPrice'], cart_stats['currency'], {sigdig:options[:sigdig] || default_sigdig}) },
        #"Items" => lambda {|it| cart['items'].size },
        # "Created" => lambda {|it| format_local_dt(it['dateCreated']) },
        # "Updated" => lambda {|it| format_local_dt(it['lastUpdated']) },
      }
      invoice_columns.delete("Storage") unless current_invoice['storagePrice'] && current_invoice['storagePrice'].to_f > 0
      invoice_columns.delete("Memory") unless current_invoice['memoryPrice'] && current_invoice['memoryPrice'].to_f > 0
      invoice_columns.delete("Network") unless current_invoice['networkPrice'] && current_invoice['networkPrice'].to_f > 0
      invoice_columns.delete("Extra") unless current_invoice['extraPrice'] && current_invoice['extraPrice'].to_f > 0
      print as_pretty_table(current_invoice, invoice_columns.upcase_keys!, options)
    end

    show_cart = cart && cart['items'] && cart['items'].size() > 0
    if show_cart
      if cart
        
        # get_cart([] + (options[:remote] ? ["-r",options[:remote]] : []))
        
        print_h2 "Cart"
        print cyan
        if cart['items'].size() > 0
          # cart_columns = {
          #   "Qty" => lambda {|it| cart['items'].sum {|cart_item| cart_item['quantity'] } },
          #   "Total" => lambda {|it| 
          #     begin
          #       format_money(cart_stats['price'], cart_stats['currency'], {sigdig:options[:sigdig] || default_sigdig}) + (cart_stats['unit'].to_s.empty? ? "" : " / #{cart_stats['unit'] || 'month'}")
          #     rescue => ex
          #       raise ex
          #       # no cart stats eh?
          #     end
          #   },
          # }
          # print as_pretty_table(cart, cart_columns.upcase_keys!, options)


          cart_item_columns = [
            {"ID" => lambda {|it| it['id'] } },
            #{"NAME" => lambda {|it| it['name'] } },
            {"TYPE" => lambda {|it| it['type']['name'] rescue '' } },
            #{"QTY" => lambda {|it| it['quantity'] } },
            {"PRICE" => lambda {|it| it['price'] ? format_money(it['price'] , it['currency'], {sigdig:options[:sigdig] || default_sigdig}) : "No pricing configured" } },
            {"STATUS" => lambda {|it| 
              status_string = format_catalog_item_status(it)
              if it['errorMessage'].to_s != ""
                status_string << " - #{it['errorMessage']}"
              end
              status_string
            } },
            # {"CONFIG" => lambda {|it| 
            #   truncate_string(format_name_values(it['config']), 50)
            # } },
          ]
          print as_pretty_table(cart_items, cart_item_columns)
        
          print reset,"\n"
          print cyan
          if cart_stats['price']
            puts "Total: " + format_money(cart_stats['price'], cart_stats['currency'], {sigdig:options[:sigdig] || default_sigdig}) + " / #{cart_stats['unit'].to_s.empty? ? 'month' : cart_stats['unit']}"
          else
            puts "Total: " + "No pricing configured"
          end
          # print reset,"\n"

        else
          print cyan, "Cart is empty", reset, "\n"
        end
      end
      
    end
    
    print reset,"\n"

  end
  return 0, nil
end

#default_sigdigObject



39
40
41
# File 'lib/morpheus/cli/service_catalog_command.rb', line 39

def default_sigdig
  4
end

#get(args) ⇒ Object



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

def get(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[item]")
    opts.on( '-c', '--config', "Display raw config only. Default is YAML. Combine with -j for JSON instead." ) do
      options[:show_config] = true
    end
    # opts.on('--no-config', "Do not display config content." ) do
    #   options[:no_config] = true
    # end
    build_standard_get_options(opts, options, [:sigdig])
    opts.footer = <<-EOT
Get details about a specific catalog inventory item.
[item] is required. This is the name or id of a catalog inventory item.
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, min:1)
  connect(options)
  id_list = parse_id_list(args)
  return run_command_for_each_arg(id_list) do |arg|
    _get(arg, params, options)
  end
end

#get_cart(args) ⇒ Object



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
537
538
539
540
541
542
# File 'lib/morpheus/cli/service_catalog_command.rb', line 505

def get_cart(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    opts.on('-a', '--details', "Display all details: item configuration." ) do
      options[:details] = true
    end
    build_standard_get_options(opts, options, [:sigdig])
    opts.footer = <<-EOT
Get details of current cart and the items in it.
Exits non-zero if cart is empty.
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:0)
  connect(options)
  
  @service_catalog_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @service_catalog_interface.dry.get_cart(params)
    return 0, nil
  end
  # skip extra query, list has same data as show right now
  json_response = @service_catalog_interface.get_cart(params)
  cart = json_response['cart']
  cart_items = cart['items'] || []
  cart_stats = cart['stats'] || {}
  render_response(json_response, options, 'cart') do
    print_h1 "Catalog Cart", [], options
    print_order_details(cart, options)
  end
  if cart_items.empty?
    return 1, "cart is empty"
  else
    return 0, nil
  end
end

#get_type(args) ⇒ Object



275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# File 'lib/morpheus/cli/service_catalog_command.rb', line 275

def get_type(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    build_standard_get_options(opts, options, [:sigdig])
    opts.footer = <<-EOT
Get details about a specific catalog item type.
[name] is required. This is the name or id of a catalog item type.
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, min:1)
  connect(options)
  id_list = parse_id_list(args)
  return run_command_for_each_arg(id_list) do |arg|
    _get_type(arg, params, options)
  end
end

#handle(args) ⇒ Object



51
52
53
# File 'lib/morpheus/cli/service_catalog_command.rb', line 51

def handle(args)
  handle_subcommand(args)
end

#list(args) ⇒ Object

inventory actions



340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
# File 'lib/morpheus/cli/service_catalog_command.rb', line 340

def list(args)
  options = {}
  params = {}
  ref_ids = []
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[search]")
    opts.on('-t', '--type TYPE', String, "Catalog Item Type Name or ID") do |val|
      type_id = val.to_s
    end
    build_standard_list_options(opts, options, [:sigdig])
    opts.footer = "List catalog inventory."
  end
  optparse.parse!(args)
  connect(options)
  # verify_args!(args:args, optparse:optparse, count:0)
  if args.count > 0
    options[:phrase] = args.join(" ")
  end
  params.merge!(parse_list_options(options))
  @service_catalog_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @service_catalog_interface.dry.list_inventory(params)
    return
  end
  json_response = @service_catalog_interface.list_inventory(params)
  catalog_items = json_response[catalog_item_list_key]
  render_response(json_response, options, catalog_item_list_key) do
    print_h1 "Morpheus Catalog Inventory", parse_list_subtitles(options), options
    if catalog_items.empty?
      print cyan,"No catalog items found.",reset,"\n"
    else
      list_columns = catalog_item_column_definitions.upcase_keys!
      #list_columns["Config"] = lambda {|it| truncate_string(it['config'], 100) }
      print as_pretty_table(catalog_items, list_columns.upcase_keys!, options)
      print_results_pagination(json_response)
    end
    print reset,"\n"
  end
  if catalog_items.empty?
    return 1, "no catalog items found"
  else
    return 0, nil
  end
end

#list_types(args) ⇒ Object



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

def list_types(args)
  options = {}
  params = {}
  ref_ids = []
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[search]")
    opts.on( '--featured [on|off]', String, "Filter by featured" ) do |val|
      params['featured'] = (val.to_s != 'false' && val.to_s != 'off')
    end
    build_standard_list_options(opts, options, [:sigdig])
    opts.footer = "List available catalog item types."
  end
  optparse.parse!(args)
  connect(options)
  # verify_args!(args:args, optparse:optparse, count:0)
  if args.count > 0
    options[:phrase] = args.join(" ")
  end
  params.merge!(parse_list_options(options))
  @service_catalog_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @service_catalog_interface.dry.list_types(params)
    return
  end
  json_response = @service_catalog_interface.list_types(params)
  catalog_item_types = json_response[catalog_item_type_list_key]
  render_response(json_response, options, catalog_item_type_list_key) do
    print_h1 "Morpheus Catalog Types", parse_list_subtitles(options), options
    if catalog_item_types.empty?
      print cyan,"No catalog item types found.",reset,"\n"
    else
      list_columns = catalog_item_type_column_definitions.upcase_keys!
      #list_columns["Config"] = lambda {|it| truncate_string(it['config'], 100) }
      print as_pretty_table(catalog_item_types, list_columns.upcase_keys!, options)
      print_results_pagination(json_response)
    end
    print reset,"\n"
  end
  if catalog_item_types.empty?
    return 1, "no catalog item types found"
  else
    return 0, nil
  end
end

#remove(args) ⇒ Object



1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
# File 'lib/morpheus/cli/service_catalog_command.rb', line 1109

def remove(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[item] [options]")
    opts.on('--remove-instances [true|false]', String, "Remove instances. Default is true. Applies to apps only.") do |val|
      params[:removeInstances] = ['true','on','1',''].include?(val.to_s.downcase)
    end
    opts.on( '-B', '--keep-backups [true|false]', "Preserve copy of backups. Default is false." ) do
      params[:keepBackups] = ['true','on','1',''].include?(val.to_s.downcase)
    end
    opts.on('--preserve-volumes [on|off]', String, "Preserve Volumes. Default is off. Applies to certain types only.") do |val|
      params[:preserveVolumes] = ['true','on','1',''].include?(val.to_s.downcase)
    end
    opts.on('--releaseEIPs [true|false]', String, "Release EIPs. Default is on. Applies to Amazon only.") do |val|
      params[:releaseEIPs] = ['true','on','1',''].include?(val.to_s.downcase)
    end
    opts.on( '-f', '--force', "Force Delete" ) do
      params[:force] = true
    end
    build_standard_remove_options(opts, options, [:sigdig])
    opts.footer = <<-EOT
Delete a catalog inventory item.
This removes the item from the inventory and deprovisions the associated instance(s).
[item] is required. This is the name or id of a catalog inventory item.
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:1)
  connect(options)

  catalog_item = find_catalog_item_by_name_or_id(args[0])
  return 1 if catalog_item.nil?
  
  is_app = (catalog_item['type']['type'] == 'app' || catalog_item['type']['type'] == 'blueprint' || catalog_item['type']['type'] == 'apptemplate') rescue false
  
  params.merge!(parse_query_options(options))
  # delete dialog
  # we do not have provisioning settings right now to know if we can prompt for volumes / eips
  # skip force because it is excessive prompting...
  delete_prompt_options = [
    {'fieldName' => 'removeInstances', 'fieldLabel' => 'Remove Instances', 'type' => 'checkbox', 'defaultValue' => true},
    {'fieldName' => 'keepBackups', 'fieldLabel' => 'Preserve Backups', 'type' => 'checkbox', 'defaultValue' => false},
    #{'fieldName' => 'preserveVolumes', 'fieldLabel' => 'Preserve Volumes', 'type' => 'checkbox', 'defaultValue' => false},
    # {'fieldName' => 'releaseEIPs', 'fieldLabel' => 'Release EIPs. Default is on. Applies to Amazon only.', 'type' => 'checkbox', 'defaultValue' => true},
    #{'fieldName' => 'force', 'fieldLabel' => 'Force Delete', 'type' => 'checkbox', 'defaultValue' => false},
  ]
  if !is_app
    delete_prompt_options.reject! {|it| it['fieldName'] == 'removeInstances'}
  end
  options[:options][:no_prompt] = true if options[:yes] # -y could always mean do not prompt too..
  v_prompt = Morpheus::Cli::OptionTypes.prompt(delete_prompt_options, options[:options], @api_client)
  v_prompt.booleanize! # 'on' => true
  params.deep_merge!(v_prompt)

  unless options[:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to delete the inventory item #{catalog_item['id']} '#{catalog_item['name']}'?")
    return 9, "aborted command"
  end
  @service_catalog_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @service_catalog_interface.dry.destroy_inventory(catalog_item['id'], params)
    return
  end
  json_response = @service_catalog_interface.destroy_inventory(catalog_item['id'], params)
  render_response(json_response, options) do
    print_green_success "Removing catalog item"
  end
  return 0, nil
end

#remove_cart_item(args) ⇒ Object



763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
# File 'lib/morpheus/cli/service_catalog_command.rb', line 763

def remove_cart_item(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[id]")
    build_standard_remove_options(opts, options, [:sigdig])
    opts.footer = <<-EOT
Delete an item from the cart.
[id] is required. This is the id of a cart item (also matches on type)
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, max:1)
  connect(options)
  
  # fetch current cart
  cart = @service_catalog_interface.get_cart()['cart']
  cart_items = cart['items'] || []
  cart_item = nil
  item_id = args[0]
  # match cart item on id OR type.name
  if item_id.nil?
    cart_item_option_type = {'fieldName' => 'id', 'fieldLabel' => 'Cart Item', 'type' => 'select', 'optionSource' => lambda { |api_client, api_params| 
        # cart_items.collect {|ci| {'name' => ci['name'], 'value' => ci['id']} }
        cart_items.collect {|ci| {'name' => (ci['type']['name'] rescue ci['name']), 'value' => ci['id']} }
      }, 'required' => true, 'description' => 'Cart Item to be removed'}
    item_id = Morpheus::Cli::OptionTypes.prompt([cart_item_option_type], options[:options], @api_client)['id']
  end
  if item_id
    cart_item = cart_items.find { |ci| ci['id'] == item_id.to_i }
    if cart_item.nil?
      matching_items = cart_items.select { |ci| (ci['type']['name'] rescue nil) == item_id.to_s }
      if matching_items.size > 1
        print_red_alert "#{matching_items.size} cart items matched '#{item_id}'"
        cart_item_columns = [
            {"ID" => lambda {|it| it['id'] } },
            #{"NAME" => lambda {|it| it['name'] } },
            {"Type" => lambda {|it| it['type']['name'] rescue '' } },
            #{"Qty" => lambda {|it| it['quantity'] } },
            {"Price" => lambda {|it| it['price'] ? format_money(it['price'] , it['currency'], {sigdig:options[:sigdig] || default_sigdig}) : "No pricing configured" } },
          ]
        puts_error as_pretty_table(matching_items, cart_item_columns, {color:red})
        print_red_alert "Try using ID instead"
        print reset,"\n"
        return nil
      end
      cart_item = matching_items[0]
    end
  end
  if cart_item.nil?
    err = "Cart item not found for '#{item_id}'"
    print_red_alert err
    return 1, err
  end

  @service_catalog_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @service_catalog_interface.dry.destroy_cart_item(cart_item['id'], params)
    return
  end
  unless options[:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to remove item '#{cart_item['type']['name'] rescue cart_item['id']}' from your cart?")
    return 9, "aborted command"
  end
  json_response = @service_catalog_interface.destroy_cart_item(cart_item['id'], params)
  render_response(json_response, options) do
    print_green_success "Removed item from cart"
    get_cart([] + (options[:remote] ? ["-r",options[:remote]] : []))
  end
  return 0, nil
end

#update_cart(args) ⇒ Object



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

def update_cart(args)
  options = {}
  params = {}
  payload = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("--name [name]")
    opts.on('--name [NAME]', String, "Set an optional name for your catalog order") do |val|
      options[:options]['name'] = val.to_s
    end
    build_standard_update_options(opts, options, [:sigdig])
    opts.footer = <<-EOT
Update your cart settings, such as name.
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:0)
  connect(options)
  # fetch current cart
  # cart = @service_catalog_interface.get_cart()['cart']
  payload = {}
  update_cart_object_key = 'order'
  if options[:payload]
    payload = options[:payload]
    payload.deep_merge!({update_cart_object_key => parse_passed_options(options)})
  else
    payload.deep_merge!({update_cart_object_key => parse_passed_options(options)})
    payload.deep_merge!({update_cart_object_key => params})
    if payload[update_cart_object_key].empty? # || options[:no_prompt]
      raise_command_error "Specify at least one option to update.\n#{optparse}"
    end
  end
  @service_catalog_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @service_catalog_interface.dry.update_cart(payload)
    return
  end
  json_response = @service_catalog_interface.update_cart(payload)
  #cart = json_response['cart']
  #cart = @service_catalog_interface.get_cart()['cart']
  render_response(json_response, options, 'cart') do
    print_green_success "Updated cart"
    get_cart([] + (options[:remote] ? ["-r",options[:remote]] : []))
  end
  return 0, nil
end

#update_cart_item(args) ⇒ Object



758
759
760
761
# File 'lib/morpheus/cli/service_catalog_command.rb', line 758

def update_cart_item(args)
  #todo
  raise_command_error "Not yet implemented"
end