-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathemail_addresses_controller.rb
More file actions
57 lines (48 loc) · 2.02 KB
/
email_addresses_controller.rb
File metadata and controls
57 lines (48 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
# frozen_string_literal: true
class EmailAddressesController < ApplicationController
before_action :require_login
before_action :set_teacher
before_action :require_email_edit_permission
def create
email = params[:email].to_s.strip
if email.blank?
redirect_to teacher_path(@teacher), alert: "No email provided."
return
end
@teacher.email_addresses.create!(email:, primary: false)
# Sync teacher to MailBluster when a new email is added
MailblusterService.create_or_update_lead(@teacher) if MailblusterService.configured? && @teacher.validated?
redirect_to teacher_path(@teacher), notice: "Personal email addresses added successfully."
rescue ActiveRecord::RecordInvalid => e
error_message = e.record&.errors&.full_messages&.join(", ")
error_message ||= "A validation error occurred."
redirect_to teacher_path(@teacher), alert: error_message
end
def destroy
email = EmailAddress.find(params[:id])
if email.teacher_id != @teacher.id
redirect_to teacher_path(@teacher), alert: "Email address not found."
return
end
if @teacher.email_addresses.count <= 1
redirect_to teacher_path(@teacher), alert: "Add another email before deleting this one."
return
end
email.destroy!
# Re-sync to MailBluster since email list changed
MailblusterService.create_or_update_lead(@teacher) if MailblusterService.configured? && @teacher.validated?
redirect_to teacher_path(@teacher), notice: "Email address deleted successfully."
rescue ActiveRecord::RecordNotFound
redirect_to teacher_path(@teacher), alert: "Email address not found."
rescue ActiveRecord::RecordNotDestroyed
redirect_to teacher_path(@teacher), alert: "Could not delete email address."
end
private
def set_teacher
@teacher = Teacher.find(params[:teacher_id])
end
def require_email_edit_permission
return if is_admin? || current_user.id == @teacher.id
redirect_to edit_teacher_path(current_user.id), alert: "You can only edit your own information"
end
end