7 changed files with 111 additions and 0 deletions
@ -0,0 +1,66 @@
|
||||
class BulkUpload::Lettings::LogCreator |
||||
attr_reader :bulk_upload, :path |
||||
|
||||
def initialize(bulk_upload:, path:) |
||||
@bulk_upload = bulk_upload |
||||
@path = path |
||||
end |
||||
|
||||
def call |
||||
row_parsers.each do |row_parser| |
||||
next unless row_parser.valid? |
||||
|
||||
row_parser.log.bulk_upload = bulk_upload |
||||
row_parser.log.save |
||||
end |
||||
end |
||||
|
||||
private |
||||
|
||||
def row_offset |
||||
5 |
||||
end |
||||
|
||||
def col_offset |
||||
1 |
||||
end |
||||
|
||||
def row_parsers |
||||
@row_parsers ||= body_rows.map do |row| |
||||
stripped_row = row[col_offset..] |
||||
headers = ("field_1".."field_134").to_a |
||||
hash = Hash[headers.zip(stripped_row)] |
||||
hash[:bulk_upload] = bulk_upload |
||||
|
||||
BulkUpload::Lettings::RowParser.new(hash) |
||||
end |
||||
end |
||||
|
||||
def body_rows |
||||
rows[row_offset..] |
||||
end |
||||
|
||||
def rows |
||||
@rows ||= CSV.read(path, row_sep:) |
||||
end |
||||
|
||||
# determine the row seperator from CSV |
||||
# Windows will use \r\n |
||||
def row_sep |
||||
contents = "" |
||||
|
||||
File.open(path, "r") do |f| |
||||
f.seek(9900) |
||||
contents = f.read |
||||
end |
||||
|
||||
rn_count = contents.scan("\r\n").count |
||||
n_count = contents.scan(/[^\r]\n/).count |
||||
|
||||
if rn_count > n_count |
||||
"\r\n" |
||||
else |
||||
"\n" |
||||
end |
||||
end |
||||
end |
||||
@ -0,0 +1,6 @@
|
||||
class AddBulkUploadToLogs < ActiveRecord::Migration[7.0] |
||||
def change |
||||
add_reference :lettings_logs, :bulk_upload |
||||
add_reference :sales_logs, :bulk_upload |
||||
end |
||||
end |
||||
|
@ -0,0 +1,31 @@
|
||||
require "rails_helper" |
||||
|
||||
RSpec.describe BulkUpload::Lettings::LogCreator do |
||||
subject(:service) { described_class.new(bulk_upload:, path:) } |
||||
|
||||
let(:owning_org) { create(:organisation, old_visible_id: 123) } |
||||
let(:user) { create(:user, organisation: owning_org) } |
||||
|
||||
let(:bulk_upload) { create(:bulk_upload, :lettings, user:) } |
||||
let(:path) { file_fixture("2022_23_lettings_bulk_upload.csv") } |
||||
|
||||
describe "#call" do |
||||
context "when a valid csv with new log" do |
||||
it "creates a new log" do |
||||
expect { service.call }.to change(LettingsLog, :count) |
||||
end |
||||
|
||||
it "associates log with bulk upload" do |
||||
service.call |
||||
|
||||
log = LettingsLog.last |
||||
expect(log.bulk_upload).to eql(bulk_upload) |
||||
expect(bulk_upload.lettings_logs).to include(log) |
||||
end |
||||
end |
||||
|
||||
context "when valid csv with existing log" do |
||||
xit "what should happen?" |
||||
end |
||||
end |
||||
end |
||||
Loading…
Reference in new issue