Skip to content

Commit 94cb86d

Browse files
amcheerssean-dickinsonclaude
authored
Admin csv import (#120)
* Adds new route and controller for csv template. Successfully downloads template with correct headers when endpoint is hit. * Adds route, controller, and service to implement CSV upload and resource creation ability. Adds csv gem. * WIP, moves error message hash and resource arrays to instance variables, wraps persistence of resources in a transaction block, refactors errors to inherit from ActiveRecord::Rollback. * WIP Successfully imported test csv, extracted records, created and associated records. Needs cleanup and refactoring. * (WIP) Refactors StudentCsvImporter service, still needs route update, tests, and view. * Adds fixtures and tests around Csv controller, and import service. * Refactors controller and import service, updates route to include school_id as a param. * fix: require existing program in student CSV import Unknown programs now raise InvalidProgramError and surface as an import alert instead of creating a Program. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * refactor: define CSV routes without module scope Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * chore: remove unrelated tool-versions and lockfile changes Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * test: inline CSV data for controller invariants Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --------- Co-authored-by: Sean Dickinson <sean@bythepixel.com> Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent f721cd1 commit 94cb86d

8 files changed

Lines changed: 549 additions & 0 deletions

File tree

‎Gemfile‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@ gem "thruster", require: false
4242
gem "image_processing", "~> 2.2"
4343
gem "ruby-vips", "~> 2.0"
4444

45+
gem "csv"
46+
4547
group :development, :test do
4648
# See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem
4749
gem "debug", platforms: %i[ mri windows ], require: "debug/prelude"

‎Gemfile.lock‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,7 @@ GEM
115115
cruise (0.3.0-x86_64-darwin)
116116
cruise (0.3.0-x86_64-linux-gnu)
117117
cruise (0.3.0-x86_64-linux-musl)
118+
csv (3.3.6)
118119
date (3.5.1)
119120
debug (1.11.1)
120121
irb (~> 1.10)
@@ -436,6 +437,7 @@ DEPENDENCIES
436437
brakeman
437438
bundler-audit
438439
capybara
440+
csv
439441
debug
440442
faker (~> 3.8)
441443
herb
@@ -499,6 +501,7 @@ CHECKSUMS
499501
cruise (0.3.0-x86_64-darwin) sha256=5dcf048c20cfcaf208cdcdd6ddfd4410acb431ff18a84bd7441bba0c8b8d6b83
500502
cruise (0.3.0-x86_64-linux-gnu) sha256=a7bdd7c72307a450a9d37f3c7a90c118230ea6122663b32b8c8e52cad32adfa8
501503
cruise (0.3.0-x86_64-linux-musl) sha256=54ed6809f1d476bf99a3043bc256cca0efed8bbc9df93a55f4e49eac2bbcb7f4
504+
csv (3.3.6) sha256=aba61e7e507a66f03d45cb1f3c4b6359861c3504038b422962875dce099e4456
502505
date (3.5.1) sha256=750d06384d7b9c15d562c76291407d89e368dda4d4fff957eb94962d325a0dc0
503506
debug (1.11.1) sha256=2e0b0ac6119f2207a6f8ac7d4a73ca8eb4e440f64da0a3136c30343146e952b6
504507
dotenv (3.2.0) sha256=e375b83121ea7ca4ce20f214740076129ab8514cd81378161f11c03853fe619d
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
require "csv"
2+
3+
class Admin::CsvController < AdminController
4+
class CSVHeadersError < StandardError; end
5+
class StudentBulkImportError < StandardError; end
6+
class ClassroomBulkImportError < StandardError; end
7+
8+
IMPORT_ERRORS = [
9+
CSVHeadersError,
10+
StudentBulkImportError,
11+
ClassroomBulkImportError,
12+
CSV::MalformedCSVError,
13+
StudentCsvImporter::InvalidClassroomError,
14+
StudentCsvImporter::InvalidProgramError,
15+
StudentCsvImporter::InvalidStudentError,
16+
StudentCsvImporter::InvalidTeacherError
17+
].freeze
18+
19+
CSV_HEADERS = [ "Student First Name", "Student Last Name", "Grade Level", "Class Name", "Teacher", "Teacher Email",
20+
"Program", "Program Level" ].freeze
21+
22+
before_action :set_school
23+
24+
def download
25+
csv_data = CSV.generate do |csv|
26+
csv << CSV_HEADERS
27+
end
28+
29+
send_data csv_data,
30+
filename: "students-#{Date.today}.csv",
31+
type: "text/csv; charset=utf-8",
32+
disposition: "attachment"
33+
end
34+
35+
def import
36+
csv_file = params[:file]
37+
return redirect_to school_students_path(@school), alert: "Choose a CSV file to import." if csv_file.blank?
38+
39+
csv = CSV.read(csv_file.path, headers: true)
40+
validate_rows!(csv)
41+
StudentCsvImporter.new(csv: csv, school_id: @school.id).import
42+
43+
redirect_to school_students_path(@school), notice: "Students were successfully imported."
44+
rescue *IMPORT_ERRORS => error
45+
redirect_to school_students_path(@school), alert: error.message
46+
end
47+
48+
private
49+
def set_school
50+
@school = School.find(params.expect(:school_id))
51+
end
52+
53+
def validate_rows!(csv)
54+
raise CSVHeadersError, "Headers must match CSV headers" unless CSV_HEADERS == csv.headers
55+
56+
csv.each do |row|
57+
raise CSVHeadersError, "Row must have same number of columns as headers" unless CSV_HEADERS.length == row.length
58+
59+
if @school.students.exists?(first_name: row["Student First Name"], last_name: row["Student Last Name"])
60+
raise StudentBulkImportError, "Student: #{row["Student First Name"]} #{row["Student Last Name"]} already exists"
61+
end
62+
63+
if @school.classrooms.exists?(name: row["Class Name"])
64+
raise ClassroomBulkImportError, "Classroom: #{row["Class Name"]} already exists"
65+
end
66+
end
67+
end
68+
end
Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
2+
3+
class StudentCsvImporter
4+
class InvalidClassroomError < StandardError; end
5+
class InvalidProgramError < StandardError; end
6+
class InvalidStudentError < StandardError; end
7+
class InvalidTeacherError < StandardError; end
8+
9+
def initialize(csv:, school_id:)
10+
@csv = csv
11+
@school_id = school_id
12+
@error_messages = {
13+
classrooms: {},
14+
teachers: {},
15+
students: {}
16+
}
17+
@classrooms = {}
18+
@teachers = {}
19+
@students = []
20+
@row_indexes = {}
21+
end
22+
23+
24+
def import
25+
@csv.each_with_index do |row, index|
26+
next if row.blank?
27+
28+
teacher = find_or_build_teacher(row)
29+
classroom = find_or_build_classroom(row, teacher)
30+
31+
student = Student.new(
32+
first_name: row["Student First Name"],
33+
last_name: row["Student Last Name"],
34+
grade_level: row["Grade Level"],
35+
school_id: @school_id,
36+
classroom: classroom
37+
)
38+
39+
collect_errors(:teachers, teacher, index)
40+
collect_errors(:classrooms, classroom, index)
41+
collect_errors(:students, student, index)
42+
43+
@students << student
44+
end
45+
46+
save_records
47+
end
48+
49+
50+
51+
private
52+
53+
def save_records
54+
ActiveRecord::Base.transaction do
55+
raise_validation_errors!
56+
57+
save_all(@teachers.values, InvalidTeacherError)
58+
save_all(@classrooms.values, InvalidClassroomError)
59+
save_all(@students, InvalidStudentError)
60+
61+
create_program_associations
62+
end
63+
end
64+
65+
# A uniqueness collision between two rows of the same file survives `valid?`,
66+
# because neither record is persisted yet. Re-raise it in the shape the
67+
# validation errors already use so callers only have to handle one thing.
68+
def save_all(records, error_class)
69+
records.each do |record|
70+
record.save!
71+
rescue ActiveRecord::RecordInvalid => error
72+
raise error_class, { @row_indexes[record.object_id] => error.record.errors.full_messages }.to_s
73+
end
74+
end
75+
76+
def create_program_associations
77+
@csv.each do |row|
78+
teacher = @teachers[row["Teacher"]]
79+
classroom = @classrooms[[ teacher.name, row["Class Name"] ]]
80+
81+
program = find_existing_program!(row["Program"])
82+
83+
classroom.classroom_programs.create_or_find_by!(program: program, level: row["Program Level"])
84+
end
85+
end
86+
87+
def find_existing_program!(name)
88+
Program.find_by!(name: name)
89+
rescue ActiveRecord::RecordNotFound
90+
raise InvalidProgramError, "Program: #{name} does not exist"
91+
end
92+
93+
def collect_errors(type, record, index)
94+
@row_indexes[record.object_id] ||= index
95+
96+
return if record.valid?
97+
98+
@error_messages[type][index] = record.errors.full_messages
99+
end
100+
101+
def raise_validation_errors!
102+
raise InvalidClassroomError, @error_messages[:classrooms].to_s if @error_messages[:classrooms].any?
103+
raise InvalidStudentError, @error_messages[:students].to_s if @error_messages[:students].any?
104+
raise InvalidTeacherError, @error_messages[:teachers].to_s if @error_messages[:teachers].any?
105+
end
106+
107+
def find_or_build_teacher(row)
108+
@teachers[row["Teacher"]] ||= Teacher.new(
109+
name: row["Teacher"],
110+
email: row["Teacher Email"],
111+
school_id: @school_id
112+
)
113+
end
114+
115+
def find_or_build_classroom(row, teacher)
116+
key = [ teacher.name, row["Class Name"] ]
117+
118+
@classrooms[key] ||= Classroom.new(
119+
school_id: @school_id,
120+
name: row["Class Name"],
121+
teacher: teacher
122+
)
123+
end
124+
end

‎config/routes.rb‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@
2525
member { get :schedule }
2626
end
2727
resources :teachers, shallow: true, except: [ :show ]
28+
get :csv_template, to: "admin/csv#download"
29+
post :csv_import, to: "admin/csv#import"
2830
end
2931
resources :content_modules, except: [ :show ] do
3032
resources :links, shallow: true, except: %i[index show]

0 commit comments

Comments
 (0)