Class: LcpRuby::ResourcesController

Inherits:
ApplicationController show all
Includes:
AssociationOptionsBuilder, AuthorizedController, DialogRendering, FormActionExecution, PageAuthorization, ZoneResolution
Defined in:
app/controllers/lcp_ruby/resources_controller.rb

Constant Summary

Constants included from PageAuthorization

PageAuthorization::MISCONFIGURED_CODES

Constants included from FormActionExecution

FormActionExecution::VALID_FORM_ACTION_REDIRECTS

Constants included from DialogRendering

DialogRendering::DIALOG_PASS_THROUGH_KEYS

Constants included from AssociationOptionsBuilder

AssociationOptionsBuilder::MAX_SELECT_OPTIONS

Constants included from Controller::BearerAuthentication

Controller::BearerAuthentication::BASIC_PREFIX_LENGTH, Controller::BearerAuthentication::BEARER_PREFIX_LENGTH

Instance Method Summary collapse

Methods included from PageAuthorization

before_action_filter_names

Methods included from FormActionExecution

#apply_set_fields!, #current_form_actions, #dispatch_deferred_events, #execute_form_action_pipeline, #form_action_dialog_behavior, #form_action_redirect_path, #pipeline_flash_message, #pipeline_redirect_path, #resolve_form_action

Methods included from DialogRendering

#composite_dialog?, #defaults_from_params, #dialog_context?, #dialog_form_url, #dialog_locals, #dialog_pass_through_params, #partial_for_dialog_result_style, #render_composite_dialog_form, #render_dialog_form, #render_dialog_form_with_errors, #render_dialog_result, #render_dialog_success, #resolved_dialog_config, #resolved_dialog_page

Methods included from Controller::Authorization

#current_evaluator

Instance Method Details

#batch_countObject



398
399
400
401
402
403
404
# File 'app/controllers/lcp_ruby/resources_controller.rb', line 398

def batch_count
  authorize @model_class, "index?"
  scope = policy_scope(@model_class)
  scope = apply_soft_delete_scope(scope)
  scope = apply_advanced_search(scope)
  render json: { count: scope.count }
end

#batch_selectionObject



506
507
508
509
510
511
512
513
# File 'app/controllers/lcp_ruby/resources_controller.rb', line 506

def batch_selection
  authorize @model_class, "index?"
  ids = params[:ids] || []
  token = SecureRandom.uuid
  session[:batch_selections] ||= {}
  session[:batch_selections][token] = ids.map(&:to_s)
  render json: { token: token }
end

#createObject



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
# File 'app/controllers/lcp_ruby/resources_controller.rb', line 161

def create
  return head(:not_found) if api_model?
  @record = @model_class.new(permitted_params)
  authorize @record
  fa_config = resolve_form_action(@record)

  process_json_field_params(@record)
  validate_association_values!(@record)
  apply_set_fields!(@record, fa_config)

  if @record.errors.any?
    return render_create_failure
  end

  result = execute_form_action_pipeline(@record, fa_config)

  if result.success?
    dispatch_deferred_events(result)
    broadcast_model_change(current_model_definition.name)

    if dialog_context?
      behavior = form_action_dialog_behavior(fa_config)
      flash_msg = behavior == "reset" ? pipeline_flash_message("create", result) : nil
      return render_dialog_success(behavior, flash_message: flash_msg, result_config: fa_config["result"])
    end

    redirect_to pipeline_redirect_path("create", fa_config, @record, result),
      status: :see_other,
      notice: pipeline_flash_message("create", result)
  else
    render_create_failure
  end
end

#destroyObject



250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# File 'app/controllers/lcp_ruby/resources_controller.rb', line 250

