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

pulibrary / pdc_describe / 9091a1ae-29be-458c-984a-339d213919c4

12 Dec 2024 07:41PM UTC coverage: 26.434% (-69.7%) from 96.113%
9091a1ae-29be-458c-984a-339d213919c4

Pull #2000

circleci

jrgriffiniii
Removing integration with ActiveStorage
Pull Request #2000: Bump actionpack from 7.2.1.1 to 7.2.2.1

945 of 3575 relevant lines covered (26.43%)

0.35 hits per line

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

1.34
/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
×
27
  around_action :rescue_aasm_error, only: [:approve, :withdraw, :resubmit, :validate, :create]
×
28

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

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

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

48
  # only non wizard mode
49
  def create
×
50
    @work = Work.new(created_by_user_id: current_user.id, group_id: params_group_id, user_entered_doi: params["doi"].present?)
×
51
    @work.resource = FormToResourceService.convert(params, @work)
×
52
    @work.resource.migrated = migrated?
×
53
    if @work.valid?
×
54
      @work.draft!(current_user)
×
55
      upload_service = WorkUploadsEditService.new(@work, current_user)
×
56
      upload_service.update_precurated_file_list(added_files_param, deleted_files_param)
×
57
      redirect_to work_url(@work), notice: "Work was successfully created."
×
58
    else
59
      @work_decorator = WorkDecorator.new(@work, current_user)
×
60
      @form_resource_decorator = FormResourceDecorator.new(@work, current_user)
×
61
      # return 200 so the loadbalancer doesn't capture the error
62
      render :new
×
63
    end
64
  end
65

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

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

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

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

99
  def resolve_doi
×
100
    @work = Work.find_by_doi(params[:doi])
×
101
    redirect_to @work
×
102
  end
103

104
  def resolve_ark
×
105
    @work = Work.find_by_ark(params[:ark])
×
106
    redirect_to @work
×
107
  end
108

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

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

132
  def approve
×
133
    @work = Work.find(params[:id])
×
134
    @work.approve!(current_user)
×
135
    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."
×
136
    redirect_to work_path(@work)
×
137
  end
138

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

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

151
  def revert_to_draft
×
152
    @work = Work.find(params[:id])
×
153
    @work.revert_to_draft!(current_user)
×
154

155
    redirect_to work_path(@work)
×
156
  end
157

158
  def assign_curator
×
159
    work = Work.find(params[:id])
×
160
    work.change_curator(params[:uid], current_user)
×
161
    if work.errors.count > 0
×
162
      render json: { errors: work.errors.map(&:type) }, status: :bad_request
×
163
    else
164
      render json: {}
×
165
    end
166
  rescue => ex
167
    # This is necessary for JSON responses
168
    Rails.logger.error("Error changing curator for work: #{work.id}. Exception: #{ex.message}")
×
169
    Honeybadger.notify("Error changing curator for work: #{work.id}. Exception: #{ex.message}")
×
170
    render(json: { errors: ["Cannot save dataset"] }, status: :bad_request)
×
171
  end
172

173
  def add_message
×
174
    work = Work.find(params[:id])
×
175
    if params["new-message"].present?
×
176
      new_message_param = params["new-message"]
×
177
      sanitized_new_message = html_escape(new_message_param)
×
178

179
      work.add_message(sanitized_new_message, current_user.id)
×
180
    end
181
    redirect_to work_path(id: params[:id])
×
182
  end
183

184
  def add_provenance_note
×
185
    work = Work.find(params[:id])
×
186
    if params["new-provenance-note"].present?
×
187
      new_date = params["new-provenance-date"]
×
188
      new_label = params["change_label"]
×
189
      new_note = html_escape(params["new-provenance-note"])
×
190

191
      work.add_provenance_note(new_date, new_note, current_user.id, new_label)
×
192
    end
193
    redirect_to work_path(id: params[:id])
×
194
  end
195

196
  # Outputs the Datacite XML representation of the work
197
  def datacite
×
198
    work = Work.find(params[:id])
×
199
    render xml: work.to_xml
×
200
  end
201

202
  def datacite_validate
×
203
    @errors = []
×
204
    @work = Work.find(params[:id])
×
205
    validator = WorkValidator.new(@work)
×
206
    unless validator.valid_datacite?
×
207
      @errors = @work.errors.full_messages
×
208
    end
209
  end
210

211
  def migrating?
×
212
    return @work.resource.migrated if @work&.resource && !params.key?(:migrate)
×
213

214
    params[:migrate]
×
215
  end
216
  helper_method :migrating?
×
217

218
  # Returns the raw BibTex citation information
219
  def bibtex
×
220
    work = Work.find(params[:id])
×
221
    creators = work.resource.creators.map { |creator| "#{creator.family_name}, #{creator.given_name}" }
×
222
    citation = DatasetCitation.new(creators, [work.resource.publication_year], work.resource.titles.first.title, work.resource.resource_type, work.resource.publisher, work.resource.doi)
×
223
    bibtex = citation.bibtex
×
224
    send_data bibtex, filename: "#{citation.bibtex_id}.bibtex", type: "text/plain", disposition: "attachment"
×
225
  end
226

227
  # POST /works/1/upload-files (called via Uppy)
228
  def upload_files
×
229
    @work = Work.find(params[:id])
×
230
    upload_service = WorkUploadsEditService.new(@work, current_user)
×
231
    upload_service.update_precurated_file_list(params["files"], [])
×
232
  end
233

234
  # Validates that the work is ready to be approved
235
  # GET /works/1/validate
236
  def validate
×
237
    @work = Work.find(params[:id])
×
238
    @work.complete_submission!(current_user)
×
239
    redirect_to user_path(current_user)
×
240
  end
241

242
  private
×
243

244
    # Extract the Work ID parameter
245
    # @return [String]
246
    def work_id_param
×
247
      params[:id]
×
248
    end
249

250
    # Find the Work requested by ID
251
    # @return [Work]
252
    def work
×
253
      Work.find(work_id_param)
×
254
    end
255

256
    # Determine whether or not the request is for the :index action in the RSS
257
    # response format
258
    # This is to enable PDC Discovery to index approved content via the RSS feed
259
    def rss_index_request?
×
260
      action_name == "index" && request.format.symbol == :rss
×
261
    end
262

263
    # Determine whether or not the request is for the :show action in the JSON
264
    # response format
265
    # @return [Boolean]
266
    def json_show_request?
×
267
      action_name == "show" && request.format.symbol == :json
×
268
    end
269

270
    # Determine whether or not the requested Work has been approved
271
    # @return [Boolean]
272
    def work_approved?
×
273
      work&.state == "approved"
×
274
    end
275

276
    ##
277
    # Public requests are requests that do not require authentication.
278
    # This is to enable PDC Discovery to index approved content via the RSS feed
279
    # and .json calls to individual works without needing to log in as a user.
280
    # Note that only approved works can be fetched for indexing.
281
    def public_request?
×
282
      return true if rss_index_request?
×
283
      return true if json_show_request? && work_approved?
×
284
      false
×
285
    end
286

287
    def work_params
×
288
      params[:work] || {}
×
289
    end
290

291
    # @note No testing coverage but not a route, not called
292
    def patch_params
×
293
      return {} unless params.key?(:patch)
×
294

295
      params[:patch]
×
296
    end
297

298
    # @note No testing coverage but not a route, not called
299
    def pre_curation_uploads_param
×
300
      return if patch_params.nil?
×
301

302
      patch_params[:pre_curation_uploads]
×
303
    end
304

305
    # @note No testing coverage but not a route, not called
306
    def readme_file_param
×
307
      return if patch_params.nil?
×
308

309
      patch_params[:readme_file]
×
310
    end
311

312
    # @note No testing coverage but not a route, not called
313
    def rescue_aasm_error
×
314
      super
×
315
    rescue StandardError => generic_error
316
      if action_name == "create"
×
317
        handle_error_for_create(generic_error)
×
318
      else
319
        redirect_to error_url, notice: "We apologize, an error was encountered: #{generic_error.message}. Please contact the PDC Describe administrators."
×
320
      end
321
    end
322

323
    rescue_from StandardError do |generic_error|
×
324
      Honeybadger.notify("We apologize, an error was encountered: #{generic_error.message}.")
×
325
      redirect_to error_url, notice: "We apologize, an error was encountered: #{generic_error.message}. Please contact the PDC Describe administrators."
×
326
    end
327

328
    # @note No testing coverage but not a route, not called
329
    def handle_error_for_create(generic_error)
×
330
      if @work.persisted?
×
331
        Honeybadger.notify("Failed to create the new Dataset #{@work.id}: #{generic_error.message}")
×
332
        @form_resource_decorator = FormResourceDecorator.new(@work, current_user)
×
333
        redirect_to edit_work_url(id: @work.id), notice: "Failed to create the new Dataset #{@work.id}: #{generic_error.message}", params:
×
334
      else
335
        Honeybadger.notify("Failed to create a new Dataset #{@work.id}: #{generic_error.message}")
×
336
        new_params = {}
×
337
        new_params[:wizard] = wizard_mode? if wizard_mode?
×
338
        new_params[:migrate] = migrating? if migrating?
×
339
        @form_resource_decorator = FormResourceDecorator.new(@work, current_user)
×
340
        redirect_to new_work_url(params: new_params), notice: "Failed to create a new Dataset: #{generic_error.message}", params: new_params
×
341
      end
342
    end
343

344
    # @note No testing coverage but not a route, not called
345
    def redirect_aasm_error(transition_error_message)
×
346
      if @work.persisted?
×
347
        redirect_to edit_work_url(id: @work.id), notice: transition_error_message, params:
×
348
      else
349
        new_params = {}
×
350
        new_params[:wizard] = wizard_mode? if wizard_mode?
×
351
        new_params[:migrate] = migrating? if migrating?
×
352
        @form_resource_decorator = FormResourceDecorator.new(@work, current_user)
×
353
        redirect_to new_work_url(params: new_params), notice: transition_error_message, params: new_params
×
354
      end
355
    end
356

357
    # @note No testing coverage but not a route, not called
358
    def error_action
×
359
      @form_resource_decorator = FormResourceDecorator.new(@work, current_user)
×
360
      if action_name == "create"
×
361
        :new
×
362
      elsif action_name == "validate"
×
363
        :edit
×
364
      elsif action_name == "new_submission"
×
365
        :new_submission
×
366
      else
367
        @work_decorator = WorkDecorator.new(@work, current_user)
×
368
        :show
×
369
      end
370
    end
371

372
    def wizard_mode?
×
373
      params[:wizard] == "true"
×
374
    end
375

376
    def update_work
×
377
      upload_service = WorkUploadsEditService.new(@work, current_user)
×
378
      if @work.approved?
×
379
        upload_keys = deleted_files_param || []
×
380
        deleted_uploads = upload_service.find_post_curation_uploads(upload_keys:)
×
381

382
        return head(:forbidden) unless deleted_uploads.empty?
×
383
      else
384
        @work = upload_service.update_precurated_file_list(added_files_param, deleted_files_param)
×
385
      end
386

387
      process_updates
×
388
    end
389

390
    def added_files_param
×
391
      Array(work_params[:pre_curation_uploads_added])
×
392
    end
393

394
    def deleted_files_param
×
395
      deleted_count = (work_params["deleted_files_count"] || "0").to_i
×
396
      (1..deleted_count).map { |i| work_params["deleted_file_#{i}"] }.select(&:present?)
×
397
    end
398

399
    def process_updates
×
400
      if WorkCompareService.update_work(work: @work, update_params:, current_user:)
×
401
        redirect_to work_url(@work), notice: "Work was successfully updated."
×
402
      else
403
        # This is needed for rendering HTML views with validation errors
404
        @uploads = @work.uploads
×
405
        @form_resource_decorator = FormResourceDecorator.new(@work, current_user)
×
406
        @work_decorator = WorkDecorator.new(@work, current_user)
×
407

408
        # return 200 so the loadbalancer doesn't capture the error
409
        render :edit
×
410
      end
411
    end
412

413
    def migrated?
×
414
      return false unless params.key?(:submit)
×
415

416
      params[:submit] == "Migrate"
×
417
    end
418

419
    # Returns a hash object that can be serialized into something that DataTables
420
    # can consume. The `data` elements includes the work's file list all other
421
    # properties are used for displaying different data elements related but not
422
    # directly on the DataTable object (e.g. the total file size)
423
    def file_list_ajax_response(work)
×
424
      files = []
×
425
      total_size = 0
×
426
      unless work.nil?
×
427
        files = work.file_list
×
428
        total_size = work.total_file_size_from_list(files)
×
429
      end
430
      {
431
        data: files,
×
432
        total_size:,
433
        total_size_display: ActiveSupport::NumberHelper.number_to_human_size(total_size),
434
        total_file_count: files.count
435
      }
436
    end
437
end
438
# 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