· 8 years ago · Jun 15, 2018, 06:30 PM
1require 'fastercsv'
2require 'optparse'
3require 'find'
4
5namespace :db do desc "Insert or Update the database with fresh data"
6 task :staff => [:environment] do |t, args|
7 @cols = []
8 @colh = {}
9 @recchk = {}
10 @dep = ''
11 @div = ''
12 @cnm = ''
13 @ccn = ''
14 @objt = Kernel.const_get( "Staff".to_sym )
15
16 cmpcol = File.new("/home/cjay/crap/allstaff.col", "r")
17 cmpimp = File.new("/home/cjay/crap/allstaff", "r")
18
19 # Assemble the columns
20 #
21 while(@line = cmpcol.gets)
22 @cols << @line.chomp
23 @colh[@line.chomp] = (@cols.length - 1)
24 end
25
26 # Gather the id number for each active row
27 #
28 @objt.find_each(:select => "id") do |@dep|
29 @recchk[@dep.id] = false
30 end
31
32 # Iterate through everything and sort through updates
33 #
34 while @line = cmpimp.gets
35 @line = @line.chomp
36 @line = @line.split(/\t/)
37 @cnm = nil
38 @ccn = nil
39 @ccns = nil
40 @div = nil
41 @dep = nil
42
43 if(@line.length != @cols.length)
44 print "Error: Line and Col element count does not match\n"
45 end
46
47 # If the record exists, then update the columns and save it
48 #
49 # Find the parent
50 #
51 @divs = Division.find(:all, :conditions => {:div => @line[@colh["div"]]})
52
53 @divs.each do |dv|
54 if (cc = dv.cost_centers.first(:conditions => {:ccn => @line[@colh["ccn"]]}))
55
56 @ccn = cc
57 @cnm = dv.company_number
58 @div = dv
59 break
60 else
61 @ccn = nil
62 @cnm = dv.company_number
63 @div = dv
64 end
65 end
66
67 if( @div.nil? )
68 @cnm = CompanyNumber.first
69 @div = nil
70 @ccn = nil
71 end
72
73 @staff = @cnm.staffs.first(:conditions => {:employee_id => @line[@colh["employee_id"]]})
74
75 if( !@staff.nil? )
76 @recchk[@staff.id] = true
77
78 @staff.first_name = @line[ @colh["first_name"] ]
79 @staff.last_name = @line[ @colh["last_name"] ]
80 @staff.glitter = @line[ @colh["glitter"] ]
81 @staff.hr_status = @line[ @colh["hr_status"] ]
82 @staff.terminated_on = @line[ @colh["terminated_on"] ]
83 @staff.hr_updated_on = @line[ @colh["hr_updated_on"] ]
84 @staff.email_address = @line[ @colh["email_address"] ]
85
86 if( @ccn.nil? )
87 @staff.cost_center_id = @ccn
88 else
89 @staff.cost_center_id = @ccn.id
90 end
91
92 @staff.save
93
94 # Otherwise, create a new copy of the record
95 #
96 else
97 @staff = @cnm.staffs.build( :cost_center => @ccn ,
98 :employee_id => @line[ @colh["employee_id"] ],
99 :first_name => @line[ @colh["first_name"] ],
100 :last_name => @line[ @colh["last_name"] ],
101 :glitter => @line[ @colh["glitter"] ],
102 :hr_status => @line[ @colh["hr_status"] ],
103 :terminated_on => @line[ @colh["terminated_on"] ],
104 :hr_updated_on => @line[ @colh["hr_updated_on"] ],
105 :email_address => @line[ @colh["email_address"] ])
106 @staff.save
107 end
108 end
109
110 # Delete rows that can't be found
111 #
112 @recchk.each do |key, value|
113 if value == true
114 next
115 end
116
117 print "key not found in table: #{key}\n"
118
119
120 @objt.destroy(key)
121 end
122 end
123end