def destroy
  return head(:not_found) if api_model?
  authorize @record
  if current_model_definition.soft_delete?
    @record.discard!(by: current_user)
  else
    @record.destroy!
  end

  broadcast_model_change(current_model_definition.name)

  notice_key = current_model_definition.soft_delete? ? "lcp_ruby.flash.archived" : "lcp_ruby.flash.deleted"
  default_msg = current_model_definition.soft_delete? ? "%{model} was successfully archived." : "%{model} was successfully deleted."
  redirect_to resources_path,
    notice: I18n.t(notice_key, model: current_model_definition.resolved_label, default: default_msg)
end

#editObject



195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'app/controllers/lcp_ruby/resources_controller.rb', line 195

def edit
  return head(:not_found) if api_model?
  authorize @record
  warn_missing_presenter_config(:form)
  @form_actions = current_form_actions(@record)

  if dialog_context?
    return render_dialog_form
  end

  @layout_builder = Presenter::LayoutBuilder.new(current_presenter, current_model_definition)
  load_edit_virtual_columns
  preload_associations(@record, :form)
  @record.strict_loading! if LcpRuby.configuration.strict_loading_enabled?
end

#evaluate_conditionsObject



362
363
364
365
366
# File 'app/controllers/lcp_ruby/resources_controller.rb', line 362

def evaluate_conditions
  authorize @record, :edit?
  @record.assign_attributes(permitted_params)
  render json: evaluate_service_conditions(@record)
end

#evaluate_conditions_newObject



368
369
370
371
372
# File 'app/controllers/lcp_ruby/resources_controller.rb', line 368

def evaluate_conditions_new
  @record = @model_class.new(permitted_params)
  authorize @record, :create?
  render json: evaluate_service_conditions(@record)
end

#execute_transitionObject



267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'app/controllers/lcp_ruby/resources_controller.rb', line 267

def execute_transition
  authorize @record, :update?

  transition_name = params[:transition_name]
  comment = params[:transition_comment]

  Workflow::TransitionExecutor.execute(
    @record, transition_name,
    user: current_user, evaluator: current_evaluator,
    comment: comment, triggered_by: "user"
  )

  redirect_to resource_path(@record), status: :see_other,
    notice: I18n.t("lcp_ruby.flash.transition_executed",
      transition: resolve_transition_label(transition_name),
      default: "Transition '%{transition}' executed successfully.")
rescue Workflow::CommentRequiredError
  redirect_to resource_path(@record), status: :see_other,
    alert: I18n.t("lcp_ruby.flash.transition_comment_required",
      default: "A comment is required for this transition.")
rescue Workflow::TransitionDeniedError => e
  redirect_to resource_path(@record), status: :see_other, alert: e.localized_message
end

#export_fieldsObject



406
407
408
409
410
411
412
413
414
415
416
417
# File 'app/controllers/lcp_ruby/resources_controller.rb', line 406

def export_fields
  authorize @model_class, "index?"
  head(:forbidden) and return unless current_evaluator.can_execute_action?(:export)

  tree = Export::FieldTreeBuilder.build(
    model_definition: current_model_definition,
    evaluator: current_evaluator,
    presenter: current_presenter,
    current_user: current_user
  )
  render json: tree
end

#export_profilesObject



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
# File 'app/controllers/lcp_ruby/resources_controller.rb', line 419

def export_profiles
  authorize @model_class, "index?"
  head(:forbidden) and return unless current_evaluator.can_execute_action?(:export)

  profile_model = LcpRuby.registry.model_for("export_profile")
  profiles = profile_model
    .for_presenter(current_presenter.name)
    .where(
      profile_model.arel_table[:visibility].eq("global")
        .or(profile_model.arel_table[:visibility].eq("role")
          .and(profile_model.arel_table[:target_role].in(current_evaluator.roles)))
        .or(profile_model.arel_table[:visibility].eq("personal")
          .and(profile_model.arel_table[:owner_id].eq(current_user&.id)))
    )
    .order(:profile_name)

  # Build field tree to detect stale fields
  field_tree = Export::FieldTreeBuilder.build(
    model_definition: current_model_definition,
    evaluator: current_evaluator,
    presenter: current_presenter,
    current_user: current_user
  )
  available_paths = collect_field_paths(field_tree)

  render json: profiles.map { |p|
    selected = Array(p.selected_fields)
    stale = selected - available_paths
    valid = selected - stale

    {
      id: p.id,
      profile_name: p.profile_name,
      format: p.format,
      selected_fields: valid,
      formatting_options: p.formatting_options,
      stale_fields: stale
    }
  }
