|
| 1 | +class CreateAuthorizationFromSnapshot |
| 2 | + include LocalDatabaseUtils |
| 3 | + |
| 4 | + attr_reader :authorization_request, :event_row |
| 5 | + |
| 6 | + def initialize(authorization_request, event_row) |
| 7 | + @authorization_request = authorization_request |
| 8 | + @event_row = event_row |
| 9 | + end |
| 10 | + |
| 11 | + def perform |
| 12 | + snapshot = find_closest_snapshot |
| 13 | + |
| 14 | + # XXX Cas où il y a eu une révocation récente (dunno why ?) |
| 15 | + if snapshot.blank? |
| 16 | + data = authorization_request.data |
| 17 | + else |
| 18 | + snapshot_items = find_snapshot_items(snapshot) |
| 19 | + data = build_data(snapshot_items) |
| 20 | + end |
| 21 | + |
| 22 | + authorization = Authorization.create!( |
| 23 | + request_id: authorization_request.id, |
| 24 | + applicant: authorization_request.applicant, |
| 25 | + data: build_data(snapshot_items), |
| 26 | + created_at: event_datetime, |
| 27 | + ) |
| 28 | + |
| 29 | + authorization_request.class.documents.each do |document_identifier| |
| 30 | + storage_file_model = authorization_request.public_send(document_identifier) |
| 31 | + next if storage_file_model.blank? |
| 32 | + |
| 33 | + document = authorization.documents.create!( |
| 34 | + identifier: document_identifier, |
| 35 | + ) |
| 36 | + document.file.attach(storage_file_model.blob) |
| 37 | + end |
| 38 | + |
| 39 | + authorization |
| 40 | + end |
| 41 | + |
| 42 | + private |
| 43 | + |
| 44 | + def find_closest_snapshot |
| 45 | + if event_datetime.to_date <= initial_creation_date |
| 46 | + data = database.execute( |
| 47 | + 'select * from snapshots where enrollment_id = ? order by created_at limit 1', |
| 48 | + authorization_request.id, |
| 49 | + ) |
| 50 | + else |
| 51 | + data = database.execute( |
| 52 | + 'select * from snapshots where enrollment_id = ? and date(created_at) = ? order by created_at limit 1', |
| 53 | + authorization_request.id, |
| 54 | + event_datetime.to_date.to_s, |
| 55 | + ) |
| 56 | + end |
| 57 | + |
| 58 | + return if data.empty? |
| 59 | + |
| 60 | + JSON.parse(data[0][-1]).to_h |
| 61 | + end |
| 62 | + |
| 63 | + def find_snapshot_items(snapshot) |
| 64 | + database.execute('select * from snapshot_items where snapshot_id = ?', snapshot['id']) |
| 65 | + end |
| 66 | + |
| 67 | + # FIXME que 26 raws clairement ça va se faire à la main je pense |
| 68 | + def build_data(snapshot_items) |
| 69 | + authorization_request.data |
| 70 | + end |
| 71 | + |
| 72 | + def event_datetime |
| 73 | + @event_datetime ||= DateTime.parse(event_row['created_at']) |
| 74 | + end |
| 75 | + |
| 76 | + def initial_creation_date |
| 77 | + @initial_creation_date ||= Date.new(2024, 2, 21) |
| 78 | + end |
| 79 | +end |
0 commit comments