Merge branch 'test' of ../kivitendo-erp_20220811
[kivitendo-erp.git] / SL / Controller / CustomVariableConfig.pm
1 package SL::Controller::CustomVariableConfig;
2
3 use strict;
4
5 use parent qw(SL::Controller::Base);
6
7 use List::Util qw(first);
8
9 use SL::DB::CustomVariableConfig;
10 use SL::DB::CustomVariableValidity;
11 use SL::DB::PartsGroup;
12 use SL::Helper::Flash;
13 use SL::Locale::String;
14 use Data::Dumper;
15
16 use Rose::Object::MakeMethods::Generic (
17   scalar                  => [ qw(config module module_description flags) ],
18   'scalar --get_set_init' => [ qw(translated_types modules) ],
19 );
20
21 __PACKAGE__->run_before('check_auth');
22 __PACKAGE__->run_before('check_module');
23 __PACKAGE__->run_before('load_config', only => [ qw(edit update destroy) ]);
24
25 our %translations = (
26   text      => t8('Free-form text'),
27   textfield => t8('Text field'),
28   htmlfield => t8('HTML field'),
29   number    => t8('Number'),
30   date      => t8('Date'),
31   timestamp => t8('Timestamp'),
32   bool      => t8('Yes/No (Checkbox)'),
33   select    => t8('Selection'),
34   customer  => t8('Customer'),
35   vendor    => t8('Vendor'),
36   part      => t8('Part'),
37 );
38
39 our @types = qw(text textfield htmlfield number date bool select customer vendor part); # timestamp
40
41 #
42 # actions
43 #
44
45 sub action_list {
46   my ($self) = @_;
47
48   my $configs = SL::DB::Manager::CustomVariableConfig->get_all_sorted(where => [ module => $self->module ]);
49
50   $self->setup_list_action_bar;
51   $::form->header;
52   $self->render('custom_variable_config/list',
53                 title   => t8('List of custom variables'),
54                 CONFIGS => $configs);
55 }
56
57 sub action_new {
58   my ($self) = @_;
59
60   $self->config(SL::DB::CustomVariableConfig->new(module => $self->module));
61   $self->show_form(title => t8('Add custom variable'));
62 }
63
64 sub show_form {
65   my ($self, %params) = @_;
66
67   $self->flags({
68     map { split m/=/, $_, 2 }
69     split m/:/, ($self->config->flags || '')
70   });
71
72   $params{all_partsgroups} = SL::DB::Manager::PartsGroup->get_all();
73
74   $::request->layout->use_javascript("${_}.js") for qw(jquery.selectboxes jquery.multiselect2side);
75   $self->setup_form_action_bar;
76   $self->render('custom_variable_config/form', %params);
77 }
78
79 sub action_edit {
80   my ($self) = @_;
81
82   $self->show_form(title => t8('Edit custom variable'));
83 }
84
85 sub action_create {
86   my ($self) = @_;
87
88   $self->config(SL::DB::CustomVariableConfig->new);
89   $self->create_or_update;
90 }
91
92 sub action_update {
93   my ($self) = @_;
94   $self->create_or_update;
95 }
96
97 sub action_destroy {
98   my ($self) = @_;
99
100   # delete relationship to partsgroups (for filter) before cvar can be deleted
101   $self->config->update_attributes(partsgroups => []);
102
103   if (eval { $self->config->delete; 1; }) {
104     flash_later('info',  t8('The custom variable has been deleted.'));
105   } else {
106     flash_later('error', t8('The custom variable is in use and cannot be deleted.'));
107   }
108
109   $self->redirect_to(action => 'list', module => $self->module);
110 }
111
112 sub action_reorder {
113   my ($self) = @_;
114
115   SL::DB::CustomVariableConfig->reorder_list(@{ $::form->{cvarcfg_id} || [] });
116
117   $self->render(\'', { type => 'json' }); # ' make emacs happy
118 }
119
120 #
121 # filters
122 #
123
124 sub check_auth {
125   $::auth->assert('config');
126 }
127
128 sub check_module {
129   my ($self)          = @_;
130
131   $::form->{module} ||= 'CT';
132   my $mod_desc        = first { $_->{module} eq $::form->{module} } @{ $self->modules };
133   die "Invalid 'module' parameter '" . $::form->{module} . "'" if !$mod_desc;
134
135   $self->module($mod_desc->{module});
136   $self->module_description($mod_desc->{description});
137 }
138
139 sub load_config {
140   my ($self) = @_;
141
142   $self->config(SL::DB::CustomVariableConfig->new(id => $::form->{id})->load);
143 }
144
145 #
146 # helpers
147 #
148
149 sub get_translation {
150   my ($self, $type) = @_;
151
152   return $translations{$type};
153 }
154
155 sub init_translated_types {
156   my ($self) = @_;
157
158   return [ map { { type => $_, translation => $translations{$_} } } @types ];
159 }
160
161 sub init_modules {
162   my ($self, %params) = @_;
163
164   return [ sort { $a->{description}->translated cmp $b->{description}->translated } (
165     { module => 'CT',               description => t8('Customers and vendors')          },
166     { module => 'Contacts',         description => t8('Contact persons')                },
167     { module => 'IC',               description => t8('Parts, services and assemblies') },
168     { module => 'Projects',         description => t8('Projects')                       },
169     { module => 'RequirementSpecs', description => t8('Requirement Specs')              },
170     { module => 'ShipTo',           description => t8('Shipping Address')               },
171   )];
172 }
173
174 sub create_or_update {
175   my ($self) = @_;
176   my $is_new = !$self->config->id;
177
178   my $params = delete($::form->{config}) || { };
179   delete $params->{id};
180
181   if ($self->module eq 'IC') {
182     $params->{partsgroups} = [] if !$params->{flag_partsgroup_filter};
183   } else {
184     delete $params->{flag_partsgroup_filter};
185     $params->{partsgroups} = [];
186   }
187
188   $params->{partsgroups}       ||= []; # The list is empty, if control is not send by the browser.
189   $params->{default_value}       = $::form->parse_amount(\%::myconfig, $params->{default_value}) if $params->{type} eq 'number';
190   $params->{included_by_default} = 0                                                             if !$params->{includeable};
191   $params->{flags}               = join ':', map { m/^flag_(.*)/; "${1}=" . delete($params->{$_}) } grep { m/^flag_/ } keys %{ $params };
192
193   $self->config->assign_attributes(%{ $params }, module => $self->module);
194
195   my @errors = $self->config->validate;
196
197   if (@errors) {
198     flash('error', @errors);
199     $self->show_form(title => $is_new ? t8('Add new custom variable') : t8('Edit custom variable'));
200     return;
201   }
202
203   SL::DB->client->with_transaction(sub {
204     my $dbh = SL::DB->client->dbh;
205
206     $self->config->save;
207     $self->_set_cvar_validity() if $is_new;
208     1;
209   }) or do { die SL::DB->client->error };
210
211   flash_later('info', $is_new ? t8('The custom variable has been created.') : t8('The custom variable has been saved.'));
212   $self->redirect_to(action => 'list', module => $self->module);
213 }
214
215 sub _set_cvar_validity {
216   my ($self) = @_;
217
218   my $flags = {
219     map { split m/=/, $_, 2 }
220     split m/:/, ($self->config->flags || '')
221   };
222
223   # nothing to do to set valid
224   return if !$flags->{defaults_to_invalid};
225
226   my $all_parts  = SL::DB::Manager::Part->get_all(where => [ or => [ obsolete => 0, obsolete => undef ] ]);
227   foreach my $part (@{ $all_parts }) {
228     SL::DB::CustomVariableValidity->new(config_id => $self->config->id, trans_id => $part->id)->save;
229   }
230 }
231
232 sub setup_list_action_bar {
233   my ($self) = @_;
234
235   for my $bar ($::request->layout->get('actionbar')) {
236     $bar->add(
237       action => [
238         t8('Add'),
239         link => $self->url_for(action => 'new', module => $self->module),
240       ],
241     );
242   }
243 }
244
245 sub setup_form_action_bar {
246   my ($self) = @_;
247
248   my $is_new = !$self->config->id;
249
250   for my $bar ($::request->layout->get('actionbar')) {
251     $bar->add(
252       combobox => [
253         action => [
254           t8('Save'),
255           submit    => [ '#form', { action => 'CustomVariableConfig/' . ($is_new ? 'create' : 'update') } ],
256           checks    => [ 'check_prerequisites' ],
257           accesskey => 'enter',
258         ],
259
260         action => [
261           t8('Save as new'),
262           submit => [ '#form', { action => 'CustomVariableConfig/create'} ],
263           checks => [ 'check_prerequisites' ],
264           not_if => $is_new,
265         ],
266       ], # end of combobox "Save"
267
268       action => [
269         t8('Delete'),
270         submit   => [ '#form', { action => 'CustomVariableConfig/destroy' } ],
271         confirm  => t8('Do you really want to delete this object?'),
272         disabled => $is_new ? t8('This object has not been saved yet.') : undef,
273       ],
274
275       'separator',
276
277       link => [
278         t8('Abort'),
279         link => $self->url_for(action => 'list', module => $self->module),
280       ],
281     );
282   }
283 }
284
285 1;