rescue LcpRuby::Error
  render json: []
end

#filter_fieldsObject



387
388
389
390
391
392
393
394
395
396
# File 'app/controllers/lcp_ruby/resources_controller.rb', line 387

def filter_fields
  authorize @model_class, :index?

  builder = Search::FilterMetadataBuilder.new(current_presenter, current_model_definition, current_evaluator)
   = builder.build

  result = { fields: [:fields] }
  result[:scopes] = [:scopes] if [:scopes]&.any?
  render json: result
end

#import_fieldsObject



462
463
464
465
466
467
468
469
470
471
472
473
# File 'app/controllers/lcp_ruby/resources_controller.rb', line 462

def import_fields
  authorize @model_class, "index?"
  head(:forbidden) and return unless current_evaluator.can_execute_action?(:import)

  tree = Import::FieldTreeBuilder.build(
    model_definition: current_model_definition,
    evaluator: current_evaluator,
    presenter: current_presenter,
    current_user: current_user
  )
  render json: tree
end

#import_profilesObject



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
# File 'app/controllers/lcp_ruby/resources_controller.rb', line 475

def import_profiles
  authorize @model_class, "index?"
  head(:forbidden) and return unless current_evaluator.can_execute_action?(:import)

  profile_model = LcpRuby.registry.model_for("import_profile")
  profiles = profile_model
    .for_model(current_model_definition.name)
    .where(
      profile_model.arel_table[:visibility].eq("global")
        .or(profile_model.arel_table[:visibility].eq("role")
          .and(profile_model.arel_table[:target_role].in(current_evaluator.roles)))
        .or(profile_model.arel_table[:visibility].eq("personal")
          .and(profile_model.arel_table[:owner_id].eq(current_user&.id)))
    )
    .order(:profile_name)

  render json: profiles.map { |p|
    {
      id: p.id,
      profile_name: p.profile_name,
      strategy: p.strategy,
      match_attribute: p.match_attribute,
      column_mapping: p.column_mapping,
      lookup_config: p.lookup_config,
      parsing_options: p.parsing_options
    }
  }
rescue LcpRuby::Error
  render json: []
end

#indexObject



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
# File 'app/controllers/lcp_ruby/resources_controller.rb', line 25

def index
  if raw_format?
    return head :not_acceptable if raw_index_unsupported?
    return render_raw_index
  end

  # Standalone grid pages (dashboards) bypass normal CRUD authorization.
  # Page-level access is gated by LcpRuby::PageAuthorization (before_action
  # above), which calls skip_authorization on :allow so verify_authorized
  # sees authorization-having-happened.
  if current_page&.standalone? && current_page&.grid?
    load_dashboard
    return
  end

  # Composite pages may specify a separate index_presenter for index actions
  if current_page&.index_presenter
    @presenter_definition = LcpRuby.loader.presenter_definition(current_page.index_presenter)
  else
    # Check for index composite page — either the current page itself,
    # or an explicit composite page defined for this model
    @index_composite_page = if current_page&.index_composite?
      current_page
    else
      find_index_composite_for_model
    end

    if @index_composite_page
      @presenter_definition = LcpRuby.loader.presenter_definitions[@index_composite_page.main_presenter_name]
      authorize @model_class
      load_index_composite
      return
    end
  end

  authorize @model_class

  if api_model?
    load_api_index
    return
  end

  scope = policy_scope(@model_class)
  scope = apply_soft_delete_scope(scope)

  apply_default_saved_filter!

  if current_presenter.index_render_with
    load_flat_index(scope)
  else
    case current_presenter.index_layout
    when :tree
      load_tree_index(scope) if current_model_definition.tree?
    when :grouped
      load_grouped_index(scope)
    when :tiles
      load_flat_index(scope)
    when :kanban
      load_kanban_index(scope)
    else
      load_flat_index(scope)
    end
  end
end

#inline_createObject



632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
# File 'app/controllers/lcp_ruby/resources_controller.rb', line 632

def inline_create
  target_model_name = params[:target_model]
  return head(:bad_request) unless target_model_name.present?

  target_model_def = LcpRuby.loader.model_definition(target_model_name)
  target_class = LcpRuby.registry.model_for(target_model_name)
  target_record = target_class.new

  authorize_inline_target!(target_model_name, target_record, :create?)

  permitted = inline_create_params(target_model_def)
  record = target_class.new(permitted)

  if record.save
    label_method = resolve_inline_label_method(target_model_def, params[:label_method])
    render json: { id: record.id, label: resolve_label(record, label_method) }, status: :created
  else
    render json: { errors: record.errors.full_messages }, status: :unprocessable_content
  end
end

#inline_create_formObject



611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
# File 'app/controllers/lcp_ruby/resources_controller.rb', line 611

def inline_create_form
  target_model_name = params[:target_model]
  return head(:bad_request) unless target_model_name.present?

  target_presenter = find_presenter_for_inline_create(target_model_name)
  return head(:not_found) unless target_presenter

  target_model_def = LcpRuby.loader.model_definition(target_model_name)
  target_class = LcpRuby.registry.model_for(target_model_name)
  target_record = target_class.new

  authorize_inline_target!(target_model_name, target_record, :create?)

  layout_builder = Presenter::LayoutBuilder.new(target_presenter, target_model_def)
  @inline_fields = inline_form_fields(layout_builder, target_model_def)

  render partial: "lcp_ruby/resources/inline_create_form",
         locals: { fields: @inline_fields, model_name: target_model_name },
         layout: false
end

#kanban_moveObject

PATCH /:id/kanban_move — dispatches the move through the configured provider and maps Kanban::MoveResult → HTTP per docs/design/kanban_view.md.



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
# File 'app/controllers/lcp_ruby/resources_controller.rb', line 517

def kanban_move
  unless current_presenter.kanban?
    head :not_found
    return
  end

  authorize @record, :update?

  provider_class = kanban_provider_class
  provider = build_kanban_provider(provider_class)

  target_column   = params[:target_column]
  target_swimlane = params[:target_swimlane]
  target_position = params[:target_position].presence&.to_i
  comment         = params[:transition_comment]

  group_by_field = current_presenter.kanban_config["group_by"].to_s
  source_column = group_by_field.present? ? @record.public_send(group_by_field).to_s : params[:source_column].to_s

  result =
    begin
      provider.move(
        record: @record,
        target_column: target_column,
        target_swimlane: target_swimlane,
        target_position: target_position,
        user: current_user,
        comment: comment
      )
    rescue StandardError => e
      raise unless Rails.env.production?
      LcpRuby.record_error(e, subsystem: "kanban", record_id: @record.id, presenter: current_presenter.name) if LcpRuby.respond_to?(:record_error)
      LcpRuby::Kanban::MoveResult.error(code: :unknown, message: e.message)
    end

  handle_kanban_move_result(result, source_column: source_column, target_column: target_column.to_s, group_by_field: group_by_field, provider_class: provider_class)
end

#newObject



145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'app/controllers/lcp_ruby/resources_controller.rb', line 145

