· 8 years ago · May 26, 2018, 12:44 AM
1require 'rubygems'
2gem 'soap4r'
3require 'xsd/qname'
4require 'soap/wsdlDriver'
5require 'soap/header/simplehandler'
6require 'rexml/document'
7require 'lib/custom_simple_header'
8
9class CustomSimpleHeader < SOAP::Header::SimpleHandler
10 def initialize(itemname,namespace,childdata)
11 super(XSD::QName.new(namespace,itemname))
12
13 @mustunderstand = nil
14
15 case childdata
16 when Hash
17 xml_hash = {}
18 childdata.each_pair { |key,value|
19 element = XSD::QName.new(namespace, key)
20 xml_hash[element] = value
21 }
22 puts xml_hash
23 @item = xml_hash
24 else
25 @item = childdata.to_s
26 end
27 end
28
29 def on_simple_outbound
30 @item if @item
31 end
32end
33
34class InstallationsController < ApplicationController
35 helper :sort
36 include SortHelper
37 include InvertersHelper
38 layout :determine_layout
39 before_filter :login_required, :except => [:add_inverter, :remove_inverter, :auto_complete_for_company_name, :update_company_attributes]
40 permit "installer or admin or oem", :redirect_controller => 'installations', :redirect_action => 'list'
41
42 #auto_complete_for :user, :first_name
43 def auto_complete_for_company_name
44 @companies = Company.find(:all, :conditions => ['LOWER(name) LIKE ?', '%' + params[:company][:name].downcase + '%' ], :limit => 10, :order => 'LOWER(name)')
45 render :partial => 'installations/companies'
46 end
47
48 def update_company_attributes
49 @company = Company.find_by_name(params[:selected_company_name])
50 @company ? render(:partial => 'installations/company_address') : render(:nothing => true)
51 end
52
53 def list_all
54 session[:list_all] = true
55 redirect_to :action => 'list'
56 end
57
58 def list_reporting
59 session[:list_all] = false
60 redirect_to :action => 'list'
61 end
62
63 #list all the installations out there
64 def list
65 @title = "My Installations List"
66
67 # Set up the conditions statement
68 session[:user].kind_of?(Installer) ? conditions = "installations.installation_company_id = " + session[:user].company.id.to_s : conditions = ""
69 if !session[:list_all]
70 if (serials = DataSlot.safe_serials).size > 0
71 conditions += " AND " if !conditions.empty?
72 conditions += "data_slots.serial_number in ('#{serials.join("','")}')"
73 end
74 end
75
76 # Now load the installations
77 unless conditions.empty?
78 if current_user.has_role? 'OEM'
79 slots = DataSlot.find(:all, :conditions => ['oem_id = ?', current_user.company_id] )
80 @installations = []
81 for slot in slots
82 if slot.installation
83 unless @installations.include?(Installation.find(slot.installation_id))
84 @installations << Installation.find(slot.installation_id)
85 end
86 end
87 end
88 else
89
90 @installations = Installation.find(:all, :include => [:users, :location, :data_slots])
91# @installation_pages, @installations = paginate(:installations, {
92# :conditions => conditions,
93# :include => [:homeowner, :location, :data_slots],
94# :order => 'users.last_name',
95# :per_page => 25})
96 end
97 else
98 @installations = Installation.find(:all, :include => [:users, :location, :data_slots])
99# @installation_pages, @installations = paginate(:installations, {
100# :include => [:users, :location, :data_slots],
101# :order => 'users.last_name, users.first_name',
102# :per_page => 25})
103 end
104
105 @installations.sort! { |installation_a, installation_b|
106 users_a = installation_a.homeowners.find(:all, :order => 'last_name, first_name')
107 users_b = installation_b.homeowners.find(:all, :order => 'last_name, first_name')
108 if (users_a.nil? or users_a.empty?) and (users_b.nil? or users_b.empty?)
109 0
110 elsif users_a.nil? or users_a.empty?
111 -1
112 elsif users_b.nil? or users_b.empty?
113 1
114 else
115 users_a[0].last_name <=> users_b[0].last_name
116 end
117 }
118 @installation_pages, @installations = paginate_collection @installations, {:per_page => 25, :page => params[:page]}
119 @page = params[:page].nil? ? 1 : params[:page]
120 end
121
122 #Return a detailed view of a single installation
123 def show
124 @title = "My Installation Detail"
125 @installation = Installation.find(params[:id], :include => [:location, :users, :data_slots])
126 homeowner = @installation.homeowners.find(:first)
127 homeowner.graph_preference = session[:user].graph_preference if homeowner
128 session[:homeowner] = homeowner
129 session[:installation] = @installation
130 @page = params[:page].nil? ? 1 : params[:page]
131 @page = params[:page].nil? ? 1 : params[:page]
132 end
133
134 # I commented out the old new action and will be slowly migrating relevant actions from installation registration
135 # over to this controller, where they should belong. 2/12/08
136 def new
137 @using_calendar = true
138 if current_user.has_role? 'Installer'
139 company = current_user.company
140 else
141 @company_list = Array.new
142 companies = Company.find(:all)
143 for company in companies
144 for type in company.company_types
145 if type.type_name == 'Installer'
146 @company_list << company
147 end
148 end
149 end
150 company = @company_list.first
151 end
152 @installers = company.users.find(:all, :conditions => "type = 'Installer'", :order => 'first_name')
153 @installation = Installation.new
154 @installation.build_location
155 data_slot = DataSlot.new
156 @data_slots = [data_slot]
157 @installation.data_slots = [data_slot]
158 @monitoring_apis = MonitoringApi.find(:all)
159 end
160
161 def choose_company
162 c = Company.find(params[:company])
163 @installers = c.users.find(:all, :conditions => "type = 'Installer'")
164 render :layout => false
165 end
166
167 # Methods for my ajax calls
168 def get_phone
169 selected_user = User.find(params[:user_id])
170 @phone_number = selected_user.phone_readable
171 render :layout => false
172 end
173
174 def phone_observer
175 @phone_variable = (params[:sms])
176 render :layout => false
177 end
178 # End ajax call methods
179
180 def create
181 # if there are errors and we need to render the action, we also need these variables to reload the form.
182 @page = params[:page].nil? ? 1 : params[:page]
183 @using_calendar = true
184 if current_user.has_role? 'Installer'
185 company = current_user.company
186 else
187 @company_list = Array.new
188 companies = Company.find(:all)
189 for company in companies
190 for type in company.company_types
191 if type.type_name == 'Installer'
192 @company_list << company
193 end
194 end
195 end
196 company = @company_list.first
197 end
198 @installers = company.users.find(:all, :conditions => "type = 'Installer'", :order => 'first_name')
199 @monitoring_apis = MonitoringApi.find(:all)
200
201 # this slices up the phone number. this should be moved somewhere else, but for now its home is here.
202 p = params[:sms]
203 if p[3,1] == "-"
204 p.slice!(3)
205 end
206 if p[6,1] == "-"
207 p.slice!(6)
208 end
209
210 # make new SmsMessage if someone entered a phone number for a text-message
211 unless p.nil?
212 @sms = SmsMessage.new
213 @sms.phone = p
214 end
215
216 # make new Installation, Location, and DataSlots
217 @installation = Installation.new(params[:installation])
218 @installation.data_slots = []
219 @location = @installation.location
220 @installation.errors.clear
221 errors = false
222 if @installation.valid?
223 starting_status = Status.find(1)
224 @installation.status = starting_status
225 @user_params = params[:user]
226 # My :user params are coming back as an array. It's fucktarded, i know, but i don't have time to fix it right now.
227 for installer in @user_params
228 @installation_user = User.find(installer)
229 @installation_company = @installation_user.company
230 @installation.company = @installation_company
231 end
232 else
233 errors = true
234 end
235 if params[:inverter]
236 params[:inverter].each_pair { |key, value|
237 #Chop off the letters on the prefix of the serial
238 check_serial = value[:serial_number].gsub(/^[a-zA-Z]*/, '')
239 #check_serial = value[:serial_number].gsub(/\D/, '')
240 #Check to see if there is a data_pool with that serial number. if so, check to see if that data_pool has a data_slot and set
241 #the data_slot variable to the existing data_slot. Otherwise, create a new data_slot.
242 if DataPool.find_by_serial_number(check_serial)
243 found_pool = DataPool.find_by_serial_number(check_serial)
244 if found_pool.data_slot
245 data_slot = found_pool.data_slot
246 else
247 data_slot = DataSlot.new(value)
248 end
249 else
250 data_slot = DataSlot.new(value)
251 end
252 #=-=-=-=-=-=-=-=-=-=-=-=
253 #unless DataPool.find_by_serial_number(check_serial)
254 # data_slot = DataSlot.new(value)
255 #end
256 if !data_slot.valid?
257 errorMsg = "The inverter you submitted with a serial number of #{value[:serial_number]} had the following problems. <br/>"
258 data_slot.errors.each_full { |msg| errorMsg.concat(msg + "<br/>")}
259 @installation.errors.add_to_base(errorMsg)
260 errors = true
261 end
262 # Associate the data slot to the installation unless the data slot is already in use
263 unless DataSlot.find_by_serial_number(value[:serial_number])
264 @installation.data_slots << data_slot
265 # give the data_slot an OEM if if one exists
266 if current_user.has_role? 'Installer'
267 serial = value[:serial_number]
268 serial = serial[0, 2]
269 oem = Oem.find_by_code(serial)
270 if oem
271 data_slot.oem = oem
272 end
273 end
274 end
275 }
276 else
277 errors = true
278 @installation.errors.add_to_base("To register you must have at least one inverter specified.")
279 end
280 if errors
281 @data_slots = @installation.data_slots
282 render :action => 'new'
283 else
284 @installation.save
285 # Associate SMS message and user to the installation
286 unless p.nil?
287 @installation.sms_messages << @sms
288 end
289 @installation.users << @installation_user
290
291 flash_message = ""
292 if params[:monitoring_api]
293 monitored_data_config = {}
294 mapi_hash = params[:monitoring_api]
295 mapi_hash.each { |key,value|
296 imapi = InstallationMonitoringApi.find(:first, :conditions => ['monitoring_api_id = ? and installation_id = ?', key, @installation])
297 if imapi.nil?
298 imapi = InstallationMonitoringApi.new
299 imapi.monitoring_api_id = key
300 imapi.installation_id = @installation
301 end
302 imapi.active = value
303
304 # If API is enabled, for each inverter, send an AMD to API
305 if value.to_i
306 @installation.data_slots.each { |slot|
307
308 mapi = MonitoringApi.find(:first, :conditions => ['id = ? and config_name is not null', imapi.monitoring_api_id])
309 next if mapi.nil?
310
311 mapi_name = mapi.config_name
312 monitored_data_config[mapi_name] = YAML.load_file(File.join(RAILS_ROOT, 'config', 'monitored_data.yml'))[mapi_name] if monitored_data_config.nil? or monitored_data_config[mapi_name].nil? or monitored_data_config[mapi_name].empty?
313 next if monitored_data_config[mapi_name].nil? or monitored_data_config[mapi_name].empty?
314 next if monitored_data_config[mapi_name]['class'].nil?
315
316 mapi_obj = eval(monitored_data_config[mapi_name]['class'] + ".new(monitored_data_config[mapi_name], mapi.id)")
317
318 # Deliver message and handle exceptions
319 begin
320
321 logger_id = ""
322 mac_address = slot.data_pool.mac_address
323 if mac_address.match(':')
324 logger_id = slot.data_pool.mac_address
325 else
326 position = 1
327 mac_address.each_char { |c|
328 logger_id.concat(c)
329 logger_id.concat(":") if position % 2 == 0
330 position += 1
331 }
332 logger_id.chop!
333 end
334 device_id = slot.serial_number
335 model_number = slot.data_pool.inverter_model.model_number
336 monitored_data = MonitoredData.new(logger_id, device_id, model_number)
337 monitored_data_channels = {
338 "acCurrent" => 0,
339 "acVoltage" => 0,
340 "dcVoltage" => 0,
341 "acPower" => 0,
342 "acTotalEnergy" => 0
343 }
344
345 monitored_data_status = {}
346 monitored_data.add_poll(Time.now.to_i, monitored_data_channels, monitored_data_status)
347 monitored_data.namespace = monitored_data_config[mapi_name]['namespace']
348 #mapi_obj.deliver!(@monitored_data, logger, false, true)
349 mapi_obj.load_and_deliver!(Marshal.dump(monitored_data), logger, false, true)
350 rescue MonitoredDataLoginErrorException
351 flash_message += "Inverter (#{device_id}) failed to verify data monitoring availability for #{mapi.name}. "
352 logger.info("Inverter device_id=\"#{device_id}\" model_number=\"#{model_number}\" logger_id=\"#{logger_id}\" failed to verify data monitoring availability (MonitoredDataLoginErrorException) for #{mapi.name}")
353 rescue MonitoredDataAddMonitoredDataErrorException
354 flash_message += "Inverter (#{device_id}) failed to verify data monitoring availability for #{mapi.name}. "
355 logger.info("Inverter device_id=\"#{device_id}\" model_number=\"#{model_number}\" logger_id=\"#{logger_id}\" failed to verify data monitoring availability (MonitoredDataAddMonitoredDataErrorException) for #{mapi.name}")
356 rescue MonitoredDataRecordErrorException
357 flash_message += "Inverter (#{device_id}) needs to be registered with #{monitored_data_config[mapi_name]['registration_url']}. "
358 logger.info("Inverter device_id=\"#{device_id}\" model_number=\"#{model_number}\" logger_id=\"#{logger_id}\" is not registered with #{monitored_data_config[mapi_name]['registration_url']}.")
359 end
360 }
361 end
362
363 imapi.save
364 }
365 end
366
367 flash[:notice] = "Installation schedule has been successful. " + flash_message
368 redirect_to :controller => 'installations', :action => 'list'
369 end
370 end
371
372 def edit
373 @title = "My Edit Installation"
374 @page = params[:page].nil? ? 1 : params[:page]
375 @installation = Installation.find(params[:id], :include => [:location, :company])
376 @location = @installation.location
377 @company = @installation.company
378 @installations_monitoring_apis = InstallationMonitoringApi.find(:all, :conditions => ['installation_id = ?', params[:id]])
379 unless @installation.homeowners.empty?
380 @user = session[:homeowner] = @installation.homeowners.find(:first)
381 else
382 #@user = []
383 homeowner = Homeowner.new
384 session[:homeowners] = homeowner
385 @user = homeowner
386 end
387 @data_slots = @installation.data_slots
388
389# if @installation.homeowner
390# @user = session[:homeowner] = @installation.homeowner
391# else
392# homeowner = Homeowner.new
393# homeowner.installation = @installation
394# @user = session[:homeowner] = homeowner
395# end
396# @data_slots = @user.installation.data_slots
397
398 end
399
400 #
401 # Update the installation with the company name, location values, and inverters if available
402 # TODO implement all inside a single transaction block
403 #
404 def update
405 @page = params[:page].nil? ? 1 : params[:page]
406 @installation = Installation.find(params[:id])
407 @installation.attributes = params[:installation]
408 params[:inverter].each { |key, value|
409 slot = DataSlot.find(value[:id])
410 slot.update_attributes(value)
411 } unless params[:inverter].nil?
412 params[:data_slots].each { |key, value|
413 slot = DataSlot.find(key)
414 slot.update_attributes(value)
415 } unless params[:data_slots].nil?
416 # since scheduled_for is required for validations if there is no scheduled_for date, i'm setting it to today.
417 if !@installation.scheduled_for
418 @installation.scheduled_for = Time.now
419 end
420 # end scheduled_for hack
421 @company = @installation.company = Company.find_by_name(params[:company][:name])
422 @location = find_location(@installation)
423 if @installation.company
424 @installation.company.save
425 end
426 @location.attributes = params[:location]
427 @location.installation = @installation if @location.new_record?
428 update_installation_data_slots(@installation, params[:inverter]) unless params[:inverter].nil?
429
430 flash_message = ""
431 if params[:installation_monitoring_api]
432
433 monitored_data_config = {}
434 imapi_hash = params[:installation_monitoring_api]
435 imapi_hash.each { |key,value|
436 imapi = InstallationMonitoringApi.find(:first, :conditions => ['monitoring_api_id = ? and installation_id = ?', key, params[:id]])
437 imapi.active = value
438
439 # If API is enabled, for each inverter, send an AMD to API
440 if value.to_i
441 @installation.data_slots.each { |slot|
442
443 mapi = MonitoringApi.find(:first, :conditions => ['id = ? and config_name is not null', imapi.monitoring_api_id])
444 next if mapi.nil?
445
446 mapi_name = mapi.config_name
447 monitored_data_config[mapi_name] = YAML.load_file(File.join(RAILS_ROOT, 'config', 'monitored_data.yml'))[mapi_name] if monitored_data_config.nil? or monitored_data_config[mapi_name].nil? or monitored_data_config[mapi_name].empty?
448 next if monitored_data_config[mapi_name].nil? or monitored_data_config[mapi_name].nil? or monitored_data_config[mapi_name].empty?
449 next if monitored_data_config[mapi_name]['class'].nil?
450
451 mapi_obj = eval(monitored_data_config[mapi_name]['class'] + ".new(monitored_data_config[mapi_name], mapi.id)")
452
453 # Deliver message and handle exceptions
454 begin
455
456 logger_id = ""
457 mac_address = slot.data_pool.mac_address
458 if mac_address.match(':')
459 logger_id = slot.data_pool.mac_address
460 else
461 position = 1
462 mac_address.each_char { |c|
463 logger_id.concat(c)
464 logger_id.concat(":") if position % 2 == 0
465 position += 1
466 }
467 logger_id.chop!
468 end
469 device_id = slot.serial_number
470 model_number = slot.data_pool.inverter_model.model_number
471 monitored_data = MonitoredData.new(logger_id, device_id, model_number)
472 monitored_data_channels = {
473 "acCurrent" => 0,
474 "acVoltage" => 0,
475 "dcVoltage" => 0,
476 "acPower" => 0,
477 "acTotalEnergy" => 0
478 }
479
480 monitored_data_status = {}
481 monitored_data.add_poll(Time.now.to_i, monitored_data_channels, monitored_data_status)
482 monitored_data.namespace = monitored_data_config[mapi_name]['namespace']
483 #mapi_obj.deliver!(@monitored_data, logger, false, true)
484 mapi_obj.load_and_deliver!(Marshal.dump(monitored_data), logger, false, true)
485 rescue MonitoredDataLoginErrorException
486 flash_message += "Inverter (#{device_id}) failed to verify data monitoring availability for #{mapi.name}. "
487 logger.info("Inverter device_id=\"#{device_id}\" model_number=\"#{model_number}\" logger_id=\"#{logger_id}\" failed to verify data monitoring availability (MonitoredDataLoginErrorException) for #{mapi.name}")
488 rescue MonitoredDataAddMonitoredDataErrorException
489 flash_message += "Inverter (#{device_id}) failed to verify data monitoring availability for #{mapi.name}. "
490 logger.info("Inverter device_id=\"#{device_id}\" model_number=\"#{model_number}\" logger_id=\"#{logger_id}\" failed to verify data monitoring availability (MonitoredDataAddMonitoredDataErrorException) for #{mapi.name}")
491 rescue MonitoredDataRecordErrorException
492 flash_message += "Inverter (#{device_id}) needs to be registered with #{monitored_data_config[mapi_name]['registration_url']}. "
493 logger.info("Inverter device_id=\"#{device_id}\" model_number=\"#{model_number}\" logger_id=\"#{logger_id}\" is not registered with #{monitored_data_config[mapi_name]['registration_url']}.")
494 end
495 }
496 end
497
498 imapi.save
499 }
500 end
501
502 if @installation.errors.empty? && @installation.save && @location.save
503 session[:homeowner] = nil
504 flash[:notice] = 'Installation was successfully updated. ' + flash_message
505 redirect_to :action => 'list'
506 else
507 @user = session[:homeowner]
508 flash[:notice] = flash_message unless flash_message.empty?
509 render :action => 'edit'
510 end
511 end
512
513 def link
514 @slot = DataSlot.find(params[:id])
515 end
516
517 def link_update
518 end
519 # Note we call location.destroy here instead of installation.destroy
520 # because of the way that the has_one and belongs_to relationships are wired. Rails
521 # needs to have the belongs_to keyword on the object whose table has the foreign key
522 # relationship (in this case the installation "belongs_to" the location because the
523 # installations table has a foreign key location_id. In effect, the InstallationLocation
524 # is the 'parent' table even though the object relationship can be thought of differently
525 # If there is no installation location, we just call destroy on the @installation instance
526 # method updated on 3/24/06 to access via AJAX call to secure actions behind post
527 def destroy
528 @installation = Installation.find(params[:id])
529 if @installation.location
530 @installation.location.destroy
531 @installation.destroy
532 else
533 @installation.destroy
534 end
535 redirect_to :back
536
537 end
538
539 def add_inverter
540 @installation = Installation.find(params[:id])
541 @installation.errors.clear
542 if request.post?
543 # ALWAYS REMEMBER TO USE THE '?' BIND FUNCTION AS BELOW TO SUBVERT SQL
544 # INJECTION ATTACKS!
545 serial = params[:inverter_serial]
546 @dataslot = DataSlot.find(:all,
547 :conditions => ["serial_number = ?", serial])
548
549 # In most cases the serial_number field inside data_slot will be nil
550 # this means we need to hinge off of the pvm serial number
551
552 if @dataslot.empty?
553 @dataslot = DataSlot.find_reclaimable_data_slots(serial)
554 end
555
556 flash_message = ""
557
558 #Check if we found anything
559 if !@dataslot
560 flash[:error] = "We couldn't find an inverter with that serial.
561 Make sure you entered the serial correctly and that the inverter is plugged in."
562 logger.info("Couldn't find an inverter with the serial #{serial}")
563 else
564 # The code now automatically creates an installation if one doesn't
565 # exist
566 for slot in @dataslot
567 slot.serial_number = serial
568 slot.nickname = '' if slot.nickname.nil?
569
570 #Go through the 4 possible combos of installations
571 if slot.installation
572 flash[:error] = "That inverter is already associated to an installation."
573 logger.info("Inverter #{serial} is already associated to an installation")
574 else
575 slot.installation = @installation
576 slot.save
577
578 unless @installation.monitoring_apis.nil? or @installation.monitoring_apis.empty?
579
580 # Process message thru each API
581 monitored_data_config = {}
582 imapis = InstallationMonitoringApi.find(:all, :conditions => ['installation_id = ? and active = ?', @installation.id, true])
583 imapis.each { |imapi|
584
585 mapi = MonitoringApi.find(:first, :conditions => ['id = ? and config_name is not null', imapi.monitoring_api_id])
586 next if mapi.nil?
587
588 mapi_name = mapi.config_name
589 monitored_data_config[mapi_name] = YAML.load_file(File.join(RAILS_ROOT, 'config', 'monitored_data.yml'))[mapi_name] if monitored_data_config.nil? or monitored_data_config[mapi_name].nil? or monitored_data_config[mapi_name].empty?
590 next if monitored_data_config[mapi_name].nil? or monitored_data_config[mapi_name].empty?
591 next if monitored_data_config[mapi_name]['class'].nil?
592
593 mapi_obj = eval(monitored_data_config[mapi_name]['class'] + ".new(monitored_data_config[mapi_name], mapi.id)")
594
595 # Deliver message and handle exceptions
596 begin
597
598 logger_id = ""
599 mac_address = slot.data_pool.mac_address
600 if mac_address.match(':')
601 logger_id = slot.data_pool.mac_address
602 else
603 position = 1
604 mac_address.each_char { |c|
605 logger_id.concat(c)
606 logger_id.concat(":") if position % 2 == 0
607 position += 1
608 }
609 logger_id.chop!
610 end
611 device_id = slot.serial_number
612 model_number = slot.data_pool.inverter_model.model_number
613 monitored_data = MonitoredData.new(logger_id, device_id, model_number)
614 monitored_data_channels = {
615 "acCurrent" => 0,
616 "acVoltage" => 0,
617 "dcVoltage" => 0,
618 "acPower" => 0,
619 "acTotalEnergy" => 0
620 }
621 monitored_data_status = {}
622 monitored_data.add_poll(Time.now.to_i, monitored_data_channels, monitored_data_status)
623 monitored_data.namespace = monitored_data_config[mapi_name]['namespace']
624 #mapi_obj.deliver!(@monitored_data, logger, false, true)
625 mapi_obj.load_and_deliver!(Marshal.dump(monitored_data), logger, false, true)
626 rescue MonitoredDataLoginErrorException
627 flash_message += "Inverter (#{device_id}) failed to verify data monitoring availability for #{mapi.name}. "
628 logger.info("Inverter device_id=\"#{device_id}\" model_number=\"#{model_number}\" logger_id=\"#{logger_id}\" failed to verify data monitoring availability (MonitoredDataLoginErrorException) for #{mapi.name}")
629 rescue MonitoredDataAddMonitoredDataErrorException
630 flash_message += "Inverter (#{device_id}) failed to verify data monitoring availability for #{mapi.name}. "
631 logger.info("Inverter device_id=\"#{device_id}\" model_number=\"#{model_number}\" logger_id=\"#{logger_id}\" failed to verify data monitoring availability (MonitoredDataAddMonitoredDataErrorException) for #{mapi.name}")
632 rescue MonitoredDataRecordErrorException
633 flash_message += "Inverter (#{device_id}) needs to be registered with #{monitored_data_config[mapi_name]['registration_url']}. "
634 logger.info("Inverter device_id=\"#{device_id}\" model_number=\"#{model_number}\" logger_id=\"#{logger_id}\" is not registered with #{monitored_data_config[mapi_name]['registration_url']}.")
635 end
636
637 imapi.save
638 }
639 else
640 logger.info("Inverter #{serial} has been associated to the installation")
641 end
642 flash[:notice] = "The inverter (#{serial}) has been added to your installation. " + flash_message
643 end
644 end
645
646
647 #Move onto the next stage of the reg if there wasn't an error
648 if !flash[:error]
649 #Update my installations if there was a change made
650 @dataslot.each { |slot| slot.save } if @change
651 redirect_to :action => 'edit', :id => @installation
652 end
653 end
654 end
655 end
656
657 def remove_inverter
658 @data_slot = DataSlot.find(params[:id])
659 @installation = @data_slot.installation.id
660 @data_slot.installation = nil
661 @data_slot.save
662 flash[:notice] = "You have removed an inverter from your installation"
663 redirect_to :action => 'edit', :id => @installation
664 end
665
666 #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
667 # Add a new inverter via AJAX call
668=begin def add_inverter
669 if request.method == :post
670 @user = current_user
671
672 @data_slot = DataSlot.new
673 render(:partial => "installations/data_slot", :object => @data_slot,
674 :layout => false)
675 else
676 flash[:notice] = "Inverter not added"
677 redirect_to :controller => 'homeowner', :action => 'index'
678 end
679 end
680
681 # Remove an inverter via AJAX call
682 def remove_inverter
683 if request.method == :post
684 if params[:persistent]
685 @data_slot = DataSlot.find(params[:id])
686 @data_slot.installation_id = nil
687 @data_slot.save
688# @data_slot.destroy
689# session[:homeowner].installation.inverters.delete(@data_slot)
690 end
691 render(:nothing => true)
692 else
693 flash[:notice] = "Inverter not found"
694 redirect_to :action => 'index'
695 end
696 end
697=end
698 def show_energy
699 if params[:installation]
700 session[:installation] = Installation.find_by_id(params[:installation])
701 @homeowner = session[:installation].homeowners.find(:first)
702 else
703 @homeowner = session[:homeowner]
704 session[:installation] = Installation.find_by_id(params[:installation])
705 end
706 #HACK: calling for data slots directly
707 #@data_slot = @homeowner.installation.find_data_slot_by_id(params[:id])
708 @data_slot = DataSlot.find_by_id(params[:id])
709 refresh_graph_for_data_slot(@data_slot)
710 session[:user].current_data_slot = params[:id]
711 render :template => 'homeowner/energy', :layout => 'simple'
712 end
713
714 #Return a sorted list of all the currently inverters
715 def reporting
716 @timezone = TZInfo::Timezone.new("America/Los_Angeles")
717 sort_init('data_slots.updated_on', 'desc')
718 sort_update
719 # This code block will determine the user role. if it is OEM then we have to get the data slots a different way
720 # so we just show the OEM's data slots and not everybody's data slots. This is not a good way to do it, though.
721 if current_user.has_role? 'Admin'
722 @dataslots = DataSlot.find(:all)
723 @slots = []
724 for slot in @dataslots
725 if slot.data_pool
726 @slots << slot
727 end
728 end
729 elsif current_user.has_role? 'OEM'
730 @slots = []
731 oem_company = current_user.company_id
732 @dataslots = DataSlot.find(:all, :conditions => "oem_id = #{oem_company}")
733 # installations = Installation.find(:all, :conditions => "installation_company_id = '#{current_user.company_id}'")
734 for slot in @dataslots
735 if slot.data_pool
736 @slots << slot
737 end
738 end
739 end
740 # end user role determination
741 if params[:sort_key] == 'state'
742 @slots.sort! { |b,a| a.safe_state <=> b.safe_state }
743 elsif params[:sort_key] == 'ip_address'
744 @slots.sort! { |b,a| a.safe_ip_address <=> b.safe_ip_address }
745 elsif params[:sort_key] == 'mac_address'
746 @slots.sort! { |b,a| a.safe_mac_address <=> b.safe_mac_address }
747 elsif params[:sort_key] == 'serial_number'
748 @slots.sort! { |b,a| a.safe_serial <=> b.safe_serial }
749 else
750 #elsif params[:sort_key] == 'updated_on'
751 @slots.sort! { |b,a| a.updated_on <=> b.updated_on }
752 end
753 end
754
755 def search_by_homeowner
756 homeowners = User.search(params[:homeowner][:name], :conditions => "type = 'Homeowner'")
757 if homeowners.size > 0
758 ids = []
759 homeowners.each { |h| ids << h.id }
760 @installations = Installation.find_all_by_homeowner_id(ids)
761 restrict_installations(@installations) if current_user.kind_of?(Installer)
762 else
763 @installations = []
764 end
765 @installation_pages = Paginator.new(self, @installations.size, 10, params[:page])
766 render :action => 'list'
767 end
768
769 def search_by_location
770 locations = Location.search(params[:location][:name])
771 if locations.size > 0
772 ids = []
773 locations.each { |l| ids << l.id }
774 @installations = Installation.find_all_by_location_id(ids)
775 restrict_installations(@installations) if current_user.kind_of?(Installer)
776 else
777 @installations = []
778 end
779 @installation_pages = Paginator.new(self, @installations.size, 10, params[:page])
780 render :action => 'list'
781 end
782
783 def login_as_user
784 return unless request.post? && current_user.kind_of?(Admin)
785 login = current_user.login
786 reset_session
787 session[:old_admin_login] = login
788 session[:was_an_administrator] = true
789 session[:homeowner] = session[:user] = Homeowner.find(params[:id])
790 check_redirect
791 end
792
793 #Show a summary of installations by installer
794 def summary
795 if current_user.has_role? 'admin' or 'oem'
796 @company_list = Array.new
797 companies = Company.find(:all)
798 for company in companies
799 for type in company.company_types
800 if type.type_name == 'Installer'
801 @company_list << company
802 end
803 end
804 end
805 company = @company_list.first
806 elsif current_user.has_role? 'installer'
807 company = current_user.company
808 end
809 @selected_time = params[:selected_time]
810 if !params[:selected_user].nil?
811 @selected_user = User.find(params[:selected_user])
812
813 end
814 if @selected_time.nil?
815 @selected_time = Time.now.to_date.to_s(:db)
816 @readable_time = @selected_time.to_time.to_date.to_s(:long)
817 @timeframe = "scheduled_for = '#{Time.now.to_date.to_s(:db)}'"
818 else
819 @selected_time = params[:selected_time]
820 @time2 = Time.now
821 case @selected_time
822 when "tomorrow"
823 @timeframe = "scheduled_for = '#{1.day.from_now.to_date.to_s(:db)}'"
824 @readable_time = @time2.to_time.advance(:days => 1).to_date.to_s(:long)
825 when "next 7 days"
826 @timeframe = "scheduled_for <= '#{ @time2.to_time.advance(:days => 7).to_s(:db)}' and scheduled_for >= '#{ Time.now.to_time.yesterday.to_s(:db)}'"
827 @readable_time = @time2.to_time.to_date.to_s(:long) + " to " + @time2.to_time.advance(:days => 7).to_date.to_s(:long)
828 when "next 30 days"
829 @timeframe = "scheduled_for <= '#{ @time2.advance(:days => 30).to_s(:db)}' and scheduled_for >= '#{ Time.now.to_time.yesterday.to_s(:db)}'"
830 @readable_time = @time2.to_time.to_date.to_s(:long) + " to " + @time2.to_time.tomorrow.advance(:days => 30).to_date.to_s(:long)
831 end
832 end
833 @installers = User.find(:all, :conditions => "company_id = #{company.id} and type = 'Installer'", :order => 'first_name')
834 if !@selected_user.nil?
835 @installations = @selected_user.installations.find(:all, :conditions => "#{@timeframe} and status_id = 1")
836 end
837 @installation_date = "-"
838 @installation_builder = "-"
839 @installation_development = "-"
840 if params[:classic] == '1'
841 sort_init('scheduled_for', 'asc')
842 sort_update
843 @installations = Installation.find(:all, :conditions => "#{@timeframe} and status_id = 1", :order => sort_clause)
844 render :action => 'classic_summary'
845 end
846 end
847
848 def choose_company
849 c = Company.find(params[:company])
850 @installers = c.users.find(:all, :conditions => "type = 'Installer'")
851 render :layout => false
852 end
853
854 def classic_summary
855 company = current_user.company.id
856 @selected_user = params[:selected_user]
857
858 sort_init('builder', 'desc')
859 sort_update
860 @installations = Installation.find(:all, :include => [:location, :users, :data_slots], :conditions => "status_id = 1 and scheduled_for >= '#{Time.now.to_s(:db)}'", :order => sort_clause)
861 end
862
863 def movie
864 render :layout => false
865 end
866
867 private
868
869 def find_location(installation)
870 installation.location ||= InstallationLocation.new
871 end
872
873 def restrict_installations(installations)
874 installations.delete_if { |i| i.company_id != session[:user].company.id }
875 end
876end