Project

General

Profile

Download (2.14 KB) Statistics
| Branch: | Tag: | Revision:

hammer-cli-csv / lib / hammer_cli_csv / organizations.rb @ f92e695a

1
module HammerCLICsv
2
  class CsvCommand
3
    class OrganizationsCommand < BaseCommand
4
      command_name 'organizations'
5
      desc         'import or export organizations'
6

    
7
      LABEL = 'Label'
8
      DESCRIPTION = 'Description'
9

    
10
      def export(csv)
11
        csv << [NAME, LABEL, DESCRIPTION]
12

    
13
        @api.resource(:organizations).call(:index, {:per_page => 999999})['results'].each do |organization|
14
          next if option_organization && organization['name'] != option_organization
15
          csv << [organization['name'], organization['label'], organization['description']]
16
        end
17
      end
18

    
19
      def import
20
        @existing = {}
21
        @api.resource(:organizations).call(:index, {:per_page => 999999})['results'].each do |organization|
22
          @existing[organization['name']] = organization['id'] if organization
23
        end
24

    
25
        thread_import do |line|
26
          create_organizations_from_csv(line)
27
        end
28
      end
29

    
30
      def create_organizations_from_csv(line)
31
        count(line[COUNT]).times do |number|
32
          name = namify(line[NAME], number)
33
          return if option_organization && name != option_organization
34
          label = namify(line[LABEL], number)
35
          organization_id = @existing[name]
36
          if organization_id.nil?
37
            print "Creating organization '#{name}'... " if option_verbose?
38
            @api.resource(:organizations).call(:create, {
39
                'name' => name,
40
                'organization' => {
41
                    'name' => name,
42
                    'label' => label,
43
                    'description' => line[DESCRIPTION]
44
                }
45
            })
46
          else
47
            print "Updating organization '#{name}'... " if option_verbose?
48
            organization = @api.resource(:organizations).call(:show, {'id' => organization_id})
49
            @api.resource(:organizations).call(:update, {
50
                'id' => organization_id,
51
                'organization' => {
52
                    'id' => organization_id,
53
                    'description' => line[DESCRIPTION]
54
                }
55
            })
56
          end
57
          print "done\n" if option_verbose?
58
        end
59
      end
60
    end
61
  end
62
end