def new
  return head(:not_found) if api_model?
  @record = @model_class.new
  authorize @record
  warn_missing_presenter_config(:form)
  apply_presenter_defaults(@record)
  @form_actions = current_form_actions(@record)

  if dialog_context?
    return render_dialog_form
  end

  build_nested_records(@record)
  @layout_builder = Presenter::LayoutBuilder.new(current_presenter, current_model_definition)
end

#parse_qlObject



374
375
376
377
378
379
380
381
382
383
384
385
# File 'app/controllers/lcp_ruby/resources_controller.rb', line 374

def parse_ql
  authorize @model_class, :index?

  ql_text = params[:ql].to_s.first(Search::QueryLanguageParser::MAX_INPUT_LENGTH + 1)
  max_depth = current_presenter.advanced_filter_config["max_nesting_depth"] || 2
  parser = Search::QueryLanguageParser.new(ql_text, max_nesting_depth: max_depth)
  tree = parser.parse

  render json: { success: true, tree: tree }
rescue Search::QueryLanguageParser::ParseError => e
  render json: { success: false, error: e.message, position: e.position }
end

#permanently_destroyObject



299
300
301
302
303
304
305
# File 'app/controllers/lcp_ruby/resources_controller.rb', line 299

def permanently_destroy
  authorize @record
  @record.destroy!
  redirect_to resources_path, status: :see_other,
    notice: I18n.t("lcp_ruby.flash.permanently_deleted", model: current_model_definition.resolved_label,
      default: "%{model} was permanently deleted.")
end

#reorderObject



555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
# File 'app/controllers/lcp_ruby/resources_controller.rb', line 555

def reorder
  unless current_model_definition.positioned?
    head :not_found
    return
  end

  authorize @record, :update?
  authorize_position_field!

  stale = verify_list_version!
  return if stale

  position_value = parse_position_param
  pos_field = current_model_definition.positioning_field
  @record.update!(pos_field => position_value)

  render json: {
    position: @record.reload.send(pos_field),
    list_version: compute_list_version(@record)
  }
end

#reparentObject



577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
# File 'app/controllers/lcp_ruby/resources_controller.rb', line 577

def reparent
  unless current_model_definition.tree?
    head :not_found
    return
  end

  authorize @record, :update?
  authorize_parent_field_writable!

  stale = verify_tree_version!
  return if stale

  parent_field = current_model_definition.tree_parent_field
  new_parent_id = parse_parent_id_param

  @record.send("#{parent_field}=", new_parent_id)

  # Optional position when tree is ordered
  if params[:position].present? && current_model_definition.tree_ordered?
    pos_field = current_model_definition.tree_position_field
    @record.send("#{pos_field}=", parse_position_param)
  end

  if @record.save
    render json: {
      id: @record.id,
      parent_id: @record[parent_field],
      tree_version: compute_tree_version
    }
  else
    render json: { errors: @record.errors.full_messages }, status: :unprocessable_content
  end
end

#restoreObject



291
292
293
294
295
296
297
# File 'app/controllers/lcp_ruby/resources_controller.rb', line 291

def restore
  authorize @record
  @record.undiscard!
  redirect_to resources_path, status: :see_other,
    notice: I18n.t("lcp_ruby.flash.restored", model: current_model_definition.resolved_label,
                   default: "%{model} was successfully restored.")
end

#select_optionsObject



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
# File 'app/controllers/lcp_ruby/resources_controller.rb', line 307

