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

pulibrary / pdc_describe / 9dbcf7a4-1c56-4510-9614-74ad5a22cff6

31 Jul 2024 02:46PM UTC coverage: 1.08% (-95.1%) from 96.17%
9dbcf7a4-1c56-4510-9614-74ad5a22cff6

push

circleci

jrgriffiniii
wip

52 of 4814 relevant lines covered (1.08%)

0.01 hits per line

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

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

3
require "nokogiri"
×
4
require "open-uri"
×
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
×
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
      render :new, status: :unprocessable_entity
×
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
×
69
    @work = Work.find(params[:id])
×
70
    UpdateSnapshotJob.perform_later(work_id: @work.id, last_snapshot_id: work.upload_snapshots.first&.id)
×
71
    @work_decorator = WorkDecorator.new(@work, current_user)
×
72

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

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

86
  # only non wizard mode
87
  def file_list
×
88
    if params[:id] == "NONE"
×
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: []
×
92
    else
×
93
      @work = Work.find(params[:id])
×
94
      render json: @work.file_list
×
95
    end
×
96
  end
×
97

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

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

108
  # GET /works/1/edit
109
  # only non wizard mode
110
  def edit
×
111
    @work = Work.find(params[:id])
×
112
    @work_decorator = WorkDecorator.new(@work, current_user)
×
113
    if validate_modification_permissions(work: @work,
×
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
×
117
      @form_resource_decorator = FormResourceDecorator.new(@work, current_user)
×
118
    end
×
119
  end
×
120

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

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

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

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

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

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

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

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

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

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

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

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

204
    params[:migrate]
×
205
  end
×
206
  helper_method :migrating?
×
207

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

217
  # POST /works/1/upload-files (called via Uppy)
218
  def upload_files
×
219
    @work = Work.find(params[:id])
×
220
    upload_service = WorkUploadsEditService.new(@work, current_user)
×
221
    upload_service.update_precurated_file_list(params["files"], [])
×
222
  end
×
223

224
  # Validates that the work is ready to be approved
225
  # GET /works/1/validate
226
  def validate
×
227
    @work = Work.find(params[:id])
×
228
    @work.complete_submission!(current_user)
×
229
    redirect_to user_path(current_user)
×
230
  end
×
231

232
  private
×
233

234
    # Extract the Work ID parameter
235
    # @return [String]
236
    def work_id_param
×
237
      params[:id]
×
238
    end
×
239

240
    # Find the Work requested by ID
241
    # @return [Work]
242
    def work
×
243
      Work.find(work_id_param)
×
244
    end
×
245

246
    # Determine whether or not the request is for the :index action in the RSS
247
    # response format
248
    # This is to enable PDC Discovery to index approved content via the RSS feed
249
    def rss_index_request?
×
250
      action_name == "index" && request.format.symbol == :rss
×
251
    end
×
252

253
    # Determine whether or not the request is for the :show action in the JSON
254
    # response format
255
    # @return [Boolean]
256
    def json_show_request?
×
257
      action_name == "show" && request.format.symbol == :json
×
258
    end
×
259

260
    # Determine whether or not the requested Work has been approved
261
    # @return [Boolean]
262
    def work_approved?
×
263
      work&.state == "approved"
×
264
    end
×
265

266
    ##
267
    # Public requests are requests that do not require authentication.
268
    # This is to enable PDC Discovery to index approved content via the RSS feed
269
    # and .json calls to individual works without needing to log in as a user.
270
    # Note that only approved works can be fetched for indexing.
271
    def public_request?
×
272
      return true if rss_index_request?
×
273
      return true if json_show_request? && work_approved?
×
274
      false
×
275
    end
×
276

277
    def work_params
×
278
      params[:work] || {}
×
279
    end
×
280

281
    # @note No testing coverage but not a route, not called
282
    def patch_params
×
283
      return {} unless params.key?(:patch)
×
284

285
      params[:patch]
×
286
    end
×
287

288
    # @note No testing coverage but not a route, not called
289
    def pre_curation_uploads_param
×
290
      return if patch_params.nil?
×
291

292
      patch_params[:pre_curation_uploads]
×
293
    end
×
294

295
    # @note No testing coverage but not a route, not called
296
    def readme_file_param
×
297
      return if patch_params.nil?
×
298

299
      patch_params[:readme_file]
×
300
    end
×
301

302
    # @note No testing coverage but not a route, not called
303
    def rescue_aasm_error
×
304
      super
×
305
    rescue StandardError => generic_error
×
306
      if action_name == "create"
×
307
        handle_error_for_create(generic_error)
×
308
      else
×
309
        redirect_to root_url, notice: "We apologize, an error was encountered: #{generic_error.message}. Please contact the PDC Describe administrators."
×
310
      end
×
311
    end
×
312

313
    # @note No testing coverage but not a route, not called
314
    def handle_error_for_create(generic_error)
×
315
      if @work.persisted?
×
316
        Honeybadger.notify("Failed to create the new Dataset #{@work.id}: #{generic_error.message}")
×
317
        @form_resource_decorator = FormResourceDecorator.new(@work, current_user)
×
318
        redirect_to edit_work_url(id: @work.id), notice: "Failed to create the new Dataset #{@work.id}: #{generic_error.message}", params:
×
319
      else
×
320
        Honeybadger.notify("Failed to create a new Dataset #{@work.id}: #{generic_error.message}")
×
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)
×
325
        redirect_to new_work_url(params: new_params), notice: "Failed to create a new Dataset: #{generic_error.message}", params: new_params
×
326
      end
×
327
    end
×
328

329
    # @note No testing coverage but not a route, not called
330
    def redirect_aasm_error(transition_error_message)
×
331
      if @work.persisted?
×
332
        redirect_to edit_work_url(id: @work.id), notice: transition_error_message, params:
×
333
      else
×
334
        new_params = {}
×
335
        new_params[:wizard] = wizard_mode? if wizard_mode?
×
336
        new_params[:migrate] = migrating? if migrating?
×
337
        @form_resource_decorator = FormResourceDecorator.new(@work, current_user)
×
338
        redirect_to new_work_url(params: new_params), notice: transition_error_message, params: new_params
×
339
      end
×
340
    end
×
341

342
    # @note No testing coverage but not a route, not called
343
    def error_action
×
344
      @form_resource_decorator = FormResourceDecorator.new(@work, current_user)
×
345
      if action_name == "create"
×
346
        :new
×
347
      elsif action_name == "validate"
×
348
        :edit
×
349
      elsif action_name == "new_submission"
×
350
        :new_submission
×
351
      else
×
352
        @work_decorator = WorkDecorator.new(@work, current_user)
×
353
        :show
×
354
      end
×
355
    end
×
356

357
    def wizard_mode?
×
358
      params[:wizard] == "true"
×
359
    end
×
360

361
    def update_work
×
362
      upload_service = WorkUploadsEditService.new(@work, current_user)
×
363
      if @work.approved?
×
364
        upload_keys = deleted_files_param || []
×
365
        deleted_uploads = upload_service.find_post_curation_uploads(upload_keys:)
×
366

367
        return head(:forbidden) unless deleted_uploads.empty?
×
368
      else
×
369
        @work = upload_service.update_precurated_file_list(added_files_param, deleted_files_param)
×
370
      end
×
371

372
      process_updates
×
373
    end
×
374

375
    def added_files_param
×
376
      Array(work_params[:pre_curation_uploads_added])
×
377
    end
×
378

379
    def deleted_files_param
×
380
      deleted_count = (work_params["deleted_files_count"] || "0").to_i
×
381
      (1..deleted_count).map { |i| work_params["deleted_file_#{i}"] }.select(&:present?)
×
382
    end
×
383

384
    def process_updates
×
385
      if WorkCompareService.update_work(work: @work, update_params:, current_user:)
×
386
        redirect_to work_url(@work), notice: "Work was successfully updated."
×
387
      else
×
388
        # This is needed for rendering HTML views with validation errors
389
        @uploads = @work.uploads
×
390
        @form_resource_decorator = FormResourceDecorator.new(@work, current_user)
×
391

392
        render :edit, status: :unprocessable_entity
×
393
      end
×
394
    end
×
395

396
    def migrated?
×
397
      return false unless params.key?(:submit)
×
398

399
      params[:submit] == "Migrate"
×
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