-
-
Notifications
You must be signed in to change notification settings - Fork 52
/
auto.ex
874 lines (745 loc) · 24.8 KB
/
auto.ex
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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
defmodule AshPhoenix.Form.Auto do
@auto_opts [
relationship_fetcher: [
type: :any,
doc: """
A two argument function that receives the parent data, the relationship to fetch.
The default simply fetches the relationship value, and if it isn't loaded, it uses `[]` or `nil`.
"""
],
sparse_lists?: [
type: :boolean,
doc:
"Sets all list type forms to `sparse?: true` by default. Has no effect on forms derived for embedded resources.",
default: false
],
include_non_map_types?: [
type: :boolean,
doc: "Creates form for non map or array of map type inputs",
default: false
]
]
@moduledoc """
A tool to automatically generate available nested forms based on a resource and action.
To use this, specify `forms: [auto?: true]` when creating the form.
Keep in mind, you can always specify these manually when creating a form by simply specifying the `forms` option.
There are two things that this builds forms for:
1. Attributes/arguments who's type is an embedded resource.
2. Arguments that have a corresponding `change manage_relationship(..)` configured.
For more on relationships see the documentation for `Ash.Changeset.manage_relationship/4`.
When building forms, you can switch on the action type and/or resource of the form, in order to have different
fields depending on the form. For example, if you have a simple relationship called `:comments` with
`on_match: :update` and `on_no_match: :create`, there are two types of forms that can be in `inputs_for(form, :comments)`.
In which case you may have something like this:
```elixir
<%= for comment_form <- inputs_for(f, :comments) do %>
<%= hidden_inputs_for(comment_form) %>
<%= if comment_form.source.type == :create do %>
<%= text_input comment_form, :text %>
<%= text_input comment_form, :on_create_field %>
<% else %>
<%= text_input comment_form, :text %>
<%= text_input comment_form, :on_update_field %>
<% end %>
<button phx-click="remove_form" phx-value-path="<%= comment_form.name %>">Add Comment</button>
<button phx-click="add_form" phx-value-path="<%= comment_form.name %>">Add Comment</button>
<% end %>
```
This also applies to adding forms of different types manually. For instance, if you had a "search" field
to allow them to search for a record (e.g in a liveview), and you had an `on_lookup` read action, you could
render a search form for that read action, and once they've selected a record, you could render the fields
to update that record (in the case of `on_lookup: :relate_and_update` configurations).
## Options
#{Spark.OptionsHelpers.docs(@auto_opts)}
## Special Considerations
### `on_lookup: :relate_and_update`
For `on_lookup: :relate_and_update` configurations, the "read" form for that relationship will use the appropriate read action.
However, you may also want to include the relevant fields for the update that would subsequently occur. To that end, a special
nested form called `:_update` is created, that uses an empty instance of that resource as the base of its changeset. This may require
some manual manipulation of that data before rendering the relevant form because it assumes all the default values. To solve for this,
if you are using liveview, you could actually look up the record using the input from the read action, and then use `AshPhoenix.Form.update_form/3`
to set that looked up record as the data of the `_update` form.
### Many to Many Relationships
In the case that a manage_change option points to a join relationship, that form is presented via a special nested form called
`_join`. So the first form in `inputs_for(form, :relationship)` would be for the destination, and then inside of that you could say
`inputs_for(nested_form, :_join)`. The parameters are merged together during submission.
"""
@dialyzer {:nowarn_function, rel_to_resource: 2}
def auto(resource, action, opts \\ []) do
opts = Spark.OptionsHelpers.validate!(opts, @auto_opts)
Keyword.new(
related(resource, action, opts) ++
embedded(resource, action, opts) ++ unions(resource, action, opts)
)
end
def unions(resource, action, auto_opts) do
action =
if is_atom(action) do
Ash.Resource.Info.action(resource, action)
else
action
end
resource
|> accepted_attributes(action)
|> Enum.concat(action.arguments)
|> Enum.filter(&union?(&1.type))
|> Enum.reject(&match?({:array, {:array, _}}, &1.type))
|> Enum.map(fn attr ->
{type, constraints} =
if Ash.Type.NewType.new_type?(attr.type) do
{Ash.Type.NewType.subtype_of(attr.type),
Ash.Type.NewType.constraints(attr.type, attr.constraints)}
else
{attr.type, attr.constraints}
end
form_type =
case type do
{:array, _} ->
:list
_ ->
:single
end
constraints = unwrap_union(type, constraints)
data =
case form_type do
:list ->
fn parent ->
if parent do
Map.get(parent, attr.name) || []
else
[]
end
end
:single ->
fn parent ->
if parent do
case Map.get(parent, attr.name) do
[value | _] -> value
[] -> nil
value -> value
end
end
end
end
updater = fn opts, data, params ->
{type, constraints} = determine_type(constraints, data, params)
{embed, constraints, fake_embedded?} =
if Ash.Type.embedded_type?(type) do
{type, constraints, false}
else
{AshPhoenix.Form.WrappedValue, [], true}
end
prepare_source =
if fake_embedded? do
fn source ->
case source do
%Ash.Changeset{} ->
Ash.Changeset.set_context(source, %{type: type, constraints: constraints})
%Ash.Query{} ->
Ash.Query.set_context(source, %{type: type, constraints: constraints})
end
end
end
transform_params =
if fake_embedded? do
fn form, params, type ->
if type == :nested do
AshPhoenix.Form.value(form, :value)
else
params
end
end
end
create_action =
if constraints[:create_action] do
Ash.Resource.Info.action(embed, constraints[:create_action])
else
Ash.Resource.Info.primary_action(embed, :create)
end
update_action =
if constraints[:update_action] do
Ash.Resource.Info.action(embed, constraints[:update_action])
else
Ash.Resource.Info.primary_action(embed, :update)
end
Keyword.merge(opts,
resource: embed,
create_action: create_action.name,
update_action: update_action.name,
prepare_source: prepare_source,
transform_params: transform_params,
embed?: true,
forms: [],
updater: fn opts ->
Keyword.update!(opts, :forms, fn forms ->
forms ++
embedded(embed, create_action, auto_opts) ++
embedded(embed, update_action, auto_opts) ++
unions(embed, create_action, auto_opts) ++
unions(embed, update_action, auto_opts)
end)
end
)
end
{attr.name,
[
data: data,
type: form_type,
updater: updater
]}
end)
|> Keyword.new()
end
defp determine_type(constraints, _data, %{"_union_type" => union_type} = params) do
constraints[:types]
|> Enum.find(fn {key, _value} ->
to_string(key) == union_type
end)
|> case do
nil ->
raise """
Got "_union_type" parameter of #{inspect(union_type)}, but no type with that name was found in the constraints.
Params:
#{inspect(params, pretty: true)}
Available types:
#{inspect(constraints[:types], pretty: true)}
"""
{_key, config} ->
{config[:type], config[:constraints]}
end
end
defp determine_type(constraints, data, params) do
constraints[:types]
|> Enum.find(fn {key, config} ->
config[:tag] && (tags_equal(config, key, params) || tags_equal_data(config, key, data))
end)
|> case do
nil ->
raise """
Got no "_union_type" parameter, and no union type had a tag & tag_value pair matching the params.
If you are adding a form, select a type using `params: %{"_union_type" => "type_name"}`, or if one
or more of your types is using a tag you can set that tag with `params: %{"tag" => "tag_value"}`.
Params:
#{inspect(params, pretty: true)}
Available types:
#{inspect(constraints[:types], pretty: true)}
"""
{_key, config} ->
{config[:type], config[:constraints]}
end
end
defp tags_equal(config, key, params) do
if is_map(params) do
case config[:tag_value] || key do
value when is_atom(value) ->
params[to_string(config[:tag])] == to_string(value) ||
params[to_string(config[:tag])] == value
value ->
params[to_string(config[:tag])] == value
end
else
false
end
end
defp tags_equal_data(config, key, data) do
if is_struct(data) do
case config[:tag_value] || key do
value when is_atom(value) ->
data[config[:tag]] == to_string(value) ||
data[config[:tag]] == value
value ->
data[config[:tag]] == value
end
else
false
end
end
def related(resource, action, auto_opts) do
passed_in_action = action
action =
if is_atom(action) do
Ash.Resource.Info.action(resource, action)
else
action
end
if is_nil(action) && is_atom(passed_in_action) do
raise "No such action :#{passed_in_action} for #{inspect(resource)}"
end
action.arguments
|> Enum.reject(& &1.private?)
|> exclude_non_map_types(auto_opts)
|> Enum.flat_map(fn arg ->
case find_manage_change(arg, action) do
nil ->
[]
manage_opts ->
[{arg, manage_opts}]
end
end)
|> Enum.map(fn {arg, manage_opts} ->
relationship = Ash.Resource.Info.relationship(resource, manage_opts[:relationship])
manage_opts = manage_opts[:opts]
defaults =
if manage_opts[:type] do
Ash.Changeset.manage_relationship_opts(manage_opts[:type])
else
[]
end
manage_opts =
Ash.Changeset.ManagedRelationshipHelpers.sanitize_opts(
relationship,
Keyword.merge(defaults, manage_opts)
)
type =
case arg.type do
{:array, _} -> :list
_ -> :single
end
must_load_opts = [
type: relationship.type,
action_type: action.type,
could_be_related_at_creation?:
Map.get(relationship, :could_be_related_at_creation?, false)
]
opts = [
type: type,
forms: [],
sparse?: auto_opts[:sparse_lists?],
managed_relationship: {relationship.source, relationship.name},
must_load?:
Ash.Changeset.ManagedRelationshipHelpers.must_load?(manage_opts, must_load_opts),
updater: fn opts ->
opts =
opts
|> add_create_action(manage_opts, relationship, auto_opts)
|> add_read_action(manage_opts, relationship, auto_opts)
|> add_update_action(manage_opts, relationship, auto_opts)
|> add_destroy_action(manage_opts, relationship, auto_opts)
|> add_nested_forms(auto_opts)
if opts[:read_action] || opts[:update_action] || opts[:destroy_action] do
Keyword.put(
opts,
:data,
relationship_fetcher(relationship, auto_opts[:relationship_fetcher], opts[:type])
)
else
opts
end
end
]
opts =
if map_type?(arg.type) do
opts
else
key =
manage_opts[:value_is_key] ||
relationship.destination
|> Ash.Resource.Info.primary_key()
|> case do
[key] ->
key
_ ->
nil
end
if key do
opts
|> Keyword.put(:forms, [])
|> Keyword.put(:transform_params, fn form, params, type ->
if type == :nested do
AshPhoenix.Form.value(form, key)
else
params
end
end)
else
Keyword.put(opts, :forms, [])
end
end
{arg.name, opts}
end)
|> Keyword.new()
end
defp exclude_non_map_types(args, opts) do
if opts[:include_non_map_types?] do
args
else
Enum.filter(args, fn %{type: type} ->
map_type?(type)
end)
end
end
defp map_type?({:array, type}) do
map_type?(type)
end
defp map_type?(:map), do: true
defp map_type?(Ash.Type.Map), do: true
defp map_type?(type) do
if Ash.Type.embedded_type?(type) do
if is_atom(type) && :erlang.function_exported(type, :admin_map_type?, 0) do
type.admin_map_type?()
else
false
end
else
false
end
end
defp add_nested_forms(opts, auto_opts) do
Keyword.update!(opts, :forms, fn forms ->
forms =
if forms[:update_action] do
forms ++ set_for_type(auto(opts[:resource], opts[:update_action], auto_opts), :update)
else
forms
end
forms =
if forms[:create_action] do
forms ++ set_for_type(auto(opts[:resource], opts[:create_action], auto_opts), :create)
else
forms
end
forms =
if forms[:destroy_action] do
forms ++ set_for_type(auto(opts[:resource], opts[:destroy_action], auto_opts), :destroy)
else
forms
end
if forms[:read_action] do
forms ++ set_for_type(auto(opts[:resource], opts[:read_action], auto_opts), :read)
else
forms
end
end)
end
defp set_for_type(forms, type) do
Enum.map(forms, fn {key, value} ->
{key, Keyword.put(value, :for_type, type)}
end)
end
defp add_read_action(opts, manage_opts, relationship, auto_opts) do
manage_opts
|> Ash.Changeset.ManagedRelationshipHelpers.on_lookup_read_action(relationship)
|> case do
nil ->
opts
{source_dest_or_join, action_name} ->
resource = rel_to_resource(source_dest_or_join, relationship)
opts
|> Keyword.put(:read_resource, resource)
|> Keyword.put(:read_action, action_name)
|> Keyword.update!(
:forms,
fn forms ->
case Ash.Changeset.ManagedRelationshipHelpers.on_lookup_update_action(
manage_opts,
relationship
) do
nil ->
forms ++
auto(resource, action_name, auto_opts)
{source_dest_or_join, update_action} ->
resource = rel_to_resource(source_dest_or_join, relationship)
forms ++
auto(resource, action_name, auto_opts) ++
[
{:_update,
[
resource: resource,
managed_relationship: {relationship.source, relationship.name},
type: :single,
data: resource.__struct__(),
update_action: update_action
]}
]
{:join, update_action, _} ->
resource = relationship.through
forms ++
auto(resource, action_name, auto_opts) ++
[
{:_update,
[
resource: resource,
managed_relationship: {relationship.source, relationship.name},
type: :single,
data: resource.__struct__(),
update_action: update_action
]}
]
end
end
)
end
end
defp add_create_action(opts, manage_opts, relationship, auto_opts) do
manage_opts
|> Ash.Changeset.ManagedRelationshipHelpers.on_no_match_destination_actions(relationship)
|> List.wrap()
|> Enum.sort_by(&(elem(&1, 0) == :join))
|> case do
[] ->
opts
[{source_dest_or_join, action_name} | rest] ->
resource = rel_to_resource(source_dest_or_join, relationship)
opts
|> Keyword.put(:create_resource, resource)
|> Keyword.put(:create_action, action_name)
|> Keyword.update!(
:forms,
&(&1 ++
auto(resource, action_name, auto_opts))
)
|> add_join_form(relationship, rest)
end
end
defp add_update_action(opts, manage_opts, relationship, auto_opts) do
manage_opts
|> Ash.Changeset.ManagedRelationshipHelpers.on_match_destination_actions(relationship)
|> List.wrap()
|> Enum.sort_by(&(elem(&1, 0) == :join))
|> case do
[] ->
opts
[{source_dest_or_join, action_name} | rest] ->
resource = rel_to_resource(source_dest_or_join, relationship)
opts
|> Keyword.put(:update_resource, resource)
|> Keyword.put(:update_action, action_name)
|> Keyword.update!(
:forms,
&(&1 ++
auto(resource, action_name, auto_opts))
)
|> add_join_form(relationship, rest)
end
end
defp add_destroy_action(opts, manage_opts, relationship, auto_opts) do
manage_opts
|> Ash.Changeset.ManagedRelationshipHelpers.on_missing_destination_actions(relationship)
|> List.wrap()
|> Enum.sort_by(&(elem(&1, 0) == :join))
|> case do
[] ->
opts
[{source_dest_or_join, action_name} | rest] ->
resource = rel_to_resource(source_dest_or_join, relationship)
opts
|> Keyword.put(:destroy_resource, resource)
|> Keyword.put(:destroy_action, action_name)
|> Keyword.update!(
:forms,
&(&1 ++
auto(resource, action_name, auto_opts))
)
|> add_join_form(relationship, rest)
end
end
defp add_join_form(opts, _relationship, []), do: opts
defp add_join_form(opts, relationship, [{:join, action, fields}]) do
action = Ash.Resource.Info.action(relationship.through, action)
case action.type do
:update ->
Keyword.update!(opts, :forms, fn forms ->
update_join_forms(forms,
resource: relationship.through,
managed_relationship: {relationship.source, relationship.name},
type: :single,
data: &get_join(&1, &2, relationship),
update_fields: fields,
merge?: true,
update_action: action.name
)
end)
:create ->
Keyword.update!(opts, :forms, fn forms ->
update_join_forms(forms,
resource: relationship.through,
type: :single,
managed_relationship: {relationship.source, relationship.name},
create_fields: fields,
merge?: true,
create_action: action.name
)
end)
:destroy ->
Keyword.update!(opts, :forms, fn forms ->
update_join_forms(forms,
resource: relationship.through,
managed_relationship: {relationship.source, relationship.name},
type: :single,
data: &get_join(&1, &2, relationship),
destroy_fields: fields,
destroy_action: action.name,
merge?: true
)
end)
end
end
defp update_join_forms(forms, config) do
Keyword.update(forms, :_join, config, fn existing_config ->
Keyword.merge(existing_config, config)
end)
end
defp get_join(parent, prev_path, relationship) do
case Enum.find(prev_path, &(&1.__struct__ == relationship.source)) do
nil ->
nil
root ->
case Map.get(root, relationship.join_relationship) do
value when is_list(value) ->
Enum.find(value, fn join ->
Map.get(join, relationship.destination_attribute_on_join_resource) ==
Map.get(parent, relationship.destination_attribute)
end)
_ ->
nil
end
end
end
defp unwrap_union({:array, type}, constraints) do
unwrap_union(type, constraints[:items] || [])
end
defp unwrap_union(_type, constraints) do
constraints
end
defp relationship_fetcher(relationship, relationship_fetcher, type) do
fn parent ->
if relationship_fetcher do
relationship_fetcher.(parent, relationship)
else
case Map.get(parent, relationship.name) do
%Ash.NotLoaded{} ->
if type == :single do
nil
else
[]
end
value ->
if type == :single && is_list(value) do
Enum.at(value, 0)
else
value
end
end
end
end
end
defp rel_to_resource(source_dest_or_join, relationship) do
case source_dest_or_join do
:source ->
relationship.source
:destination ->
relationship.destination
:join ->
relationship.through
end
end
def embedded(resource, action, auto_opts) do
action =
if is_atom(action) do
Ash.Resource.Info.action(resource, action)
else
action
end
resource
|> accepted_attributes(action)
|> Enum.concat(action.arguments)
|> Enum.filter(&Ash.Type.embedded_type?(&1.type))
|> Enum.reject(&match?({:array, {:array, _}}, &1.type))
|> Enum.map(fn attr ->
type =
case attr.type do
{:array, _} ->
:list
_ ->
:single
end
embed = unwrap_type(attr.type)
data =
case type do
:list ->
fn parent ->
if parent do
List.wrap(Map.get(parent, attr.name))
else
[]
end
end
:single ->
fn parent ->
if parent do
case Map.get(parent, attr.name) do
[value | _] -> value
[] -> nil
value -> value
end
end
end
end
create_action =
if attr.constraints[:create_action] do
Ash.Resource.Info.action(embed, attr.constraints[:create_action])
else
Ash.Resource.Info.primary_action(embed, :create)
end
update_action =
if attr.constraints[:update_action] do
Ash.Resource.Info.action(embed, attr.constraints[:update_action])
else
Ash.Resource.Info.primary_action(embed, :update)
end
{attr.name,
[
type: type,
resource: embed,
create_action: create_action.name,
update_action: update_action.name,
embed?: true,
data: data,
forms: [],
updater: fn opts ->
Keyword.update!(opts, :forms, fn forms ->
forms ++
embedded(embed, create_action, auto_opts) ++
embedded(embed, update_action, auto_opts) ++
unions(embed, create_action, auto_opts) ++
unions(embed, update_action, auto_opts)
end)
end
]}
end)
|> Keyword.new()
end
defp union?({:array, type}), do: union?(type)
defp union?(type) do
if Ash.Type.NewType.new_type?(type) do
union?(Ash.Type.NewType.subtype_of(type))
else
type == Ash.Type.Union
end
end
defp unwrap_type({:array, type}), do: unwrap_type(type)
defp unwrap_type(type), do: type
@doc false
def accepted_attributes(resource, action) do
resource
|> Ash.Resource.Info.public_attributes()
|> only_accepted(action)
end
defp only_accepted(_attributes, %{type: :read}), do: []
defp only_accepted(attributes, %{accept: nil, reject: reject}) do
Enum.filter(attributes, &(&1.name not in reject || []))
end
defp only_accepted(attributes, %{accept: accept}) do
Enum.filter(attributes, &(&1.name in accept))
end
defp find_manage_change(argument, action) do
Enum.find_value(Map.get(action, :changes, []), fn
%{change: {Ash.Resource.Change.ManageRelationship, opts}} ->
if opts[:argument] == argument.name do
opts
end
_ ->
nil
end)
end
end