def select_options
  field_name = params[:field]
  field_config = find_form_field_config(field_name)
  unless field_config
    skip_authorization
    return render(json: [])
  end

  # Resolve association from enriched field config (covers association_select + multi_select)
  assoc = field_config["association"] || field_config["multi_select_association"]
  # Fallback to FK lookup for non-enriched cases
  assoc ||= resolve_association_for_field(field_name)
  unless assoc&.lcp_model?
    skip_authorization
    return render(json: [])
  end

  # Authorize against the TARGET model's policy, not the page-level
  # presenter model. The user is requesting a list of records FROM
  # `assoc.target_model`; access to the presenter alone does not
  # imply read access to the association target. `before_action
  # :authorize_presenter_access` (Controller::Authorization) already
  # gates presenter visibility, so we only need the additional
  # target-model `:index?` check here.
  authorize_select_options_target!(assoc.target_model)

  input_options = field_config["input_options"] || {}

  # API-backed target model: delegate to data source
  if api_target_model?(assoc)
    return render json: build_api_select_options(assoc, input_options)
  end

  # Reverse cascade: resolve ancestor chain for a given value
  if params[:ancestors_for].present?
    ancestors = resolve_field_ancestors(field_name, params[:ancestors_for])
    return render json: { ancestors: ancestors }
  end

  # Tree select mode
  if params[:tree] == "true"
    tree = build_tree_select_options(assoc, input_options)
    return render json: tree
  end

  # Paginated search mode when q or page param present
  if params[:q].present? || params[:page].present?
    result = build_select_options_search(assoc, input_options)
    render json: result
  else
    options = build_select_options_json(assoc, input_options)
    render json: options
  end
end

#showObject



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
# File 'app/controllers/lcp_ruby/resources_controller.rb', line 90

def show
  authorize @record

  if raw_format?
    return head :not_acceptable if raw_show_unsupported?
    return render_raw_show
  end

  warn_missing_presenter_config(:show)

  if dialog_context?
    setup_show_view_objects(current_presenter)
    return render partial: "lcp_ruby/dialogs/dialog_show_frame",
                   locals: {
                     record: @record,
                     layout_builder: @layout_builder,
                     column_set: @column_set,
                     field_resolver: @field_resolver
                   },
                   layout: false
  end

  if current_page&.composite?
    load_composite_page
    return
  end

  if api_model?
    setup_show_view_objects(current_presenter)
    return
  end

  setup_show_view_objects(current_presenter)
  load_show_virtual_columns
  preload_associations(@record, :show)
  @record.strict_loading! if LcpRuby.configuration.strict_loading_enabled?
end

#updateObject



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
# File 'app/controllers/lcp_ruby/resources_controller.rb', line 211

def update
  return head(:not_found) if api_model?
  authorize @record
  @record.assign_attributes(permitted_params)
  fa_config = resolve_form_action(@record)
  purge_removed_attachments!(@record)

  process_json_field_params(@record)
  validate_association_values!(@record)
  apply_set_fields!(@record, fa_config)

  if @record.errors.any?
    return render_update_failure
  end

  result = execute_form_action_pipeline(@record, fa_config)

  if result.success?
    dispatch_deferred_events(result)
    broadcast_model_change(current_model_definition.name)

    if dialog_context?
      behavior = form_action_dialog_behavior(fa_config)
      flash_msg = behavior == "reset" ? pipeline_flash_message("update", result) : nil
      return render_dialog_success(behavior, flash_message: flash_msg, result_config: fa_config["result"])
    end

    path = if current_page&.form_zone&.submit_redirect_self?
      resource_path(@record)
    else
      pipeline_redirect_path("update", fa_config, @record, result)
    end
    redirect_to path, status: :see_other,
      notice: pipeline_flash_message("update", result)
  else
    render_update_failure
  end
end

#zoneObject



128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'app/controllers/lcp_ruby/resources_controller.rb', line 128

def zone
  authorize @record, :show?

  zone_name = params[:zone_name]
  zone = find_composite_zone(zone_name)
  return head(:not_found) unless zone
  return head(:not_found) unless zone_accessible?(zone)

  data = resolve_zone_data(zone, zone_params: zone_params(zone))

  frame_id = zone.area == "tabs" ? "lcp-zone-tab-content" : "lcp-zone-#{zone.name}"

  render partial: "lcp_ruby/zones/zone_frame",
         locals: { zone: zone, data: data, frame_id: frame_id, record: @record },
         layout: false
end