Class: Morpheus::Cli::PricesCommand

Inherits:
Object
  • Object
show all
Includes:
AccountsHelper, CliCommand, ProvisioningHelper, WhoamiHelper
Defined in:
lib/morpheus/cli/prices_command.rb

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from WhoamiHelper

#current_account, #current_user, #current_user_permissions, included, #is_master_account, #load_whoami

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 AccountsHelper

#account_column_definitions, #accounts_interface, #find_account_by_id, #find_account_by_name, #find_account_by_name_or_id, #find_account_from_options, #find_all_user_ids, #find_role_by_id, #find_role_by_name, #find_role_by_name_or_id, #find_user_by_id, #find_user_by_username, #find_user_by_username_or_id, #find_user_group_by_id, #find_user_group_by_name, #find_user_group_by_name_or_id, #format_access_string, #format_role_type, #format_user_role_names, #format_user_status, #get_access_color, #get_access_string, included, #list_account_column_definitions, #list_user_column_definitions, #list_user_group_column_definitions, #role_column_definitions, #roles_interface, #subtenant_role_column_definitions, #user_column_definitions, #user_group_column_definitions, #user_groups_interface, #users_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_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

Instance Method Details

#_get(price_id, options = {}) ⇒ Object



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

def _get(price_id, options = {})
  params = {}
  begin
    @prices_interface.setopts(options)

    if !(price_id.to_s =~ /\A\d{1,}\Z/)
      price = find_price(price_id)

      if !price
        print_red_alert "Price #{price_id} not found"
        exit 1
      end
      price_id = price['id']
    end

    if options[:dry_run]
      print_dry_run @prices_interface.dry.get(price_id)
      return
    end
    json_response = @prices_interface.get(price_id)

    render_result = render_with_format(json_response, options, 'price')
    return 0 if render_result

    title = "Morpheus Price"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles

    price = json_response['price']
    print cyan
    description_cols = {
        "ID" => lambda {|it| it['id']},
        "Name" => lambda {|it| it['name']},
        "Code" => lambda {|it| it['code']},
        "Tenant" => lambda {|it| it['account'].nil? ? ( ? 'All Tenants' : nil) : it['account']['name']},
        "Price Type" => lambda {|it| price_type_label(it['priceType'])}
    }

    if price['priceType'] == 'platform'
      description_cols['Platform'] = lambda {|it| it['platform'].nil? ? nil : it['platform'].capitalize}
    elsif price['priceType'] == 'software'
      description_cols['Software'] = lambda {|it| it['software'].nil? ? nil : it['software']}
    elsif price['priceType'] == 'storage'
      description_cols['Volume Type'] = lambda {|it| it['volumeType'].nil? ? nil : it['volumeType']['name']}
    elsif price['priceType'] == 'datastore'
      description_cols['Data Store'] = lambda {|it| it['datastore'].nil? ? nil : it['datastore']['name']}
      description_cols['Apply Across Clouds'] = lambda {|it| it['crossCloudApply'] == true ? 'On' : 'Off'}
    end

    description_cols['Price Unit'] = lambda {|it| it['priceUnit'].nil? ? nil : it['priceUnit'].capitalize}
    description_cols['Incur Charges'] = lambda {|it| it['incurCharges'].nil? ? nil : (it['incurCharges'] != 'always' ? 'While ' : '') + it['incurCharges'].capitalize}
    description_cols['Currency'] = lambda {|it| (it['currency'] || '').upcase}
    description_cols['Cost'] = lambda {|it| price_prefix(it) + format_amount(it['cost'] || 0)}
    description_cols['Price Adjustment'] = lambda {|it| it['markupType'].nil? ? 'None' : it['markupType'].capitalize}

    if ['fixed', 'percent'].include?(price['markupType'])
      description_cols['Markup'] = lambda {|it| price_markup(it)}
    end

    description_cols['Custom Price'] = lambda {|it| price_prefix(it) + format_amount(it['customPrice'] || 0)}

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

#add(args) ⇒ Object



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
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
# File 'lib/morpheus/cli/prices_command.rb', line 185

