• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

pulibrary / pdc_describe / 6d3ba70e-74ee-40ef-a5be-d2cda3dbf2d7

15 Apr 2024 06:35PM UTC coverage: 95.333% (-0.5%) from 95.804%
6d3ba70e-74ee-40ef-a5be-d2cda3dbf2d7

Pull #1762

circleci

carolyncole
Added an explicit endpoint to the Wizard controlller to upload files. Moved the logic to upload a file to the controller instead of my hack via the Readme class.
Pull Request #1762: Fixes Wizard delay in displaying uploaded files

3 of 22 new or added lines in 2 files covered. (13.64%)

34 existing lines in 3 files now uncovered.

3268 of 3428 relevant lines covered (95.33%)

210.97 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

83.18
/app/controllers/works_controller.rb
1
# frozen_string_literal: true
2

3
require "nokogiri"
1✔
4
require "open-uri"
1✔
5

6
# Currently this controller supports Multiple ways to create a work, wizard mode, create dataset, and migrate
7
# The goal is to eventually break some of these workflows into separate contorllers.
8
# For the moment I'm documenting which methods get called by each workflow below.
9
# Note: new, edit and update get called by both the migrate and Non wizard workflows
10
#
11
# Normal mode
12
#  new & file_list -> create -> show & file_list
13
#
14
#  Clicking Edit puts you in wizard mode for some reason :(
15
#
16
# migrate
17
#
18
#  new & file_list -> create -> show & file_list
19
#
20
#  Clicking edit
21
#   edit & file_list -> update -> show & file_list
22
#
23

24
# rubocop:disable Metrics/ClassLength
25
class WorksController < ApplicationController
1✔
26
  include ERB::Util
1✔
27
  around_action :rescue_aasm_error, only: [:approve, :withdraw, :resubmit, :validate, :create]
1✔
28

29
  skip_before_action :authenticate_user!
1✔
30
  before_action :authenticate_user!, unless: :public_request?
1✔
31

32
  def index
1✔
33
    @works = Work.all
4✔
34
    respond_to do |format|
4✔
35
      format.html
4✔
36
      format.rss { render layout: false }
6✔
37
    end
38
  end
39

40
  # only non wizard mode
41
  def new
1✔
42
    group = Group.find_by(code: params[:group_code]) || current_user.default_group
27✔
43
    @work = Work.new(created_by_user_id: current_user.id, group:)
27✔
44
    @work_decorator = WorkDecorator.new(@work, current_user)
27✔
45
    @form_resource_decorator = FormResourceDecorator.new(@work, current_user)
27✔
46
  end
47

48
  # only non wizard mode
49
  def create
1✔
50
    @work = Work.new(created_by_user_id: current_user.id, group_id: params_group_id, user_entered_doi: params["doi"].present?)
32✔
51
    @work.resource = FormToResourceService.convert(params, @work)
32✔
52
    @work.resource.migrated = migrated?
32✔
53
    if @work.valid?
32✔
54
      @work.draft!(current_user)
28✔
55
      upload_service = WorkUploadsEditService.new(@work, current_user)
27✔
56
      upload_service.update_precurated_file_list(added_files_param, deleted_files_param)
27✔
57
      redirect_to work_url(@work), notice: "Work was successfully created."
27✔
58
    else
59
      @work_decorator = WorkDecorator.new(@work, current_user)
4✔
60
      @form_resource_decorator = FormResourceDecorator.new(@work, current_user)
4✔
61
      render :new, status: :unprocessable_entity
4✔
62
    end
63
  end
64

65
  ##
66
  # Show the information for the dataset with the given id
67
  # When requested as .json, return the internal json resource
68
  def show
1✔
69
    @work = Work.find(params[:id])
115✔
70
    UpdateSnapshotJob.perform_later(work_id: @work.id, last_snapshot_id: work.upload_snapshots.first&.id)
115✔
71
    @work_decorator = WorkDecorator.new(@work, current_user)
115✔
72

73
    respond_to do |format|
115✔
74
      format.html do
115✔
75
        # Ensure that the Work belongs to a Group
76
        group = @work_decorator.group
112✔
77
        raise(Work::InvalidGroupError, "The Work #{@work.id} does not belong to any Group") unless group
112✔
78

79
        @can_curate = current_user.can_admin?(group)
111✔
80
        @work.mark_new_notifications_as_read(current_user.id)
111✔
81
      end
