Class: Morpheus::Cli::EmailTemplates

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

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from CliCommand

#add_query_parameter, #apply_options, #build_common_options, #build_get_options, #build_list_options, #build_option_type_options, #build_standard_add_many_options, #build_standard_add_options, #build_standard_api_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, #confirm, #confirm!, #default_refresh_interval, #default_sigdig, #default_subcommand, #establish_remote_appliance_connection, #execute_api, #execute_api_payload, #execute_api_request, #find_all, #find_all_json, #find_by_id, #find_by_name, #find_by_name_or_id, #find_record, #find_record_json, #full_command_usage, #get_interface, #get_list_key, #get_object_key, #get_subcommand_description, #handle_each_payload, #handle_subcommand, included, #interactive?, #my_help_command, #my_terminal, #my_terminal=, #parse_array, #parse_bytes_param, #parse_get_options!, #parse_id_list, #parse_labels, #parse_list_options, #parse_list_options!, #parse_list_subtitles, #parse_options, #parse_parameter_as_resource_id!, #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



82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/morpheus/cli/commands/email_templates_command.rb', line 82

def _get(id, params, options)
  if id.to_s !~ /\A\d{1,}\Z/
    record = find_by_name_or_id('emailTemplate', id)
    if record.nil?
      return 1, "EmailTemplate not found for '#{id}'"
    end
    id = record['id']
  end
  options[:params] = params # parse_options(options, params)
  options.delete(:payload)
  execute_api(@email_templates_interface, :get, [id], options, 'emailTemplate') do |json_response|
    email_template = json_response['emailTemplate']
    print_h1 "EmailTemplate Details", [], options
    print cyan
    columns = email_template_column_definitions
    print_description_list(columns, email_template, options)
    print reset,"\n"
  end
end

#add(args) ⇒ Object



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
# File 'lib/morpheus/cli/commands/email_templates_command.rb', line 102

def add(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage( "[name]")
    opts.on("--type [TEXT]", String, "Type") do |val|
      options[:type] = val.to_s
    end
    opts.on( '--template [TEXT]', "Template" ) do |val|
      options[:template] = val.to_s
    end
    opts.on('--accounts LIST', Array, "Tenant accounts, comma separated list of account IDs") do |list|
      if list.size == 1 && list[0] == 'null' # hacky way to clear it
        options[:accounts] = []
      else
        options[:accounts] = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end

    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Create an email template.\n" +
                  "[name] is required. This is the name of the new template."
  end

  optparse.parse!(args)
  if args.count > 1
    raise_command_error "wrong number of arguments, expected 0-2 and got (#{args.count}) #{args}\n#{optparse}"
  end
  connect(options)

  begin
    payload = nil
    if options[:payload]
      payload = options[:payload]
      # support -O OPTION switch on top of --payload
      payload['emailTemplate'] ||= {}
      if options[:options]
        payload['emailTemplate'].deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) })
      end

      if options[:type]
        payload['emailTemplate']['type'] = options[:type]
      end

      if options[:template]
        payload['emailTemplate']['template'] = options[:template]
      end

      if options[:accounts]
        payload['emailTemplate']['accounts'] = options[:accounts]
      end

    else
      payload = {'emailTemplate' => {}}
     
      # Template Type
      template_type_id = nil
      template_type = options[:type] ? find_template_type_by_name_or_id(options[:type]) : nil

      if template_type
        template_type_id = template_type['id']
      else
        available_template_types = template_types_for_dropdown

        if available_template_types.empty?
          print_red_alert "A template type is required"
          exit 1
        elsif available_template_types.count > 1 && !options[:no_prompt]
          template_type_code = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'templateType', 'type' => 'select', 'fieldLabel' => 'Template Type', 'selectOptions' => template_types_for_dropdown, 'required' => true, 'description' => 'Select Template Type.'}],options[:options],@api_client,{})
          template_type_code = template_type_code["templateType"]
        else
          template_type_code = available_template_types.first['code']
        end
        #template_type = get_template_types.find { |ct| ct['code'] == template_type_code }
      end

      payload['emailTemplate']['code'] = template_type_code
      payload['emailTemplate']['template'] = Morpheus::Cli::OptionTypes.file_content_prompt({'fieldName' => 'source', 'fieldLabel' => 'File Content', 'type' => 'file-content', 'required' => true}, {'source' => {'source' => 'local'}}, nil, {})['content']
      # Tenants
      if options[:accounts]
          payload['emailTemplate']['accounts'] = options[:accounts]
        else
          v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'accounts', 'fieldLabel' => 'Tenants', 'type' => 'text', 'required' => false, 'description' => 'Tenant accounts, comma separated list of account IDs'}], options)
          payload['emailTemplate']['accounts'] = v_prompt['accounts']
        end

    end
    @email_templates_interface.setopts(options)
    if options[:dry_run]
       print_dry_run @email_templates_interface.dry.create(payload)
       return
    end
    json_response = @email_templates_interface.create(payload)
    if options[:json]
       print JSON.pretty_generate(json_response)
       print "\n"
    elsif json_response['success']
       get_args = [json_response["emailTemplate"]["id"]] + (options[:remote] ? ["-r",options[:remote]] : []) + (options[:refresh_interval] ? ['--refresh', options[:refresh_interval].to_s] : [])
       get(get_args)
    else
       print_rest_errors(json_response, options)
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#connect(opts) ⇒ Object



