/
resource.ex
375 lines (317 loc) · 11.3 KB
/
resource.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
defmodule LiveAdmin.Resource do
@moduledoc """
API for managing Ecto schemas and their individual record instances used internally by LiveAdmin.
> #### `use LiveAdmin.Resource` {: .info}
> This is required in any module that should act as a LiveAdmin Resource.
> If the module is not an Ecto schema, then the `:schema` option must be passed.
> Using this module will create a __live_admin_config__ module variable and 2 functions
> to query it, __live_admin_config__/0 and __live_admin_config__/1. The former returns the entire
> config while the latter will return a key if it exists, otherwise it will fallback
> to either a global config for that key, or the key's default value.
To customize UI behavior, the following options may also be used:
* `title_with` - a binary, or MFA that returns a binary, used to identify the resource
* `label_with` - a binary, or MFA that returns a binary, used to identify records
* `list_with` - an atom or MFA that identifies the function that implements listing the resource
* `create_with` - an atom or MFA that identifies the function that implements creating the resource (set to false to disable create)
* `update_with` - an atom or MFA that identifies the function that implements updating a record (set to false to disable update)
* `delete_with` - an atom or MFA that identifies the function that implements deleting a record (set to false to disable delete)
* `validate_with` - an atom or MFA that identifies the function that implements validating a changed record
* `render_with` - an atom or MFA that identifies the function that implements table field rendering logic
* `hidden_fields` - a list of fields that should not be displayed in the UI
* `immutable_fields` - a list of fields that should not be editable in forms
* `actions` - list of atoms or MFAs that identify a function that operates on a record
* `tasks` - list atoms or MFAs that identify a function that operates on a resource
* `components` - keyword list of component module overrides for specific views (`:list`, `:new`, `:edit`, `:home`, `:nav`, `:session`, `:view`)
* `ecto_repo` - Ecto repo to use when building queries for this resource
"""
import Ecto.Query
import LiveAdmin, only: [record_label: 2, parent_associations: 1]
alias Ecto.Changeset
alias PhoenixHTMLHelpers.{Format, Tag}
@doc false
defmacro __using__(opts) do
quote bind_quoted: [opts: opts] do
@__live_admin_config__ Keyword.put_new(opts, :schema, __MODULE__)
def __live_admin_config__, do: @__live_admin_config__
def __live_admin_config__(key) do
@__live_admin_config__
|> Keyword.get(key, Application.get_env(:live_admin, key))
|> case do
false -> false
nil -> LiveAdmin.Resource.default_config_value(key)
config -> config
end
end
end
end
def render(record, field, resource, assoc_resource, session) do
:render_with
|> resource.__live_admin_config__()
|> case do
nil ->
if assoc_resource do
record_label(
Map.fetch!(record, get_assoc_name!(resource.__live_admin_config__(:schema), field)),
elem(assoc_resource, 1)
)
else
record
|> Map.fetch!(field)
|> render_field()
end
{m, f, a} ->
apply(m, f, [record, field, session] ++ a)
f when is_atom(f) ->
apply(resource, f, [record, field, session])
end
end
def all(ids, resource, prefix, repo) do
resource.__live_admin_config__(:schema)
|> where([s], s.id in ^ids)
|> repo.all(prefix: prefix)
end
def find!(id, resource, prefix, repo) do
find(id, resource, prefix, repo) ||
raise(Ecto.NoResultsError, queryable: resource.__live_admin_config__(:schema))
end
def find(id, resource, prefix, repo) do
resource.__live_admin_config__(:schema)
|> preload(^preloads(resource))
|> repo.get(id, prefix: prefix)
end
def delete(record, resource, session, repo) do
:delete_with
|> resource.__live_admin_config__()
|> case do
nil ->
repo.delete(record)
{mod, func_name, args} ->
apply(mod, func_name, [record, session] ++ args)
name when is_atom(name) ->
apply(resource, name, [record, session])
end
end
def list(resource, opts, session, repo) do
:list_with
|> resource.__live_admin_config__()
|> case do
nil ->
build_list(resource, opts, repo)
{mod, func_name, args} ->
apply(mod, func_name, [resource, opts, session] ++ args)
name when is_atom(name) ->
apply(resource, name, [opts, session])
end
end
def change(resource, record \\ nil, params \\ %{})
def change(resource, record, params) when is_struct(record) do
build_changeset(record, resource, params)
end
def change(resource, nil, params) do
:schema
|> resource.__live_admin_config__()
|> struct(%{})
|> build_changeset(resource, params)
end
def create(resource, params, session, repo) do
:create_with
|> resource.__live_admin_config__()
|> case do
nil ->
resource
|> change(nil, params)
|> repo.insert(prefix: session.prefix)
{mod, func_name, args} ->
apply(mod, func_name, [params, session] ++ args)
name when is_atom(name) ->
apply(resource, name, [params, session])
end
end
def update(record, resource, params, session) do
:update_with
|> resource.__live_admin_config__()
|> case do
nil ->
resource
|> change(record, params)
|> resource.__live_admin_config__(:ecto_repo).update()
{mod, func_name, args} ->
apply(mod, func_name, [record, params, session] ++ args)
name when is_atom(name) ->
apply(resource, name, [record, params, session])
end
end
def validate(changeset, resource, session) do
:validate_with
|> resource.__live_admin_config__()
|> case do
nil -> changeset
{mod, func_name, args} -> apply(mod, func_name, [changeset, session] ++ args)
name when is_atom(name) -> apply(resource, name, [changeset, session])
end
|> Map.put(:action, :validate)
end
def fields(resource) do
schema = resource.__live_admin_config__(:schema)
Enum.flat_map(schema.__schema__(:fields), fn field_name ->
:hidden_fields
|> resource.__live_admin_config__()
|> Enum.member?(field_name)
|> case do
false ->
[
{field_name, schema.__schema__(:type, field_name),
[
immutable:
Enum.member?(resource.__live_admin_config__(:immutable_fields) || [], field_name)
]}
]
true ->
[]
end
end)
end
def default_config_value(key) when key in [:actions, :tasks, :components, :hidden_fields],
do: []
def default_config_value(:label_with), do: :id
def default_config_value(_), do: nil
defp build_list(resource, opts, repo) do
opts =
opts
|> Enum.into(%{})
|> Map.put_new(:page, 1)
|> Map.put_new(:sort_dir, :asc)
|> Map.put_new(:sort_attr, :id)
query =
:schema
|> resource.__live_admin_config__()
|> limit(10)
|> offset(^((opts[:page] - 1) * 10))
|> order_by(^[{opts[:sort_dir], opts[:sort_attr]}])
|> preload(^preloads(resource))
query =
opts
|> Enum.reduce(query, fn
{:search, q}, query when byte_size(q) > 0 ->
apply_search(query, q, fields(resource))
_, query ->
query
end)
{
repo.all(query, prefix: opts[:prefix]),
repo.aggregate(
query |> exclude(:limit) |> exclude(:offset),
:count,
prefix: opts[:prefix]
)
}
end
defp apply_search(query, q, fields) do
q
|> String.split(~r{[^\s]*:}, include_captures: true, trim: true)
|> case do
[q] ->
matcher = if String.contains?(q, "%"), do: q, else: "%#{q}%"
Enum.reduce(fields, query, fn {field_name, _, _}, query ->
or_where(
query,
[r],
like(
fragment("LOWER(CAST(? AS text))", field(r, ^field_name)),
^String.downcase(matcher)
)
)
end)
field_queries ->
field_queries
|> Enum.map(&String.trim/1)
|> Enum.chunk_every(2)
|> Enum.reduce(query, fn
[field_key, q], query ->
fields
|> Enum.find_value(fn {field_name, _, _} ->
if "#{field_name}:" == field_key, do: field_name
end)
|> case do
nil ->
query
field_name ->
or_where(
query,
[r],
ilike(fragment("CAST(? AS text)", field(r, ^field_name)), ^"%#{q}%")
)
end
_, query ->
query
end)
end
end
defp build_changeset(record = %schema{}, resource, params) do
resource
|> case do
:embed ->
Enum.map(schema.__schema__(:fields), fn field_name ->
{field_name, schema.__schema__(:type, field_name), []}
end)
resource ->
fields(resource)
end
|> Enum.reduce(Changeset.cast(record, params, []), fn
{field_name, {_, Ecto.Embedded, %{cardinality: :many}}, _}, changeset ->
Changeset.cast_embed(changeset, field_name,
with: fn embed, params -> build_changeset(embed, :embed, params) end,
sort_param: LiveAdmin.View.sort_param_name(field_name),
drop_param: LiveAdmin.View.drop_param_name(field_name)
)
{field_name, {_, Ecto.Embedded, %{cardinality: :one}}, _}, changeset ->
if Map.get(params, to_string(field_name)) == "" do
Changeset.put_change(changeset, field_name, nil)
else
Changeset.cast_embed(changeset, field_name,
with: fn embed, params -> build_changeset(embed, :embed, params) end
)
end
{field_name, type, opts}, changeset ->
unless Keyword.get(opts, :immutable, false) do
changeset = Changeset.cast(changeset, params, [field_name])
if type == :map do
Changeset.update_change(changeset, field_name, &parse_map_param/1)
else
changeset
end
else
changeset
end
end)
end
defp parse_map_param(param = %{}) do
param
|> Enum.sort_by(fn {idx, _} -> idx end)
|> Map.new(fn {_, %{"key" => key, "value" => value}} -> {key, value} end)
end
defp parse_map_param(param), do: param
defp preloads(resource) do
:preload
|> resource.__live_admin_config__()
|> case do
nil ->
resource.__live_admin_config__(:schema)
|> parent_associations()
|> Enum.map(& &1.field)
{m, f, a} ->
apply(m, f, [resource | a])
preloads when is_list(preloads) ->
preloads
end
end
defp get_assoc_name!(schema, fk) do
Enum.find(schema.__schema__(:associations), fn assoc_name ->
fk == schema.__schema__(:association, assoc_name).owner_key
end)
end
defp render_field(val = %{}), do: Tag.content_tag(:pre, inspect(val, pretty: true))
defp render_field(val) when is_list(val), do: Enum.map(val, &render_field/1)
defp render_field(val) when is_binary(val), do: Format.text_to_html(val)
defp render_field(val), do: inspect(val)
end