82
      format.json { render json: @work.to_json }
118✔
83
    end
84
  end
85

86
  # only non wizard mode
87
  def file_list
1✔
88
    if params[:id] == "NONE"
181✔
89
      # This is a special case when we render the file list for a work being created
90
      # (i.e. it does not have an id just yet)
91
      render json: []
30✔
92
    else
93
      @work = Work.find(params[:id])
151✔
94
      render json: @work.file_list
151✔
95
    end
96
  end
97

98
  def resolve_doi
1✔
99
    @work = Work.find_by_doi(params[:doi])
3✔
100
    redirect_to @work
2✔
101
  end
102

103
  def resolve_ark
1✔
104
    @work = Work.find_by_ark(params[:ark])
3✔
105
    redirect_to @work
2✔
106
  end
107

108
  # GET /works/1/edit
109
  # only non wizard mode
110
  def edit
1✔
111
    @work = Work.find(params[:id])
52✔
112
    @work_decorator = WorkDecorator.new(@work, current_user)
52✔
113
    if validate_modification_permissions(work: @work,
52✔
114
                                         uneditable_message: "Can not update work: #{@work.id} is not editable by #{current_user.uid}",
115
                                         current_state_message: "Can not update work: #{@work.id} is not editable in current state by #{current_user.uid}")
116
      @uploads = @work.uploads
47✔
117
      @form_resource_decorator = FormResourceDecorator.new(@work, current_user)
47✔
118
    end
119
  end
120

121
  # PATCH /works/1
122
  # only non wizard mode
123
  def update
1✔
124
    @work = Work.find(params[:id])
50✔
125
    if validate_modification_permissions(work: @work, uneditable_message: "Can not update work: #{@work.id} is not editable by #{current_user.uid}",
50✔
126
                                         current_state_message: "Can not update work: #{@work.id} is not editable in current state by #{current_user.uid}")
127
      update_work
48✔
128
    end
129
  end
130

131
  def approve
1✔
132
    @work = Work.find(params[:id])
15✔
133
    @work.approve!(current_user)
15✔
134
    flash[:notice] = "Your files are being moved to the post-curation bucket in the background. Depending on the file sizes this may take some time."
7✔
135
    redirect_to work_path(@work)
7✔
136
  end
137

138
  def withdraw
1✔
139
    @work = Work.find(params[:id])
2✔
140
    @work.withdraw!(current_user)
2✔
141
    redirect_to work_path(@work)
1✔
142
  end
143

144
  def resubmit
1✔
145
    @work = Work.find(params[:id])
2✔
146
    @work.resubmit!(current_user)
2✔
147
    redirect_to work_path(@work)
1✔
148
  end
149

150
  def assign_curator
1✔
151
    work = Work.find(params[:id])
5✔
152
    work.change_curator(params[:uid], current_user)
5✔
153
    if work.errors.count > 0
4✔
154
      render json: { errors: work.errors.map(&:type) }, status: :bad_request
1✔
155
    else
156
      render json: {}
3✔
157
    end
158
  rescue => ex
159
    Rails.logger.error("Error changing curator for work: #{work.id}. Exception: #{ex.message}")
1✔
160
    render json: { errors: ["Cannot save dataset"] }, status: :bad_request
1✔
161
  end
162

163
  def add_message
1✔
164
    work = Work.find(params[:id])
6✔
165
    if params["new-message"].present?
6✔
166
      new_message_param = params["new-message"]
6✔
167
      sanitized_new_message = html_escape(new_message_param)
6✔
168

169
      work.add_message(sanitized_new_message, current_user.id)
6✔
170
    end
171
    redirect_to work_path(id: params[:id])
6✔
172
  end
173

174
  def add_provenance_note
1✔
175
    work = Work.find(params[:id])
2✔
176
    if params["new-provenance-note"].present?
2✔
177
      new_date = params["new-provenance-date"]
2✔
178
      new_label = params["change_label"]
2✔
179
      new_note = html_escape(params["new-provenance-note"])
2✔
180

181
      work.add_provenance_note(new_date, new_note, current_user.id, new_label)
2✔
182
    end
183
    redirect_to work_path(id: params[:id])
2✔
184
  end
185

186
  # Outputs the Datacite XML representation of the work
187
  def datacite
1✔
188
    work = Work.find(params[:id])
2✔
189
    render xml: work.to_xml
2✔
190
  end