8
9
10
11
# File 'lib/morpheus/cli/commands/email_templates_command.rb', line 8

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @email_templates_interface = @api_client.email_templates
end

#email_template_column_definitionsObject



353
354
355
356
357
358
359
360
361
# File 'lib/morpheus/cli/commands/email_templates_command.rb', line 353

def email_template_column_definitions()
  {
    "ID" => 'id',
    "Name" => 'name',
    "Owner" => lambda {|it| it['owner']['name'] || 'System' },
    "Template" => lambda {|it| it['template'] rescue '' },
    "Tenants" => lambda {|it| it['accounts'].collect {|a| a['name'] }.join(', ') rescue it['owner'] ? 'Global' : ''}
  }
end

#get(args) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/morpheus/cli/commands/email_templates_command.rb', line 61

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

#get_template_types(refresh = false) ⇒ Object



367
368
369
370
371
372
# File 'lib/morpheus/cli/commands/email_templates_command.rb', line 367

def get_template_types(refresh=false)
  if !@template_types || refresh
    @template_types = @email_templates_interface.template_types()['types']
  end
  @template_types
end

#handle(args) ⇒ Object



13
14
15
# File 'lib/morpheus/cli/commands/email_templates_command.rb', line 13

def handle(args)
  handle_subcommand(args)
end

#list(args) ⇒ Object



17
18
19
20
21
22
23
24
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
# File 'lib/morpheus/cli/commands/email_templates_command.rb', line 17

def list(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[search]")

    build_standard_list_options(opts, options)
    opts.footer = "List email templates."
  end
  optparse.parse!(args)
  connect(options)
  if args.count > 0
    options[:phrase] = args.join(" ")
  end
  params.merge!(parse_list_options(options))
  @email_templates_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @email_templates.dry.list(params)
    return
  end

  json_response = @email_templates_interface.list(params)
  templates = json_response['emailTemplates']
  render_response(json_response, options, 'templates') do
    title = "Morpheus Email Templates"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles
    if templates.empty?
      print cyan,"No templates found.",reset,"\n"
    else
      print cyan
      print_templates_table(templates, options)
      print_results_pagination(json_response)
    end
    print reset,"\n"
  end
  if templates.empty?
    return 1, "no templates found"
  else
    return 0, nil
  end
end


338
339
340
341
342
343
344
345
346
347
348
349
350
351
# File 'lib/morpheus/cli/commands/email_templates_command.rb', line 338

def print_templates_table(templates, opts={})
  columns = [
    {"ID" => lambda {|it| it['id'] } },
    {"Name" => lambda {|it| it['name'] } },
    {"Owner" => lambda {|it| it['owner']['name'] || 'System'} },
    {"Tenants" => lambda {|it| it['accounts'].collect {|a| a['name'] }.join(', ') rescue it['owner'] ? 'Global' : ''} }

    # {"UPDATED" => lambda {|it| format_local_dt(it['lastUpdated']) } },
  ]
  if opts[:include_fields]
    columns = opts[:include_fields]
  end
  print as_pretty_table(templates, columns, opts)
end

#remove(args) ⇒ Object



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
# File 'lib/morpheus/cli/commands/email_templates_command.rb', line 291

def remove(args)
  options = {}
  query_params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[emailTemplate]")
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :quiet, :remote])
    opts.footer = "Delete an email template.\n" +
                  "[emailTemplate] is required. This is the id of an existing email template.\n" +
                  "Note: You cannot remove System Templates, only those that you own/created."
  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)

  begin
    email_template = find_by_name_or_id('emailTemplate', args[0])

    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to remove the email template '#{email_template['name']}'?", options)
      return 9, "aborted command"
    end
    @email_templates_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @email_templates_interface.dry.destroy(email_template['id'], query_params)
      return
    end
    json_response = @email_templates_interface.destroy(email_template['id'], query_params)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      msg = "Email Template #{email_template['name']} is being removed..."
      if json_response['msg'] != nil && json_response['msg'] != ''
        msg = json_response['msg']
      end
      print_green_success msg
      
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#template_types_for_dropdownObject



363
364
365
# File 'lib/morpheus/cli/commands/email_templates_command.rb', line 363

def template_types_for_dropdown
  get_template_types.collect {|it| {'name' => it['name'], 'code' => it['value'], 'value' => it['value']} }
end

#update(args) ⇒ Object



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
# File 'lib/morpheus/cli/commands/email_templates_command.rb', line 209

def update(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage( "[emailTemplate] --template")
    opts.on("--template TEMPLATE", String, "Updates Email Template") do |val|
      options[:template] = val.to_s
    end
    opts.on('--accounts LIST', Array, "Tenant accounts, comma separated list of account IDs") do |list|
      if list.size == 1 && list[0] == 'null' # hacky way to clear it
        options[:accounts] = []
      else
        options[:accounts] = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end

    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Update an Email Template.\n" +
                  "[emailTemplate] is required. This is the name or id of an existing email template."
  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)

  begin
    payload = nil
    email_template = nil

    if options[:payload]
      payload = options[:payload]
      # support -O OPTION switch on top of --payload
      if options[:options]
        payload['emailTemplate'] ||= {}
        payload['emailTemplate'].deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) })
      end

      if !payload['emailTemplate'].empty?
        email_template = find_by_name_or_id('emailTemplate', payload['emailTemplate']['id'] || payload['emailTemplate']['name'])
      end
    else
      email_template = find_by_name_or_id('emailTemplate', args[0])
      template_payload = {}
      if options[:template]
        template_payload['template'] = options[:template]
      end
      if options[:accounts]
        template_payload['accounts'] = options[:accounts]
      end

      payload = {"emailTemplate" => template_payload}
    end

    if !email_template
      print_red_alert "No templates available for update"
      exit 1
    end

    if payload.empty?
      print_green_success "Nothing to update"
      exit 1
    end

    @email_templates_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @email_templates_interface.dry.update(email_template['id'], payload)
      return
    end
    json_response = @email_templates_interface.update(email_template['id'], payload)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif json_response['success']
      get_args = [json_response["emailTemplate"]["id"]] + (options[:remote] ? ["-r",options[:remote]] : []) + (options[:refresh_interval] ? ['--refresh', options[:refresh_interval].to_s] : [])
      get(get_args)
    else
      print_rest_errors(json_response, options)
    end
  end
end