def add(args)
  options = {}
  params = {}

  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name] [code]")
    opts.on("--name NAME", String, "Price name") do |val|
      params['name'] = val.to_s
    end
    opts.on("--code CODE", String, "Price code, unique identifier") do |val|
      params['code'] = val.to_s
    end
    opts.on("--tenant [ACCOUNT|all]", String, "Tenant account or all. Apply price to all tenants when not set.") do |val|
      options[:tenant] = val
    end
    opts.on("--type [TYPE]", String, "Price type") do |val|
      if price_types[val]
        params['priceType'] = val
      else
        raise_command_error "Invalid price type '#{val}'. Available price types: #{price_types.keys.join(', ')}"
      end
    end
    opts.on("--unit [UNIT]", String, "Price unit") do |val|
      if price_units.include?(val)
        params['priceUnit'] = val
      else
        raise_command_error "Invalid price unit '#{val}'. Available price units: #{price_units.join(', ')}"
      end
    end
    opts.on("--platform [PLATFORM]", String, "Price platform [linux|windows]. Required for platform price type") do |val|
      if ['linux', 'windows'].include?(val)
        params['platform'] = val
      else
        raise_command_error "Invalid platform '#{val}'. Available platforms: linux, windows"
      end
    end
    opts.on("--software [TEXT]", String, "Price software. Required for software price type") do |val|
      params['software'] = val
    end
    opts.on("--volume [TYPE]", String, "Volume type ID or name. Required for storage price type") do |val|
      options[:volumeType] = val
    end
    opts.on("--datastore [DATASTORE]", String, "Datastore ID or name. Required for datastore price type") do |val|
      options[:datastore] = val
    end
    opts.on("--cross-apply [on|off]", String, "Apply price across clouds. Applicable for datastore price type only") do |val|
      options[:crossCloudApply] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.on("--incur [WHEN]", String, "Incur charges [running|stopped|always]") do |val|
      if ['running', 'stopped', 'always'].include?(val)
        params['incurCharges'] = val
      else
        raise_command_error "Invalid incur charges '#{val}'. Available options: running, stopped, always"
      end
    end
    opts.on("--currency [CURRENCY]", String, "Price currency") do |val|
      if avail_currencies.include?(val.upcase)
        params['currency'] = val.upcase
      else
        raise_command_error "Unsupported currency '#{val}'. Available currencies: #{avail_currencies.join(', ')}"
      end
    end
    opts.on("--cost [AMOUNT]", Float, "Price cost") do |val|
      params['cost'] = val
    end
    opts.on("--fixed-markup [AMOUNT]", Float, "Add fixed price adjustment") do |val|
      params['markupType'] = 'fixed'
      params['markup'] = val
    end
    opts.on("--percent-markup [PERCENT]", Float, "Add percent price adjustment") do |val|
      params['markupType'] = 'percent'
      params['markupPercent'] = val
    end
    opts.on("--custom-price [AMOUNT]", Float, "Set customer price directly. Can be used to override price calculation based on cost and markup") do |val|
      params['markupType'] = 'custom'
      params['customPrice'] = val
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote, :quiet])
    opts.footer = "Create price"
  end
  optparse.parse!(args)
  connect(options)
  if args.count > 2
    raise_command_error "wrong number of arguments, expected 0-2 and got (#{args.count}) #{args}\n#{optparse}"
    return 1
  end

  begin
    payload = parse_payload(options)

    if !payload
      # name
      params['name'] ||= args[0] || Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'name', 'type' => 'text', 'fieldLabel' => 'Price Name', 'required' => true, 'description' => 'Price Set Name.'}],options[:options],@api_client,{}, options[:no_prompt])['name']

      # code
      params['code'] ||= args[1] || Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'code', 'type' => 'text', 'fieldLabel' => 'Price Code', 'required' => true, 'defaultValue' => params['name'].gsub(/[^0-9a-z ]/i, '').gsub(' ', '.').downcase, 'description' => 'Price Set Code.'}],options[:options],@api_client,{}, options[:no_prompt])['code']

      # tenant
      if options[:tenant].nil?
         = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'account', 'type' => 'select', 'fieldLabel' => 'Tenant', 'required' => false, 'description' => 'Assign price to tenant', 'selectOptions' => accounts_interface.list()['accounts'].collect {|it| {'name' => it['name'], 'value' => it['id']}}}], options[:options], @api_client, {}, options[:no_prompt])['account']
        if 
          params['account'] = {'id' => }
        end
      elsif options[:tenant] != 'all'
        if  = (options[:tenant])
          params['account'] = {'id' => ['id']}
        else
          print_red_alert "Tenant #{options[:tenant]} not found"
          exit 1
        end
      end

      # type (platform, software, datastore, storage)
      params['priceType'] ||= Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'priceType', 'type' => 'select', 'fieldLabel' => 'Price Type', 'required' => true, 'description' => 'Select price type', 'selectOptions' => price_types.collect {|k,v| {'name' => v, 'value' => k}}}], options[:options], @api_client, {}, options[:no_prompt])['priceType']

      # price type
      prompt_for_price_type(params, options)

      # unit
      params['priceUnit'] ||= Morpheus::Cli::OptionTypes.prompt(['fieldName' => 'priceUnit', 'type' => 'select', 'fieldLabel' => 'Price Unit', 'required' => true, 'description' => 'Select price unit', 'defaultValue' => 'month', 'selectOptions' => price_units.collect {|it| {'name' => it.split(' ').collect {|it| it.capitalize}.join(' '), 'value' => it}}], options[:options], @api_client, {}, options[:no_prompt])['priceUnit']

      # incur
      params['incurCharges'] ||= Morpheus::Cli::OptionTypes.prompt(['fieldName' => 'incurCharges', 'type' => 'select', 'fieldLabel' => 'Incur Charges', 'required' => true, 'description' => 'Select when to incur charges', 'defaultValue' => 'running', 'selectOptions' => [{'name' => 'When Running', 'value' => 'running'}, {'name' => 'When Stopped', 'value' => 'stopped'}, {'name' => 'Always', 'value' => 'always'}]], options[:options], @api_client, {}, options[:no_prompt])['incurCharges']

      # currency
      params['currency'] ||= Morpheus::Cli::OptionTypes.prompt(['fieldName' => 'currency', 'type' => 'select', 'fieldLabel' => 'Currency', 'required' => true, 'description' => 'Select when to incur charges', 'defaultValue' => 'USD', 'selectOptions' => avail_currencies.collect {|it| {'value' => it}}], options[:options], @api_client, {}, options[:no_prompt])['currency']

      # cost
      if params['cost'].nil?
        params['cost'] = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'cost', 'type' => 'number', 'fieldLabel' => 'Cost', 'required' => true, 'description' => 'Price cost', 'defaultValue' => 0.0}],options[:options],@api_client,{}, options[:no_prompt])['cost']
      end

      # adjustment / markup type
      if params['markupType'].nil?
        markup_type = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'markupType', 'type' => 'select', 'fieldLabel' => 'Price Adjustment', 'required' => false, 'description' => 'Price Adjustment', 'selectOptions' => [{'name' => 'None', 'value' => 'none'}, {'name' => 'Fixed Markup', 'value' => 'fixed'}, {'name' => 'Percent Markup', 'value' => 'percent'}, {'name' => 'Custom Price', 'value' => 'custom'}], 'defaultValue' => 'none'}],options[:options],@api_client,{}, options[:no_prompt])['markupType']

        if markup_type && markup_type != 'none'
          params['markupType'] = markup_type
        end
      end

      prompt_for_markup_type(params, options)

      payload = {'price' => params}
    end

    @prices_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @prices_interface.dry.create(payload)
      return
    end
    json_response = @prices_interface.create(payload)

    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      if json_response['success']
        print_green_success  "Price created"
        _get(json_response['id'], options)
      else
        print_red_alert "Error creating price: #{json_response['msg'] || json_response['errors']}"
      end
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#connect(opts) ⇒ Object



