| 1 | package App::Netdisco::Util::CustomFields; | ||
| 2 | |||
| 3 | use App::Netdisco; # a no-op except needed for testing | ||
| 4 | |||
| 5 | use Dancer ':syntax'; | ||
| 6 | use Dancer::Plugin::DBIC; | ||
| 7 | |||
| 8 | use App::Netdisco::DB::ResultSet::Device; | ||
| 9 | use App::Netdisco::DB::ResultSet::DevicePort; | ||
| 10 | |||
| 11 | my %device_fields_json = (); | ||
| 12 | my @inline_device_actions = (); | ||
| 13 | my @inline_device_port_actions = (); | ||
| 14 | |||
| 15 | foreach my $config (@{ setting('custom_fields')->{'device'} || [] }) { | ||
| 16 | next unless $config->{'name'}; | ||
| 17 | push @inline_device_actions, $config->{'name'}; | ||
| 18 | ++$device_fields_json{ $config->{'name'} } if $config->{'json_list'}; | ||
| 19 | } | ||
| 20 | |||
| 21 | foreach my $config (@{ setting('custom_fields')->{'device_port'} || [] }) { | ||
| 22 | next unless $config->{'name'}; | ||
| 23 | push @inline_device_port_actions, $config->{'name'}; | ||
| 24 | } | ||
| 25 | |||
| 26 | { | ||
| 27 | package App::Netdisco::DB::ResultSet::Device; | ||
| 28 | |||
| 29 | sub with_custom_fields { | ||
| 30 | my ($rs, $cond, $attrs) = @_; | ||
| 31 | |||
| 32 | return $rs | ||
| 33 | ->search_rs($cond, $attrs) | ||
| 34 | ->search({}, | ||
| 35 | { '+columns' => { | ||
| 36 | map {( ('cf_'. $_) => \[ | ||
| 37 | ($device_fields_json{$_} ? q{ARRAY(SELECT json_array_elements_text( COALESCE(NULLIF((me.custom_fields ->> ?),''),'[]') ::json))::text[]} | ||
| 38 | : 'me.custom_fields ->> ?') | ||
| 39 | => $_ ] )} @inline_device_actions | ||
| 40 | }}); | ||
| 41 | } | ||
| 42 | } | ||
| 43 | |||
| 44 | { | ||
| 45 | package App::Netdisco::DB::ResultSet::DevicePort; | ||
| 46 | |||
| 47 | sub with_custom_fields { | ||
| 48 | my ($rs, $cond, $attrs) = @_; | ||
| 49 | |||
| 50 | return $rs | ||
| 51 | ->search_rs($cond, $attrs) | ||
| 52 | ->search({}, | ||
| 53 | { '+columns' => { | ||
| 54 | map {( ('cf_'. $_) => \[ 'me.custom_fields ->> ?' => $_ ] )} | ||
| 55 | @inline_device_port_actions | ||
| 56 | }}); | ||
| 57 | } | ||
| 58 | } | ||
| 59 | |||
| 60 | set('_inline_actions' => [ | ||
| 61 | map {'cf_' . $_} (@inline_device_actions, @inline_device_port_actions) | ||
| 62 | ]); | ||
| 63 | |||
| 64 | true; | ||
| 65 |