191

192
  def datacite_validate
1✔
193
    @errors = []
3✔
194
    @work = Work.find(params[:id])
3✔
195
    validator = WorkValidator.new(@work)
3✔
196
    unless validator.valid_datacite?
3✔
197
      @errors = @work.errors.full_messages
2✔
198
    end
199
  end
200

201
  def migrating?
1✔
202
    return @work.resource.migrated if @work&.resource && !params.key?(:migrate)
62✔
203

204
    params[:migrate]
44✔
205
  end
206
  helper_method :migrating?
1✔
207

208
  # Returns the raw BibTex citation information
209
  def bibtex
1✔
210
    work = Work.find(params[:id])
1✔
211
    creators = work.resource.creators.map { |creator| "#{creator.family_name}, #{creator.given_name}" }
15✔
212
    citation = DatasetCitation.new(creators, [work.resource.publication_year], work.resource.titles.first.title, work.resource.resource_type, work.resource.publisher, work.resource.doi)
1✔
213
    bibtex = citation.bibtex
1✔
214
    send_data bibtex, filename: "#{citation.bibtex_id}.bibtex", type: "text/plain", disposition: "attachment"
1✔
215
  end
216

217
  # POST /works/1/upload-files (called via Uppy)
218
  def upload_files
1✔
219
    @work = Work.find(params[:id])
×
NEW
220
    params["files"].each do |file|
×
NEW
221
      upload_file(file)
×
222
    end
223
  end
224

225
  private
1✔
226

227
    # Extract the Work ID parameter
228
    # @return [String]
229
    def work_id_param
1✔
230
      params[:id]
119✔
231
    end
232

233
    # Find the Work requested by ID
234
    # @return [Work]
235
    def work
1✔
236
      Work.find(work_id_param)
119✔
237
    end
238

239
    # Determine whether or not the request is for the :index action in the RSS
240
    # response format
241
    # This is to enable PDC Discovery to index approved content via the RSS feed
242
    def rss_index_request?
1✔
243
      action_name == "index" && request.format.symbol == :rss
511✔
244
    end
245

246
    # Determine whether or not the request is for the :show action in the JSON
247
    # response format
248
    # @return [Boolean]
249
    def json_show_request?
1✔
250
      action_name == "show" && request.format.symbol == :json
509✔
251
    end
252

253
    # Determine whether or not the requested Work has been approved
254
    # @return [Boolean]
255
    def work_approved?
1✔
256
      work&.state == "approved"
4✔
257
    end
258

259
    ##
260
    # Public requests are requests that do not require authentication.
261
    # This is to enable PDC Discovery to index approved content via the RSS feed
262
    # and .json calls to individual works without needing to log in as a user.
263
    # Note that only approved works can be fetched for indexing.
264
    def public_request?
1✔
265
      return true if rss_index_request?
511✔
266
      return true if json_show_request? && work_approved?
509✔
267
      false
507✔
268
    end
269

270
    def work_params
1✔
271
      params[:work] || {}
154✔
272
    end
273

274
    def patch_params
1✔
UNCOV
275
      return {} unless params.key?(:patch)
×
276

UNCOV
277
      params[:patch]
×
278
    end
279

280
    def pre_curation_uploads_param
1✔
UNCOV
281
      return if patch_params.nil?
×
282

UNCOV
283
      patch_params[:pre_curation_uploads]
×
284
    end
285

286
    def readme_file_param
1✔
UNCOV
287
      return if patch_params.nil?
×
288

UNCOV
289
      patch_params[:readme_file]
×
290
    end
291

292
    def rescue_aasm_error
1✔
293
      super
51✔
294
    rescue StandardError => generic_error
295
      if action_name == "create"
1✔
296
        handle_error_for_create(generic_error)
1✔
297
      else
UNCOV
298
        redirect_to root_url, notice: "We apologize, an error was encountered: #{generic_error.message}. Please contact the PDC Describe administrators."
×
299
      end
300
    end
301

302
    def handle_error_for_create(generic_error)
1✔
303
      if @work.persisted?
1✔
304
        Honeybadger.notify("Failed to create the new Dataset #{@work.id}: #{generic_error.message}")
×
305
        @form_resource_decorator = FormResourceDecorator.new(@work, current_user)
×
UNCOV
306
        redirect_to edit_work_url(id: @work.id), notice: "Failed to create the new Dataset #{@work.id}: #{generic_error.message}", params:
×
307
      else
308
        Honeybadger.notify("Failed to create a new Dataset #{@work.id}: #{generic_error.message}")
1✔
309
        new_params = {}
1✔
310
        new_params[:wizard] = wizard_mode? if wizard_mode?
1✔
311
        new_params[:migrate] = migrating? if migrating?
1✔
312
        @form_resource_decorator = FormResourceDecorator.new(@work, current_user)
1✔
313
        redirect_to new_work_url(params: new_params), notice: "Failed to create a new Dataset: #{generic_error.message}", params: new_params
1✔
314
      end
315
    end
316

317
    def redirect_aasm_error(transition_error_message)
1✔
318
      if @work.persisted?
10✔
319
        redirect_to edit_work_url(id: @work.id), notice: transition_error_message, params:
10✔
320
      else
321
        new_params = {}
×
322
        new_params[:wizard] = wizard_mode? if wizard_mode?
×
323
        new_params[:migrate] = migrating? if migrating?
×
324
        @form_resource_decorator = FormResourceDecorator.new(@work, current_user)
×
UNCOV
325
        redirect_to new_work_url(params: new_params), notice: transition_error_message, params: new_params
×
326
      end
327
    end
328

329
    def error_action
1✔
330
      @form_resource_decorator = FormResourceDecorator.new(@work, current_user)
×
331
      if action_name == "create"
×
332
        :new
×
333
      elsif action_name == "validate"
×
334
        :edit
×
335
      elsif action_name == "new_submission"
×
UNCOV
336
        :new_submission
×
337
      else
338
        @work_decorator = WorkDecorator.new(@work, current_user)
×
UNCOV
339
        :show
×
340
      end
341
    end
342

343
    def wizard_mode?
1✔
344
      params[:wizard] == "true"
1✔
345
    end
346

347
    def update_work
1✔
348
      upload_service = WorkUploadsEditService.new(@work, current_user)
48✔
349
      if @work.approved?
48✔
350
        upload_keys = deleted_files_param || []
5✔
351
        deleted_uploads = upload_service.find_post_curation_uploads(upload_keys:)
5✔
352

353
        return head(:forbidden) unless deleted_uploads.empty?
5✔
354
      else
355
        @work = upload_service.update_precurated_file_list(added_files_param, deleted_files_param)
43✔
356
      end
357

358
      process_updates
47✔
359
    end
360

361
    def added_files_param
1✔
362
      Array(work_params[:pre_curation_uploads_added])
70✔
363
    end
364

365
    def deleted_files_param
1✔
366
      deleted_count = (work_params["deleted_files_count"] || "0").to_i
75✔
367
      (1..deleted_count).map { |i| work_params["deleted_file_#{i}"] }.select(&:present?)
84✔
368
    end
369

370
    def process_updates
1✔
371
      if WorkCompareService.update_work(work: @work, update_params:, current_user:)
47✔
372
        redirect_to work_url(@work), notice: "Work was successfully updated."
45✔
373
      else
374
        # This is needed for rendering HTML views with validation errors
375
        @uploads = @work.uploads
2✔
376
        @form_resource_decorator = FormResourceDecorator.new(@work, current_user)
2✔
377

378
        render :edit, status: :unprocessable_entity
2✔
379
      end
380
    end
381

382
    def migrated?
1✔
383
      return false unless params.key?(:submit)
32✔
384

385
      params[:submit] == "Migrate"
28✔
386
    end
387

388
    def upload_file(file)
1✔
NEW
UNCOV
389
      filename = file.original_filename
×
NEW
UNCOV
390
      size = file.size
×
NEW
UNCOV
391
      key = @work.s3_query_service.upload_file(io: file.to_io, filename:, size:)
×
NEW
UNCOV
392
      if key
×
NEW
UNCOV
393
        last_response = @work.s3_query_service.last_response
×
NEW
UNCOV
394
        UploadSnapshot.create(work:, files: [{ "filename" => key, "checksum" => last_response.etag.delete('"') }])
×
NEW
UNCOV
395
        @work.track_change(:added, key)
×
NEW
UNCOV
396
        @work.log_file_changes(current_user.id)
×
397
      else
NEW
UNCOV
398
        Rails.logger.error("Error uploading #{filename} to work #{@work.id}")
×
399
      end
400
    end
401
end
402
# rubocop:enable Metrics/ClassLength
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc