-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathplans_controller.rb
More file actions
596 lines (535 loc) · 21.8 KB
/
plans_controller.rb
File metadata and controls
596 lines (535 loc) · 21.8 KB
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
# frozen_string_literal: true
# Controller for the Write plan and create plan pages
# rubocop:disable Metrics/ClassLength
class PlansController < ApplicationController
include ConditionalUserMailer
include OrgSelectable
helper PaginableHelper
helper SettingsTemplateHelper
after_action :verify_authorized, except: [:overview]
# GET /plans
# rubocop:disable Metrics/AbcSize
def index
authorize Plan
@plans = Plan.includes(:roles).active(current_user).page(1)
@organisationally_or_publicly_visible = if current_user.org.is_other?
[]
else
Plan.organisationally_or_publicly_visible(current_user).page(1)
end
# TODO: Is this still used? We cannot switch this to use the :plan_params
# strong params because any calls that do not include `plan` in the
# query string will fail
@template = Template.find(params[:plan][:template_id]) if params[:plan].present?
end
# rubocop:enable Metrics/AbcSize
# GET /plans/new
def new
@plan = Plan.new
authorize @plan
org_id = current_user.org&.id
# Get templates grouped hash
@templates_grouped = templates_available_to_org_user(org_id)
respond_to :html
end
# POST /plans
# rubocop:disable Metrics/AbcSize, Metrics/MethodLength
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
def create
@plan = Plan.new
authorize @plan
# If the template_id is blank then we need to look up the available templates and
# return JSON
if plan_params[:template_id].blank?
# Something went wrong there should always be a template id
respond_to do |format|
flash[:alert] = _('Unable to identify a suitable template for your plan.')
format.html { redirect_to new_plan_path }
end
else
template_id = plan_params[:template_id].to_i
unless validate_template_available_to_org_user?(template_id, current_user.org_id)
respond_to do |format|
flash[:alert] = _('The selected template is not available to your organisation.')
format.html { redirect_to new_plan_path }
end
return
end
@plan.visibility = if plan_params['visibility'].blank?
Rails.configuration.x.plans.default_visibility
else
plan_params[:visibility]
end
@plan.template = Template.find(plan_params[:template_id])
@plan.title = if plan_params[:title].blank?
if current_user.firstname.blank?
format(_('My Plan (%{title})'), title: @plan.template.title)
else
format(_('%{user_name} Plan'), user_name: "#{current_user.firstname}'s")
end
else
plan_params[:title]
end
# bit of hackery here. There are 2 org selectors on the page
# and each is within its own specific context, plan.org or
# plan.funder which forces the hidden id hash to be :id
# so we need to convert it to :org_id so it works with the
# OrgSelectable and OrgSelection services
if plan_params[:org].present? && plan_params[:org][:id].present?
attrs = plan_params[:org]
attrs[:org_id] = attrs[:id]
@plan.org = org_from_params(params_in: attrs, allow_create: false)
else
# The user did not specify a research Org, so default to their Org
@plan.org = current_user.org
end
if plan_params[:funder].present? && plan_params[:funder][:id].present?
attrs = plan_params[:funder]
attrs[:org_id] = attrs[:id]
@plan.funder = org_from_params(params_in: attrs, allow_create: false)
end
if @plan.save
# pre-select org's guidance and the default org's guidance
ids = (Org.default_orgs.pluck(:id) << @plan.org_id).flatten.uniq
ggs = GuidanceGroup.where(org_id: ids, optional_subset: false, published: true)
@plan.guidance_groups << ggs unless ggs.empty?
default = Template.default
msg = "#{success_message(@plan, _('created'))}<br />"
if !default.nil? && default == @plan.template
# We used the generic/default template
msg += " #{_('This plan is based on the default template.')}"
elsif !@plan.template.customization_of.nil?
# We used a customized version of the the funder template
# rubocop:disable Layout/LineLength
msg += " #{_('This plan is based on the')} #{@plan.funder&.name}: '#{@plan.template.title}' #{_('template with customisations by the')} #{@plan.template.org.name}"
# rubocop:enable Layout/LineLength
else
# We used the specified org's or funder's template
msg += " #{_('This plan is based on the')} #{@plan.template.org.name}: '#{@plan.template.title}' template."
end
@plan.add_user!(current_user.id, :creator)
# Set new identifier to plan id by default on create.
# (This may be changed by user.)
@plan.identifier = @plan.id.to_s
@plan.save
respond_to do |format|
flash[:notice] = msg
format.html { redirect_to plan_path(@plan) }
end
else
# Something went wrong so report the issue to the user
respond_to do |format|
flash[:alert] = failure_message(@plan, _('create'))
format.html { redirect_to new_plan_path }
end
end
end
end
# rubocop:enable Metrics/AbcSize, Metrics/MethodLength
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
# GET /plans/show
# rubocop:disable Metrics/AbcSize, Metrics/MethodLength
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
def show
@plan = Plan.includes(
:guidance_groups, template: [:phases]
).find(params[:id])
authorize @plan
@visibility = if @plan.visibility.present?
@plan.visibility.to_s
else
Rails.configuration.x.plans.default_visibility
end
# Get all of the available funders
@funders = Org.funder
.joins(:templates)
.where(templates: { published: true }).uniq.sort_by(&:name)
# TODO: Seems strange to do this. Why are we just not using an `edit` route?
@editing = !params[:editing].nil? && @plan.administerable_by?(current_user.id)
# Get all Guidance Groups applicable for the plan and group them by org
@all_guidance_groups = @plan.guidance_group_options
@all_ggs_grouped_by_org = @all_guidance_groups.sort.group_by(&:org)
@selected_guidance_groups = @plan.guidance_groups
# Important ones come first on the page - we grab the user's org's GGs and
# "Organisation" org type GGs
@important_ggs = []
if @all_ggs_grouped_by_org.include?(current_user.org)
@important_ggs << [current_user.org, @all_ggs_grouped_by_org[current_user.org]]
end
@default_orgs = Org.default_orgs
@all_ggs_grouped_by_org.each do |org, ggs|
# @default_orgs and already selected guidance groups are important.
if (@default_orgs.include?(org) || ggs.intersect?(@selected_guidance_groups)) && !@important_ggs.include?([org,
ggs])
@important_ggs << [org, ggs]
end
end
# Sort the rest by org name for the accordion
@important_ggs = @important_ggs.sort_by { |org, _gg| (org.nil? ? '' : org.name) }
@all_ggs_grouped_by_org = @all_ggs_grouped_by_org.sort_by do |org, _gg|
(org.nil? ? '' : org.name)
end
@selected_guidance_groups = @selected_guidance_groups.ids
@based_on = if @plan.template.customization_of.nil?
@plan.template
else
Template.where(family_id: @plan.template.customization_of).first
end
@research_domains = ResearchDomain.all.order(:label)
respond_to :html
end
# rubocop:enable Metrics/AbcSize, Metrics/MethodLength
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
# TODO: This feels like it belongs on a phases controller, perhaps introducing
# a non-namespaces phases_controller woulld make sense here. Consider
# doing this when we refactor the Plan editing UI
# GET /plans/:plan_id/phases/:id/edit
# rubocop:disable Metrics/AbcSize
def edit
plan = Plan.includes(
{ template: {
phases: {
sections: {
questions: %i[question_format annotations]
}
}
} },
{ answers: :notes }
)
.find(params[:id])
authorize plan
phase_id = params[:phase_id].to_i
phase = plan.template.phases.find { |p| p.id == phase_id }
raise ActiveRecord::RecordNotFound if phase.nil?
guidance_groups = GuidanceGroup.where(published: true, id: plan.guidance_group_ids)
render_phases_edit(plan, phase, guidance_groups)
end
# rubcocop:enable Metrics/AbcSize
# PUT /plans/1
# rubocop:disable Metrics/MethodLength, Metrics/PerceivedComplexity
def update
@plan = Plan.find(params[:id])
authorize @plan
attrs = plan_params
# rubocop:disable Metrics/BlockLength
respond_to do |format|
# TODO: See notes below on the pan_params definition. We should refactor
# this once the UI pages have been reworked
# Save the guidance group selections
guidance_group_ids = if params[:guidance_group_ids].blank?
[]
else
params[:guidance_group_ids].map(&:to_i).uniq
end
@plan.guidance_groups = GuidanceGroup.where(id: guidance_group_ids)
# TODO: For some reason the `fields_for` isn't adding the
# appropriate namespace, so org_id represents our funder
funder_attrs = plan_params[:funder]
funder_attrs[:org_id] = plan_params[:funder][:id]
funder = org_from_params(params_in: funder_attrs)
@plan.funder_id = funder&.id
@plan.grant = plan_params[:grant]
attrs.delete(:funder)
attrs.delete(:grant)
attrs = remove_org_selection_params(params_in: attrs)
if @plan.update(attrs) # _attributes(attrs)
format.html do
redirect_to plan_path(@plan),
notice: success_message(@plan, _('saved'))
end
format.json do
render json: { code: 1, msg: success_message(@plan, _('saved')) }
end
else
format.html do
# TODO: Should do a `render :show` here instead but show defines too many
# instance variables in the controller
redirect_to plan_path(@plan).to_s, alert: failure_message(@plan, _('save'))
end
format.json do
render json: { code: 0, msg: failure_message(@plan, _('save')) }
end
end
rescue StandardError => e
flash[:alert] = failure_message(@plan, _('save'))
format.html do
Rails.logger.error "Unable to save plan #{@plan&.id} - #{e.message}"
redirect_to plan_path(@plan).to_s, alert: failure_message(@plan, _('save'))
end
format.json do
render json: { code: 0, msg: flash[:alert] }
end
end
# rubocop:enable Metrics/BlockLength
end
# rubocop:enable Metrics/AbcSize, Metrics/MethodLength, Metrics/PerceivedComplexity
# GET /plans/:id/share
def share
@plan = Plan.find(params[:id])
if @plan.present?
authorize @plan
@plan_roles = @plan.roles.where(active: true)
else
redirect_to(plans_path)
end
end
# TODO: Does this belong on the Roles or FeedbackRequest controllers
# as a PUT verb?
# GET /plans/:id/request_feedback
def request_feedback
@plan = Plan.find(params[:id])
if @plan.present?
authorize @plan
@plan_roles = @plan.roles.where(active: true)
else
redirect_to(plans_path)
end
end
# DELETE /plans/:id
# rubocop:disable Metrics/AbcSize
def destroy
@plan = Plan.find(params[:id])
authorize @plan
if @plan.destroy
respond_to do |format|
format.html do
redirect_to plans_url,
notice: success_message(@plan, _('deleted'))
end
end
else
respond_to do |format|
flash[:alert] = failure_message(@plan, _('delete'))
format.html { render action: 'edit' }
end
end
end
# rubocop:enable Metrics/AbcSize
# TODO: Is this used? It seems like it belongs on the answers controller
# GET /plans/:id/answer
# rubocop:disable Metrics/AbcSize
def answer
@plan = Plan.find(params[:id])
authorize @plan
if params[:q_id].nil?
respond_to do |format|
format.json { render json: {} }
end
else
respond_to do |format|
format.json do
render json: @plan.answer(params[:q_id], false).to_json(include: :options)
end
end
end
end
# rubocop:enable Metrics/AbcSize
# GET /plans/:id/download
def download
@plan = Plan.find(params[:id])
authorize @plan
@phase_options = @plan.phases.order(:number).pluck(:title, :id)
@phase_options.insert(0, ['All phases', 'All']) if @phase_options.length > 1
@export_settings = @plan.settings(:export)
render 'download'
end
# POST /plans/:id/duplicate
# rubocop:disable Metrics/AbcSize
def duplicate
plan = Plan.find(params[:id])
authorize plan
@plan = Plan.deep_copy(plan)
respond_to do |format|
if @plan.save
@plan.add_user!(current_user.id, :creator)
format.html { redirect_to @plan, notice: success_message(@plan, _('copied')) }
else
format.html { redirect_to plans_path, alert: failure_message(@plan, _('copy')) }
end
end
end
# rubocop:enable Metrics/AbcSize
# TODO: This should probablly just be merged with the update route
# POST /plans/:id/visibility
# rubocop:disable Metrics/AbcSize, Metrics/MethodLength
def visibility
plan = Plan.find(params[:id])
if plan.present?
authorize plan
if plan.visibility_allowed?
plan.visibility = plan_params[:visibility]
if plan.save
deliver_if(recipients: plan.owner_and_coowners,
key: 'owners_and_coowners.visibility_changed') do |r|
UserMailer.plan_visibility(r, plan).deliver_now
end
render status: :ok,
json: { msg: success_message(plan, _('updated')) }
else
render status: :internal_server_error,
json: { msg: failure_message(plan, _('update')) }
end
else
# rubocop:disable Layout/LineLength
render status: :forbidden, json: {
msg: format(_("Unable to change the plan's status since it is needed at least %{percentage} percentage responded"), percentage: Rails.configuration.x.plans.default_percentage_answered)
}
# rubocop:enable Layout/LineLength
end
else
render status: :not_found,
json: { msg: format(_('Unable to find plan id %{plan_id}'),
plan_id: params[:id]) }
end
end
# rubocop:enable Metrics/AbcSize, Metrics/MethodLength
# TODO: This should probablly just be merged with the update route
# POST /plans/:id/set_test
def set_test
plan = Plan.find(params[:id])
authorize plan
plan.visibility = (params[:is_test] == '1' ? :is_test : :privately_visible)
if plan.save
render json: {
code: 1,
msg: (plan.is_test? ? _('Your project is now a test.') : _('Your project is no longer a test.'))
}
else
render status: :bad_request, json: {
code: 0, msg: _("Unable to change the plan's test status")
}
end
end
# GET /plans/:id/overview
def overview
plan = Plan.includes(template: [:org, { phases: { sections: :questions } }])
.find(params[:id])
authorize plan
render(:overview, locals: { plan: plan })
rescue ActiveRecord::RecordNotFound
flash[:alert] = format(_('There is no plan associated with id %{<id}>s'), id: params[:id])
redirect_to(action: :index)
end
# ============================
# = Private instance methods =
# ============================
private
def plan_params
# TODO: The guidance_group_ids setup on the form is a bit convoluted. Refactor
# it once we've started updating the UI for these pages. There should
# probably be a separate controller and set the checkboxes to use `remote: true`
params.require(:plan)
.permit(:template_id, :title, :visibility, :description, :identifier,
:start_date, :end_date, :org_id, :org_name, :org_crosswalk,
:ethical_issues, :ethical_issues_description, :ethical_issues_report,
:research_domain_id, :funding_status,
grant: %i[name value],
org: %i[id org_id org_name org_sources org_crosswalk],
funder: %i[id org_id org_name org_sources org_crosswalk])
end
# different versions of the same template have the same family_id
# but different version numbers so for each set of templates with the
# same family_id choose the highest version number.
def get_most_recent(templates)
groups = {}
templates.each do |t|
k = t.family_id
if groups.key?(k)
other = groups[k]
groups[k] = t if other.version < t.version
else
groups[k] = t
end
end
groups.values
end
# find all object under src_plan_key
# merge them into the items under obj_plan_key using
# super_id = id
# so we have answers which each have a question_id
# rollup(plan, "answers", "quesiton_id", "questions")
# will put the answers into the right questions.
def rollup(plan, src_plan_key, super_id, obj_plan_key)
id_to_obj = {}
plan[src_plan_key].each do |o|
id = o[super_id]
id_to_obj[id] = [] unless id_to_obj.key?(id)
id_to_obj[id] << o
end
plan[obj_plan_key].each do |o|
id = o['id']
o[src_plan_key] = id_to_obj[id] if id_to_obj.key?(id)
end
plan.delete(src_plan_key)
end
def render_phases_edit(plan, phase, guidance_groups)
readonly = !plan.editable_by?(current_user.id)
# Since the answers have been pre-fetched through plan (see Plan.load_for_phase)
# we create a hash whose keys are question id and value is the answer associated
answers = plan.answers.each_with_object({}) { |a, m| m[a.question_id] = a }
render('/phases/edit', locals: {
base_template_org: phase.template.base_org,
plan: plan,
phase: phase,
readonly: readonly,
guidance_groups: guidance_groups,
answers: answers,
guidance_presenter: GuidancePresenter.new(plan)
})
end
# Get templates available to org users
# rubocop:disable Metrics/AbcSize, Metrics/MethodLength, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
def templates_available_to_org_user(org_id)
# looks into the list of families of templates
customizations = Template.latest_customized_version_per_org(org_id)
customization_ids = customizations.select(&:published?).collect(&:customization_of)
# get templates of user's own org
user_org_own_templates = Template.organisationally_visible
.where(org_id: org_id, customization_of: nil)
.published
.uniq.sort_by(&:title)
# get templates of user's customised org
user_org_custom_templates = Template.latest_customized_version_per_org(org_id)
.published
.uniq.sort_by(&:title)
# get funder templates no customised templates
funder_non_customised_templates = Template.published
.joins(:org)
.where(orgs: { org_type: Org.org_type_values_for(:funder) })
# The next line removes templates that belong to a family that
# has customised templates
.where.not(family_id: customization_ids)
.uniq.sort_by(&:title)
# get global templates
global_templates = Template.published
.where(is_default: true)
# The next line removes templates that belong to a family that
# has customised templates
.where.not(family_id: customization_ids)
.uniq.sort_by(&:title)
# create templates-grouped hash
@templates_grouped = {
_("Your Organisation's Templates:") => user_org_own_templates.map do |t|
[t.title, t.id]
end,
_("Your Organisation's Customised Templates:") => user_org_custom_templates.map do |t|
[t.title, t.id]
end,
_('Global Templates:') => global_templates.map do |t|
[t.title, t.id]
end,
_('Funder Templates:') => funder_non_customised_templates.map do |t|
[t.title, t.id]
end
}.reject { |_, val| val.empty? }
end
# rubocop:enable Metrics/AbcSize, Metrics/MethodLength, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
# Validate that a template_id is available to the org user
def validate_template_available_to_org_user?(template_id, org_id)
return false if template_id.blank? || org_id.blank?
available_templates = templates_available_to_org_user(org_id)
available_template_ids = available_templates.values.flat_map { |group| group.map(&:last) }
available_template_ids.include?(template_id.to_i)
end
end
# rubocop:enable Metrics/ClassLength