15
16
17
18
19
# File 'lib/morpheus/cli/prices_command.rb', line 15

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @prices_interface = @api_client.prices
  @accounts_interface = @api_client.accounts
end

#deactivate(args) ⇒ Object



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
537
538
539
540
# File 'lib/morpheus/cli/prices_command.rb', line 488

def deactivate(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage( "[price]")
    build_common_options(opts, options, [:json, :dry_run, :remote])
    opts.footer = "Deactivate price.\n" +
        "[price] is required. Price ID, name or code"
  end
  optparse.parse!(args)
  connect(options)
  if args.count != 1
    raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args}\n#{optparse}"
    return 1
  end

  begin
    price = find_price(args[0])

    if !price
      print_red_alert "Price #{args[0]} not found"
      exit 1
    end

    if price['active'] == false
      print_green_success "Price #{price_set['name']} already deactived."
      return 0
    end

    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to deactivate the price '#{price['name']}'?", options)
      return 9, "aborted command"
    end

    @prices_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @prices_interface.dry.deactivate(price['id'], params)
      return
    end

    json_response = @prices_interface.deactivate(price['id'], params)

    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      print_green_success "Price #{price['name']} deactivate"
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#get(args) ⇒ Object



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/morpheus/cli/prices_command.rb', line 98

def get(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[price]")
    build_common_options(opts, options, [:json, :dry_run, :remote])
    opts.footer = "Get details about a price.\n" +
        "[price] is required. Price ID, name or code"
  end
  optparse.parse!(args)
  if args.count != 1
    raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args}\n#{optparse}"
  end
  connect(options)
  return _get(args[0], options)
end

#handle(args) ⇒ Object



21
22
23
# File 'lib/morpheus/cli/prices_command.rb', line 21

def handle(args)
  handle_subcommand(args)
end

#list(args) ⇒ Object



25
26
27
28
29
30
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
95
96
# File 'lib/morpheus/cli/prices_command.rb', line 25

def list(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    opts.on('-i', '--include-inactive [on|off]', String, "Can be used to enable / disable inactive filter. Default is on") do |val|
      params['includeInactive'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.on('--platform PLATFORM', Array, "Filter by platform eg. linux, windows") do |val|
      params['platform'] = val.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact
    end
    opts.on('--price-unit UNIT', Array, "Filter by priceUnit eg. hour, month") do |val|
      params['priceUnit'] = val.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact
    end
    opts.on('--currency CURRENCY', Array, "Filter by currency eg. usd") do |val|
      params['currency'] = val.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact
    end
    opts.on('--price-type TYPE', Array, "Filter by priceType eg. fixed,platform,software,compute,storage,datastore,memory,cores,cpu") do |val|
      params['priceType'] = val.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact
    end
    build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "List prices."
  end
  optparse.parse!(args)
  #verify_args!(args:args, optparse:optparse, count:0)
  connect(options)
  
  params.merge!(parse_list_options(options))
  params['phrase'] = args.join(' ') if args.count > 0 && params['phrase'].nil? # pass args as phrase, every list command should do this
  load_whoami()
  @prices_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @prices_interface.dry.list(params)
    return
  end
  json_response = @prices_interface.list(params)
  prices = json_response['prices']
  render_response(json_response, options, 'prices') do
    title = "Morpheus Prices"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles
    if prices.empty?
      print yellow,"No prices found.",reset,"\n"
    else
      rows = prices.collect do |it|
        {
            id: (it['active'] ? cyan : yellow) + it['id'].to_s,
            name: it['name'],
            active: format_boolean(it['active']),
            priceType: price_type_label(it['priceType']),
            tenant: it['account'].nil? ? ( ? 'All Tenants' : nil) : it['account']['name'],
            priceUnit: it['priceUnit'].nil? ? nil : it['priceUnit'].capitalize,
            priceAdjustment: it['markupType'].nil? ? 'None' : it['markupType'].capitalize,
            cost: price_prefix(it) + format_amount(it['cost'] || 0),
            markup: price_markup(it),
            price: price_prefix(it) + format_amount(it['markupType'] == 'custom' ? it['customPrice'] || 0 : it['price'] || 0) + cyan
        }
      end
      columns = [
          :id, :name, :active, {'PRICE TYPE' => :priceType}, :tenant, {'PRICE UNIT' => :priceUnit}, {'PRICE ADJUSTMENT' => :priceAdjustment}, :cost, :markup, :price
      ]
      columns.delete(:active) if !params['includeInactive']

      print as_pretty_table(rows, columns, options)
      print_results_pagination(json_response)
    end
    print reset,"\n"
  end
  return 1,  "0 prices found" if prices.empty?
  return 0, nil
end

#update(args) ⇒ Object



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

def update(args)
  options = {}
  params = {}

  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[price]")
    opts.on("--name NAME", String, "Price name") do |val|
      params['name'] = val.to_s
    end
    opts.on("--type [TYPE]", String, "Price type") do |val|
      if price_types[val]
        params['priceType'] = val
      else
        raise_command_error "Invalid price type '#{val}'. Available price types: #{price_types.keys.join(', ')}"
      end
    end
    opts.on("--unit [UNIT]", String, "Price unit") do |val|
      if price_units.include?(val)
        params['priceUnit'] = val
      else
        raise_command_error "Invalid price unit '#{val}'. Available price units: #{price_units.join(', ')}"
      end
    end
    opts.on("--platform [PLATFORM]", String, "Price platform [linux|windows]. Required for platform price type") do |val|
      if ['linux', 'windows'].include?(val)
        params['platform'] = val
      else
        raise_command_error "Invalid platform '#{val}'. Available platforms: linux, windows"
      end
    end
    opts.on("--software [TEXT]", String, "Price software. Required for software price type") do |val|
      params['software'] = val
    end
    opts.on("--volume [TYPE]", String, "Volume type ID or name. Required for storage price type") do |val|
      options[:volumeType] = val
    end
    opts.on("--datastore [DATASTORE]", String, "Datastore ID or name. Required for datastore price type") do |val|
      options[:datastore] = val
    end
    opts.on("--cross-apply [on|off]", String, "Apply price across clouds. Applicable for datastore price type only") do |val|
      options[:crossCloudApply] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.on("--incur [WHEN]", String, "Incur charges [running|stopped|always]") do |val|
      if ['running', 'stopped', 'always'].include?(val)
        params['incurCharges'] = val
      else
        raise_command_error "Invalid incur charges '#{val}'. Available options: running, stopped, always"
      end
    end
    opts.on("--currency [CURRENCY]", String, "Price currency") do |val|
      if avail_currencies.include?(val.upcase)
        params['currency'] = val.upcase
      else
        raise_command_error "Unsupported currency '#{val}'. Available currencies: #{avail_currencies.join(', ')}"
      end
    end
    opts.on("--cost [AMOUNT]", Float, "Price cost") do |val|
      params['cost'] = val
    end
    opts.on("--fixed-markup [AMOUNT]", Float, "Add fixed price adjustment") do |val|
      params['markupType'] = 'fixed'
      params['markup'] = val
    end
    opts.on("--percent-markup [PERCENT]", Float, "Add percent price adjustment") do |val|
      params['markupType'] = 'percent'
      params['markupPercent'] = val
    end
    opts.on("--custom-price [AMOUNT]", Float, "Set customer price directly. Can be used to override price calculation based on cost and markup") do |val|
      params['markupType'] = 'custom'
      params['customPrice'] = val
    end
    opts.on("--restart-usage [on|off]", String, "Apply price changes to usage. Default is on") do |val|
      params['restartUsage'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote, :quiet])
    opts.footer = "Update price\n[price] is required. Price ID, name or code"
  end
  optparse.parse!(args)
  connect(options)
  if args.count != 1
    raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args}\n#{optparse}"
    return 1
  end

  begin
    price = find_price(args[0])

    if price.nil?
      print_red_alert "Price #{args[0]} not found"
      exit 1
    end

    payload = parse_payload(options)

    if payload.nil?
      # price type
      prompt_for_price_type(params, options, price)

      # adjustment / markup type
      prompt_for_markup_type(params, options)

      payload = {'price' => params}
    end

    if payload['price'].empty?
      print_green_success "Nothing to update"
      return
    end

    @prices_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @prices_interface.dry.update(price['id'], payload)
      return
    end
    json_response = @prices_interface.update(price['id'], payload)

    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      if json_response['success']
        print_green_success  "Price updated"
        _get(price['id'], options)
      else
        print_red_alert "Error updating price: #{json_response['msg'] || json_response['errors']}"
      end
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end