import_json.rb 7.9 KB
Newer Older
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# frozen_string_literal: true

class Import::ImportJson
  attr_accessor :data,  :force_uuid
  attr_reader :user_id, :collection_id, :collection, :all_collection, :user,
    :new_data, :log, :new_attachments

#Dir["public/images/reactions/*"].each{|f| if !(Reaction.find_by(reaction_svg_file: File.basename(f))) then  File.delete(f) end}


  # def dummy_data
  #   {
  #     'reactions' => [
  #       {
  #         # 'id' => nil,
  #         'name' => nil,
  #         'created_at' => nil,
  #         'updated_at' => nil,
  #         'description' => nil,
  #         'timestamp_start' => nil,
  #         'timestamp_stop' => nil,
  #         'observation' => nil,
  #         'purification' => nil,
  #         'dangerous_products' => nil,
  #         'tlc_solvents' => nil,
  #         'tlc_description' => nil,
  #         'rf_value' => nil,
  #         'temperature' => nil,
  #         'status' => nil,
  #         # 'reaction_svg_file' => nil, # to process
  #         'solvent' => nil,
  #         'deleted_at' => nil,
  #         'short_label' => nil,
  #         # 'created_by' => nil, # reprocessed
  #         'role' => nil,
  #         'origin' => nil,
  #         ##### CodeLog
  #         'uuid' => nil # from reaction.code_log.id
  #       }
  #     ],
  #     'samples' => [
  #       # 'id' => nil,
  #       # 'ancestry' => nil,
  #         # IDEA pass uuid of ancestors if present in acestry_uuids?
  #       # 'created_by' => nil,
  #        # IDEA reprocessed with user_id? use  ORCID in created_by_orcid
  #       # 'user_id' => nil, # NB this column is not used
  #       'name' => nil,
  #       'target_amount_value' => nil,
  #       'target_amount_unit' => nil,
  #       'created_at' => nil,
  #       'updated_at' => nil,
  #       'description' => nil,
  #       'molecule_id' => nil,
  #       'molfile' => nil,
  #       'purity' => nil,
  #       'solvent' => nil,
  #       'impurities' => nil,
  #       'location' => nil,
  #       'is_top_secret' => nil,
  #       'external_label' => nil,
  #       'short_label' => nil,
  #       'real_amount_value' => nil,
  #       'real_amount_unit' => nil,
  #       'imported_readout' => nil,
  #       'deleted_at' => nil,
  #       'sample_svg_file' => nil,
  #       'identifier' => nil,
  #       'density' => nil,
  #       'melting_point' => nil,
  #       'boiling_point' => nil,
  #       'fingerprint_id' => nil,
  #       'xref' => nil,
  #       'molarity_value' => nil,
  #       'molarity_unit' => nil,
  #       ##### CodeLog
  #       'uuid' => nil, # from sample.code_log.id
  #       ##### ReactionsStartingMaterialSample, ReactionsSolventSample,
  #       ##### ReactionsReactantSample, ReactionsProductSample
  #       'reaction_sample' => [nil,nil,nil,nil]
  #       'r_uuid' => nil,
  #       'r_reference' => nil,
  #       'r_equivalent' => nil,
  #     ]
  #   }
  # end

  def initialize(**arg)
    d = arg[:data]
    @data = d.is_a?(String) && JSON.parse(d, allow_nan: true) || d
    @user_id = arg[:user_id]
    @collection_id = arg[:collection_id]
    @new_data = { }
    @new_attachments = { }
    @log = { 'reactions' => {}, 'samples' => {} }
    @force_uuid = arg[:force_uuid]
    find_collection
    find_collection_all
  end

  def import
    map_data_uuids(@log)
    unless collections?
      @log['collections'] = 'could not find collection or user'
      return @log
    end
    #begin
      import_reactions
      import_samples
      import_attachments
    #rescue
    #end
    File.write("log_#{Time.now.to_i}.json", JSON.pretty_generate(@log))
  end

  def collection_id= id
    @collection_id = id
    find_collection
    id
  end

  def user_id= id
    @user_id = id
    find_collection_all
    id
  end

  private

  def import_reactions
    return unless collections?
    attribute_names = filter_attributes(Reaction)
    reactions.each do |el|
      attribs = el.slice(*attribute_names).merge(
        created_by: user_id,
        collections_reactions_attributes: [
          {collection_id: collection.id},
          {collection_id: all_collection.id}
        ]
      )
      create_element(el['uuid'], attribs, Reaction, 'reaction')
    end
  end

  def import_samples
    return unless collections?
    attribute_names = filter_attributes(Sample)
    samples.each do |el|
      attribs = el.slice(*attribute_names).merge(
        created_by: user_id,
        collections_samples_attributes: [
          { collection_id: collection.id },
          { collection_id: all_collection.id }
        ]
      )
      new_el = create_element(el['uuid'], attribs, Sample, 'sample')
      next unless new_el
      klass = if el['reaction_sample'][0]
                ReactionsStartingMaterialSample
              elsif el['reaction_sample'][2]
                ReactionsReactantSample
              elsif el['reaction_sample'][1]
                ReactionsSolventSample
              elsif el['reaction_sample'][3]
                ReactionsProductSample
              end
      add_to_reaction(klass, el, new_el) if klass
    end
  end

  def map_data_uuids(h)
    reactions.map do |r|
      r['uuid'].is_a?(String) && h['reactions'][r['uuid']] = {}
    end
    samples.map do |r|
      r['uuid'].is_a?(String) && h['samples'][r['uuid']] = {}
    end
  end

  def create_element(uuid, element, klass, source)
    #ActiveRecord::Base.transaction do
      if force_uuid && CodeLog.find_by(id: uuid)
        @log[source + 's'][uuid]['uuid'] = 'already attributed'
        return
      end
      new_el = klass.new(element)
      if new_el.save!
        if force_uuid
          new_el.code_log.really_destroy!
          CodeLog.create(id: uuid, source: source, source_id: new_el.id)
        end
        @new_data[uuid] = {'id' => new_el.id, 'type' => source}
        @log[source + 's'][uuid]['created_at'] = new_el.created_at
        if !(new_el.container)
          c = Container.create_root_container(
            containable_id: new_el.id,
            containable_type: klass.name,
          )
        end
        create_analyses(uuid, new_el)
        new_el
      else
        @log[source + 's'][uuid]['created_at'] = 'not created'
        nil
      end
    #end
  end

  def create_analyses(uuid, el)
    analyses[uuid]&.each do |a|
      new_a = el.container.children.where(container_type: 'analyses')
        .first.children.create(
        container_type: 'analysis',
        extended_metadata: a['extended_metadata'],
        description: a['description']
      )
      a['attachments']&.each do |att|
        @new_attachments[att['identifier']] = Attachment.new(
          filename: att['filename'],
          identifier: att['identifier'],
          checksum: att['checksum'],
          container_id: new_a.id
        )
      end
    end
  end

  def filter_attributes(klass)
    attributes = klass.attribute_names - %w(id user_id created_by deleted_at )
    case klass
    when Sample
      attributes -= [
        'ancestry', 'molecule_id', 'xref', 'fingerprint_id',
        'is_top_secret', 'molecule_svg_file'
       ]
      attributes += ['residues_attributes', 'elemental_compositions_attributes']
    when Reaction
      attributes -= ['reaction_svg_file']
    end
    attributes
  end

  def add_to_reaction(klass, el, new_el)
    el_uuid = el['uuid']
    r_uuid = el['r_uuid']
    ref = (el['r_reference'] == 't') || el['r_reference'] == 'f'
    eq = el['r_equivalent']
    @log['samples'][el_uuid][klass.name] = klass.create!(
      sample_id: new_el.id, reaction_id: new_data[r_uuid]['id'],
      reference: ref, equivalent: eq
    ) && '201' || '500'
  end

  def reactions
    data && data['reactions'] || []
  end

  def samples
    data && data['samples'] || []
  end

  def analyses
    data && data['analyses'] || []
  end

  def collections?
    @collection && @all_collection
  end

  def find_collection(c_id = collection_id)
    @collection = Collection.find_by(id: c_id) if c_id.is_a?(Integer)
  end

  def find_collection_all(id = user_id)
    return unless id.is_a?(Integer)
    @all_collection = Collection.get_all_collection_for_user(id)
  end
end