epic-ts
[kivitendo-erp.git] / SL / CVar.pm
1 package CVar;
2
3 use strict;
4
5 use Carp;
6 use List::MoreUtils qw(any);
7 use List::Util qw(first);
8 use Scalar::Util qw(blessed);
9 use Data::Dumper;
10
11 use SL::DBUtils;
12 use SL::MoreCommon qw(listify);
13 use SL::Util qw(trim);
14 use SL::DB;
15
16 sub get_configs {
17   $main::lxdebug->enter_sub();
18
19   my $self     = shift;
20   my %params   = @_;
21
22   my $myconfig = \%main::myconfig;
23   my $form     = $main::form;
24
25   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
26
27   my ($where, @values);
28   if ($params{module}) {
29     $where = 'WHERE module = ?';
30     push @values, $params{module};
31   }
32
33   my $query    = <<SQL;
34     SELECT *, date_trunc('seconds', localtimestamp) AS current_timestamp
35     FROM custom_variable_configs $where ORDER BY sortkey
36 SQL
37
38   $::form->{CVAR_CONFIGS} = {} unless 'HASH' eq ref $::form->{CVAR_CONFIGS};
39   if (!$::form->{CVAR_CONFIGS}->{$params{module}}) {
40     my $configs  = selectall_hashref_query($form, $dbh, $query, @values);
41
42     foreach my $config (@{ $configs }) {
43       if ($config->{type} eq 'select') {
44         $config->{OPTIONS} = [ map { { 'value' => $_ } } split(m/\#\#/, $config->{options}) ];
45
46       } elsif ($config->{type} eq 'number') {
47         $config->{precision} = $1 if ($config->{options} =~ m/precision=(\d+)/i);
48
49       } elsif ($config->{type} eq 'textfield') {
50         $config->{width}  = 30;
51         $config->{height} =  5;
52         $config->{width}  = $1 if ($config->{options} =~ m/width=(\d+)/i);
53         $config->{height} = $1 if ($config->{options} =~ m/height=(\d+)/i);
54
55       } elsif ($config->{type} eq 'text') {
56         $config->{maxlength} = $1 if ($config->{options} =~ m/maxlength=(\d+)/i);
57
58       }
59
60       $self->_unpack_flags($config);
61
62       my $cvar_config = SL::DB::CustomVariableConfig->new(id => $config->{id})->load;
63       @{$config->{'partsgroups'}} = map {$_->id} @{$cvar_config->partsgroups};
64
65     }
66     $::form->{CVAR_CONFIGS}->{$params{module}} = $configs;
67   }
68
69   $main::lxdebug->leave_sub();
70
71   return $::form->{CVAR_CONFIGS}->{$params{module}};
72 }
73
74 sub _unpack_flags {
75   $main::lxdebug->enter_sub();
76
77   my $self   = shift;
78   my $config = shift;
79
80   foreach my $flag (split m/:/, $config->{flags}) {
81     if ($flag =~ m/(.*?)=(.*)/) {
82       $config->{"flag_${1}"}    = $2;
83     } else {
84       $config->{"flag_${flag}"} = 1;
85     }
86   }
87
88   $main::lxdebug->leave_sub();
89 }
90
91 sub get_custom_variables {
92   $main::lxdebug->enter_sub();
93
94   my $self     = shift;
95   my %params   = @_;
96
97   Common::check_params(\%params, qw(module));
98
99   my $myconfig = \%main::myconfig;
100   my $form     = $main::form;
101
102   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
103
104   my $sub_module = $params{sub_module} ? $params{sub_module} : '';
105
106   my $q_var    =
107     qq|SELECT text_value, timestamp_value, timestamp_value::date AS date_value, number_value, bool_value
108        FROM custom_variables
109        WHERE (config_id = ?) AND (trans_id = ?) AND (sub_module = ?)|;
110   my $h_var    = prepare_query($form, $dbh, $q_var);
111
112   my $custom_variables = $self->get_configs(module => $params{module});
113
114   foreach my $cvar (@{ $custom_variables }) {
115     if ($cvar->{type} eq 'textfield') {
116       $cvar->{width}  = 30;
117       $cvar->{height} =  5;
118
119       $cvar->{width}  = $1 if ($cvar->{options} =~ m/width=(\d+)/i);
120       $cvar->{height} = $1 if ($cvar->{options} =~ m/height=(\d+)/i);
121
122     } elsif ($cvar->{type} eq 'text') {
123       $cvar->{maxlength} = $1 if ($cvar->{options} =~ m/maxlength=(\d+)/i);
124
125     } elsif ($cvar->{type} eq 'number') {
126       $cvar->{precision} = $1 if ($cvar->{options} =~ m/precision=(\d+)/i);
127
128     } elsif ($cvar->{type} eq 'select') {
129       $cvar->{OPTIONS} = [ map { { 'value' => $_ } } split(m/\#\#/, $cvar->{options}) ];
130     }
131
132     my ($act_var, $valid);
133     if ($params{trans_id}) {
134       my @values = (conv_i($cvar->{id}), conv_i($params{trans_id}), $sub_module);
135
136       do_statement($form, $h_var, $q_var, @values);
137       $act_var = $h_var->fetchrow_hashref();
138
139       $valid = $self->get_custom_variables_validity(config_id => $cvar->{id}, trans_id => $params{trans_id}, sub_module => $params{sub_module});
140     } else {
141       $valid = !$cvar->{flag_defaults_to_invalid};
142     }
143
144     if ($act_var) {
145       $cvar->{value} = $cvar->{type} eq 'date'      ? $act_var->{date_value}
146                      : $cvar->{type} eq 'timestamp' ? $act_var->{timestamp_value}
147                      : $cvar->{type} eq 'number'    ? $act_var->{number_value}
148                      : $cvar->{type} eq 'customer'  ? $act_var->{number_value}
149                      : $cvar->{type} eq 'vendor'    ? $act_var->{number_value}
150                      : $cvar->{type} eq 'part'      ? $act_var->{number_value}
151                      : $cvar->{type} eq 'bool'      ? $act_var->{bool_value}
152                      :                                $act_var->{text_value};
153       $cvar->{valid} = $valid;
154     } else {
155       $cvar->{valid} = $valid // 1;
156
157       if ($cvar->{type} eq 'date') {
158         if ($cvar->{default_value} eq 'NOW') {
159           $cvar->{value} = $cvar->{current_date};
160         } else {
161           $cvar->{value} = $cvar->{default_value};
162         }
163
164       } elsif ($cvar->{type} eq 'timestamp') {
165         if ($cvar->{default_value} eq 'NOW') {
166           $cvar->{value} = $cvar->{current_timestamp};
167         } else {
168           $cvar->{value} = $cvar->{default_value};
169         }
170
171       } elsif ($cvar->{type} eq 'bool') {
172         $cvar->{value} = $cvar->{default_value} * 1;
173
174       } elsif ($cvar->{type} eq 'number') {
175         $cvar->{value} = $cvar->{default_value} * 1 if ($cvar->{default_value} ne '');
176
177       } else {
178         $cvar->{value} = $cvar->{default_value};
179       }
180     }
181
182     if ($cvar->{type} eq 'number') {
183       $cvar->{value} = $form->format_amount($myconfig, $cvar->{value} * 1, $cvar->{precision});
184     } elsif ($cvar->{type} eq 'customer') {
185       require SL::DB::Customer;
186       $cvar->{value} = SL::DB::Manager::Customer->find_by(id => $cvar->{value} * 1);
187     } elsif ($cvar->{type} eq 'vendor') {
188       require SL::DB::Vendor;
189       $cvar->{value} = SL::DB::Manager::Vendor->find_by(id => $cvar->{value} * 1);
190     } elsif ($cvar->{type} eq 'part') {
191       require SL::DB::Part;
192       $cvar->{value} = SL::DB::Manager::Part->find_by(id => $cvar->{value} * 1);
193     }
194   }
195
196   $h_var->finish();
197
198   $main::lxdebug->leave_sub();
199
200   return $custom_variables;
201 }
202
203 sub save_custom_variables {
204   my ($self, %params) = @_;
205   $main::lxdebug->enter_sub();
206
207   my $rc = SL::DB->client->with_transaction(\&_save_custom_variables, $self, %params);
208
209   $::lxdebug->leave_sub;
210   return $rc;
211 }
212
213 sub _save_custom_variables {
214   my $self     = shift;
215   my %params   = @_;
216
217   Common::check_params(\%params, qw(module trans_id variables));
218
219   my $myconfig = \%main::myconfig;
220   my $form     = $main::form;
221
222   my $dbh      = $params{dbh} || SL::DB->client->dbh;
223
224   my @configs  = $params{configs} ? @{ $params{configs} } : grep { $_->{module} eq $params{module} } @{ CVar->get_configs() };
225
226   my $query    =
227     qq|DELETE FROM custom_variables
228        WHERE (trans_id  = ?)
229          AND (config_id IN (SELECT DISTINCT id
230                             FROM custom_variable_configs
231                             WHERE module = ?))|;
232   my @values   = (conv_i($params{trans_id}), $params{module});
233
234   if ($params{sub_module}) {
235     $query .= qq| AND (sub_module = ?)|;
236     push @values, $params{sub_module};
237   }
238
239   do_query($form, $dbh, $query, @values);
240
241   $query  =
242     qq|INSERT INTO custom_variables (config_id, sub_module, trans_id, bool_value, timestamp_value, text_value, number_value)
243        VALUES                       (?,         ?,          ?,        ?,          ?,               ?,          ?)|;
244   my $sth = prepare_query($form, $dbh, $query);
245
246   foreach my $config (@configs) {
247     if ($params{save_validity}) {
248       my $valid_index = "$params{name_prefix}cvar_$config->{name}$params{name_postfix}_valid";
249       my $new_valid   = $params{variables}{$valid_index} || $params{always_valid} ? 1 : 0;
250       my $old_valid   = $self->get_custom_variables_validity(trans_id => $params{trans_id}, config_id => $config->{id});
251
252       $self->save_custom_variables_validity(trans_id  => $params{trans_id},
253                                             config_id => $config->{id},
254                                             validity  => $new_valid,
255                                            );
256
257       if (!$new_valid || !$old_valid) {
258         # When activating a cvar (old_valid == 0 && new_valid == 1)
259         # the input to hold the variable's value wasn't actually
260         # rendered, meaning saving the value now would only save an
261         # empty value/the value 0. This means that the next time the
262         # form is rendered, an existing value is found and used
263         # instead of the variable's default value from the
264         # configuration. Therefore don't save the values in such
265         # cases.
266         next;
267       }
268     }
269
270     my @values = (conv_i($config->{id}), "$params{sub_module}", conv_i($params{trans_id}));
271
272     my $value  = $params{variables}->{"$params{name_prefix}cvar_$config->{name}$params{name_postfix}"};
273
274     if (($config->{type} eq 'text') || ($config->{type} eq 'textfield') || ($config->{type} eq 'select')) {
275       push @values, undef, undef, $value, undef;
276
277     } elsif (($config->{type} eq 'date') || ($config->{type} eq 'timestamp')) {
278       push @values, undef, conv_date($value), undef, undef;
279
280     } elsif ($config->{type} eq 'number') {
281       push @values, undef, undef, undef, conv_i($form->parse_amount($myconfig, $value));
282
283     } elsif ($config->{type} eq 'bool') {
284       push @values, $value ? 't' : 'f', undef, undef, undef;
285     } elsif (any { $config->{type} eq $_ } qw(customer vendor part)) {
286       push @values, undef, undef, undef, $value * 1;
287     }
288
289     do_statement($form, $sth, $query, @values);
290   }
291
292   $sth->finish();
293
294   return 1;
295 }
296
297 sub render_inputs {
298   $main::lxdebug->enter_sub(2);
299
300   my $self     = shift;
301   my %params   = @_;
302
303   Common::check_params(\%params, qw(variables));
304
305   my $myconfig = \%main::myconfig;
306   my $form     = $main::form;
307
308   my %options  = ( name_prefix           => "$params{name_prefix}",
309                    name_postfix          => "$params{name_postfix}",
310                    hide_non_editable     => $params{hide_non_editable},
311                    show_disabled_message => $params{show_disabled_message},
312                  );
313
314   # should this cvar be filtered by partsgroups?
315   foreach my $var (@{ $params{variables} }) {
316     if ($var->{flag_partsgroup_filter}) {
317       if (!$params{partsgroup_id} || (!grep {$params{partsgroup_id} == $_} @{ $var->{partsgroups} })) {
318         $var->{partsgroup_filtered} = 1;
319       }
320     }
321
322     $var->{HTML_CODE} = $form->parse_html_template('amcvar/render_inputs',     { var => $var, %options });
323     $var->{VALID_BOX} = $form->parse_html_template('amcvar/render_checkboxes', { var => $var, %options });
324   }
325
326   $main::lxdebug->leave_sub(2);
327 }
328
329 sub render_search_options {
330   $main::lxdebug->enter_sub();
331
332   my $self     = shift;
333   my %params   = @_;
334
335   Common::check_params(\%params, qw(variables));
336
337   my $myconfig = \%main::myconfig;
338   my $form     = $main::form;
339
340   $params{hidden_cvar_filters} = $myconfig->{hide_cvar_search_options};
341
342   $params{include_prefix}   = 'l_' unless defined($params{include_prefix});
343   $params{include_value}  ||= '1';
344   $params{filter_prefix}  ||= '';
345
346   my $filter  = $form->parse_html_template('amcvar/search_filter',  \%params);
347   my $include = $form->parse_html_template('amcvar/search_include', \%params);
348
349   $main::lxdebug->leave_sub();
350
351   return ($filter, $include);
352 }
353
354 sub build_filter_query {
355   $main::lxdebug->enter_sub();
356
357   my $self     = shift;
358   my %params   = @_;
359
360   Common::check_params(\%params, qw(module trans_id_field filter));
361
362   my $myconfig = \%main::myconfig;
363   my $form     = $main::form;
364
365   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
366
367   my $configs  = $self->get_configs(%params);
368
369   my (@where, @values);
370
371   foreach my $config (@{ $configs }) {
372     next unless ($config->{searchable});
373
374     my $name = "cvar_$config->{name}";
375
376     my (@sub_values, @sub_where, $not);
377
378     if (($config->{type} eq 'text') || ($config->{type} eq 'textfield')) {
379       next unless ($params{filter}->{$name});
380
381       push @sub_where,  qq|cvar.text_value ILIKE ?|;
382       push @sub_values, like($params{filter}->{$name});
383
384     } elsif ($config->{type} eq 'select') {
385       next unless ($params{filter}->{$name});
386
387       push @sub_where,  qq|cvar.text_value = ?|;
388       push @sub_values, $params{filter}->{$name};
389
390     } elsif (($config->{type} eq 'date') || ($config->{type} eq 'timestamp')) {
391       my $name_from = "${name}_from";
392       my $name_to   = "${name}_to";
393
394       if ($params{filter}->{$name_from}) {
395         push @sub_where,  qq|cvar.timestamp_value >= ?|;
396         push @sub_values, conv_date($params{filter}->{$name_from});
397       }
398
399       if ($params{filter}->{$name_to}) {
400         push @sub_where,  qq|cvar.timestamp_value <= ?|;
401         push @sub_values, conv_date($params{filter}->{$name_to});
402       }
403
404     } elsif ($config->{type} eq 'number') {
405       next if ($params{filter}->{$name} eq '');
406
407       my $f_op = $params{filter}->{"${name}_qtyop"};
408
409       my $op;
410       if ($f_op eq '==') {
411         $op  = '=';
412
413       } elsif ($f_op eq '=/=') {
414         $not = 'NOT';
415         $op  = '<>';
416
417       } elsif ($f_op eq '<') {
418         $not = 'NOT';
419         $op  = '>=';
420
421       } elsif ($f_op eq '<=') {
422         $not = 'NOT';
423         $op  = '>';
424
425       } elsif (($f_op eq '>') || ($f_op eq '>=')) {
426         $op  = $f_op;
427
428       } else {
429         $op  = '=';
430       }
431
432       push @sub_where,  qq|cvar.number_value $op ?|;
433       push @sub_values, $form->parse_amount($myconfig, trim($params{filter}->{$name}));
434
435     } elsif ($config->{type} eq 'bool') {
436       next unless ($params{filter}->{$name});
437
438       $not = 'NOT' if ($params{filter}->{$name} eq 'no');
439       push @sub_where,  qq|COALESCE(cvar.bool_value, false) = TRUE|;
440     } elsif (any { $config->{type} eq $_ } qw(customer vendor)) {
441       next unless $params{filter}->{$name};
442
443       my $table = $config->{type};
444       push @sub_where, qq|cvar.number_value * 1 IN (SELECT id FROM $table WHERE name ILIKE ?)|;
445       push @sub_values, like($params{filter}->{$name});
446     } elsif ($config->{type} eq 'part') {
447       next unless $params{filter}->{$name};
448
449       push @sub_where, qq|cvar.number_value * 1 IN (SELECT id FROM parts WHERE partnumber ILIKE ?)|;
450       push @sub_values, like($params{filter}->{$name});
451     }
452
453     if (@sub_where) {
454       add_token(\@sub_where, \@sub_values, col => 'cvar.sub_module', val => $params{sub_module} || '');
455
456       push @where,
457         qq|$not EXISTS(
458              SELECT cvar.id
459              FROM custom_variables cvar
460              LEFT JOIN custom_variable_configs cvarcfg ON (cvar.config_id = cvarcfg.id)
461              WHERE (cvarcfg.module = ?)
462                AND (cvarcfg.id     = ?)
463                AND (cvar.trans_id  = $params{trans_id_field})
464                AND | . join(' AND ', map { "($_)" } @sub_where) . qq|)|;
465       push @values, $params{module}, conv_i($config->{id}), @sub_values;
466     }
467   }
468
469   my $query = join ' AND ', @where;
470
471   $main::lxdebug->leave_sub();
472
473   return ($query, @values);
474 }
475
476 sub add_custom_variables_to_report {
477   $main::lxdebug->enter_sub();
478
479   my $self      = shift;
480   my %params    = @_;
481
482   Common::check_params(\%params, qw(module trans_id_field column_defs data configs));
483
484   my $myconfig  = \%main::myconfig;
485   my $form      = $main::form;
486   my $locale    = $main::locale;
487
488   my $dbh       = $params{dbh} || $form->get_standard_dbh($myconfig);
489
490   my $configs   = [ grep { $_->{includeable} && $params{column_defs}->{"cvar_$_->{name}"}->{visible} } @{ $params{configs} } ];
491
492   if (!scalar(@{ $params{data} }) || ! scalar(@{ $configs })) {
493     $main::lxdebug->leave_sub();
494     return;
495   }
496
497   # allow sub_module to be a coderef or a fixed value
498   if (ref $params{sub_module} ne 'CODE') {
499     my $sub_module = "$params{sub_module}";
500     $params{sub_module} = sub { $sub_module };
501   }
502
503   my %cfg_map   = map { $_->{id} => $_ } @{ $configs };
504   my @cfg_ids   = keys %cfg_map;
505
506   my $query     =
507     qq|SELECT text_value, timestamp_value, timestamp_value::date AS date_value, number_value, bool_value, config_id
508        FROM custom_variables
509        WHERE (config_id IN (| . join(', ', ('?') x scalar(@cfg_ids)) . qq|))
510          AND (trans_id = ?)
511          AND (sub_module = ?)|;
512   my $sth       = prepare_query($form, $dbh, $query);
513
514   foreach my $row (@{ $params{data} }) {
515     do_statement($form, $sth, $query, @cfg_ids, conv_i($row->{$params{trans_id_field}}), $params{sub_module}->($row));
516
517     while (my $ref = $sth->fetchrow_hashref()) {
518       my $cfg = $cfg_map{$ref->{config_id}};
519
520       $row->{"cvar_$cfg->{name}"} =
521           $cfg->{type} eq 'date'      ? $ref->{date_value}
522         : $cfg->{type} eq 'timestamp' ? $ref->{timestamp_value}
523         : $cfg->{type} eq 'number'    ? $form->format_amount($myconfig, $ref->{number_value} * 1, $cfg->{precision})
524         : $cfg->{type} eq 'customer'  ? (SL::DB::Manager::Customer->find_by(id => 1*$ref->{number_value}) || SL::DB::Customer->new)->name
525         : $cfg->{type} eq 'vendor'    ? (SL::DB::Manager::Vendor->find_by(id => 1*$ref->{number_value})   || SL::DB::Vendor->new)->name
526         : $cfg->{type} eq 'part'      ? (SL::DB::Manager::Part->find_by(id => 1*$ref->{number_value})     || SL::DB::Part->new)->partnumber
527         : $cfg->{type} eq 'bool'      ? ($ref->{bool_value} ? $locale->text('Yes') : $locale->text('No'))
528         :                               $ref->{text_value};
529     }
530   }
531
532   $sth->finish();
533
534   $main::lxdebug->leave_sub();
535 }
536
537 sub get_field_format_list {
538   $main::lxdebug->enter_sub();
539
540   my $self          = shift;
541   my %params        = @_;
542
543   Common::check_params(\%params, qw(module));
544
545   my $myconfig      = \%main::myconfig;
546   my $form          = $main::form;
547
548   my $dbh           = $params{dbh} || $form->get_standard_dbh($myconfig);
549
550   my $configs       = $self->get_configs(%params);
551
552   my $date_fields   = [];
553   my $number_fields = {};
554
555   foreach my $config (@{ $configs }) {
556     my $name = "$params{prefix}cvar_$config->{name}";
557
558     if ($config->{type} eq 'date') {
559       push @{ $date_fields }, $name;
560
561     } elsif ($config->{type} eq 'number') {
562       $number_fields->{$config->{precision}} ||= [];
563       push @{ $number_fields->{$config->{precision}} }, $name;
564     }
565   }
566
567   $main::lxdebug->leave_sub();
568
569   return ($date_fields, $number_fields);
570 }
571
572 sub save_custom_variables_validity {
573   my ($self, %params) = @_;
574   $main::lxdebug->enter_sub();
575
576   my $rc = SL::DB->client->with_transaction(\&_save_custom_variables_validity, $self, %params);
577
578   $::lxdebug->leave_sub;
579   return $rc;
580 }
581
582 sub _save_custom_variables_validity {
583   my $self     = shift;
584   my %params   = @_;
585
586   Common::check_params(\%params, qw(config_id trans_id validity));
587
588   my $myconfig = \%main::myconfig;
589   my $form     = $main::form;
590
591   my $dbh      = $params{dbh} || SL::DB->client->dbh;
592
593   my (@where, @values);
594   add_token(\@where, \@values, col => "config_id", val => $params{config_id}, esc => \&conv_i);
595   add_token(\@where, \@values, col => "trans_id",  val => $params{trans_id},  esc => \&conv_i);
596
597   my $where = scalar @where ? "WHERE " . join ' AND ', @where : '';
598   my $query = qq|DELETE FROM custom_variables_validity $where|;
599
600   do_query($form, $dbh, $query, @values);
601
602   $query  =
603     qq|INSERT INTO custom_variables_validity (config_id, trans_id)
604        VALUES                                (?,         ?       )|;
605   my $sth = prepare_query($form, $dbh, $query);
606
607   unless ($params{validity}) {
608     foreach my $config_id (listify($params{config_id})) {
609       foreach my $trans_id (listify($params{trans_id})) {
610         do_statement($form, $sth, $query, conv_i($config_id), conv_i($trans_id));
611       }
612     }
613   }
614
615   $sth->finish();
616
617   return 1;
618 }
619
620 my %_validity_sub_module_mapping = (
621   orderitems           => { table => 'orderitems',           result_column => 'parts_id', trans_id_column => 'id', },
622   delivery_order_items => { table => 'delivery_order_items', result_column => 'parts_id', trans_id_column => 'id', },
623   invoice              => { table => 'invoice',              result_column => 'parts_id', trans_id_column => 'id', },
624 );
625
626 sub get_custom_variables_validity {
627   my $self     = shift;
628   my %params   = @_;
629
630   Common::check_params(\%params, qw(config_id trans_id));
631
632   my $myconfig = \%main::myconfig;
633   my $form     = $main::form;
634
635   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
636
637   my $query;
638
639   if ($params{sub_module}) {
640     my %mapping = %{ $_validity_sub_module_mapping{ $params{sub_module} } || croak("Invalid sub_module '" . $params{sub_module} . "'") };
641     $query = <<SQL;
642       SELECT cvv.id
643       FROM $mapping{table} mt
644       LEFT JOIN custom_variables_validity cvv ON (cvv.trans_id = mt.$mapping{result_column})
645       WHERE (cvv.config_id                = ?)
646         AND (mt.$mapping{trans_id_column} = ?)
647       LIMIT 1
648 SQL
649   } else {
650     $query = <<SQL;
651       SELECT id
652       FROM custom_variables_validity
653       WHERE (config_id = ?)
654         AND (trans_id  = ?)
655       LIMIT 1
656 SQL
657   }
658
659   my ($invalid) = selectfirst_array_query($form, $dbh, $query, conv_i($params{config_id}), conv_i($params{trans_id}));
660
661   return !$invalid;
662 }
663
664 sub custom_variables_validity_by_trans_id {
665   $main::lxdebug->enter_sub(2);
666
667   my $self     = shift;
668   my %params   = @_;
669
670   return sub { 0 } unless $params{trans_id};
671
672   my $myconfig = \%main::myconfig;
673   my $form     = $main::form;
674
675   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
676
677   my $query    = qq|SELECT DISTINCT config_id FROM custom_variables_validity WHERE trans_id = ?|;
678
679   my %invalids = map { +($_->{config_id} => 1) } selectall_hashref_query($form, $dbh, $query, $params{trans_id});
680
681   $main::lxdebug->leave_sub(2);
682
683   return sub { !$invalids{+shift} };
684 }
685
686 sub parse {
687   my ($self, $value, $config) = @_;
688
689   return $::form->parse_amount(\%::myconfig, $value)          if $config->{type} eq 'number';
690   return DateTime->from_lxoffice($value)                      if $config->{type} eq 'date';
691   return !ref $value ? SL::DB::Manager::Customer->find_by(id => $value * 1) : $value  if $config->{type} eq 'customer';
692   return !ref $value ? SL::DB::Manager::Vendor->find_by(id => $value * 1)   : $value  if $config->{type} eq 'vendor';
693   return !ref $value ? SL::DB::Manager::Part->find_by(id => $value * 1)     : $value  if $config->{type} eq 'part';
694   return $value;
695 }
696
697 sub format_to_template {
698   my ($self, $value, $config) = @_;
699   # stupid template expects everything formated. except objects
700   # do not use outside of print routines for legacy templates
701
702   return $::form->format_amount(\%::myconfig, $value) if $config->{type} eq 'number';
703   return $value->to_lxoffice if $config->{type} eq 'date' && blessed $value && $value->can('to_lxoffice');
704   return $value;
705 }
706
707 sub get_non_editable_ic_cvars {
708   $main::lxdebug->enter_sub(2);
709   my $self     = shift;
710   my %params   = @_;
711
712   Common::check_params(\%params, qw(form dbh row sub_module may_converted_from));
713   my $form               = $params{form};
714   my $dbh                = $params{dbh};
715   my $row                = $params{row};
716   my $sub_module         = $params{sub_module};
717   my $may_converted_from = $params{may_converted_from};
718
719   my $cvars;
720   if (! $form->{"${sub_module}_id_${row}"}) {
721     my $conv_from = 0;
722     foreach (@{ $may_converted_from }) {
723       if ($form->{"converted_from_${_}_id_$row"}) {
724         $cvars = CVar->get_custom_variables(dbh        => $dbh,
725                                             module     => 'IC',
726                                             sub_module => $_,
727                                             trans_id   => $form->{"converted_from_${_}_id_$row"},
728                                            );
729         $conv_from = 1;
730         last;
731       }
732     }
733     # get values for CVars from master data for new items
734     if (!$conv_from) {
735       $cvars = CVar->get_custom_variables(dbh      => $dbh,
736                                           module   => 'IC',
737                                           trans_id => $form->{"id_$row"},
738                                          );
739     }
740   } else {
741     # get values for CVars from custom_variables for existing items
742     $cvars = CVar->get_custom_variables(dbh        => $dbh,
743                                         module     => 'IC',
744                                         sub_module => $sub_module,
745                                         trans_id   => $form->{"${sub_module}_id_${row}"},
746                                        );
747   }
748   # map only non-editable CVars to form
749   foreach (@{ $cvars }) {
750     next if $_->{flag_editable};
751     $form->{"ic_cvar_$_->{name}_$row"} = $_->{value}
752   }
753
754   $main::lxdebug->leave_sub(2);
755 }
756
757 1;
758
759 __END__
760
761 =head1 NAME
762
763 SL::CVar.pm - Custom Variables module
764
765 =head1 SYNOPSIS
766
767   # dealing with configs
768
769   my $all_configs = CVar->get_configs()
770
771   # dealing with custom vars
772
773   CVar->get_custom_variables(module => 'ic')
774
775 =head2 VALIDITY
776
777 Suppose the following scenario:
778
779 You have a lot of parts in your database, and a set of properties configured. Now not every part has every of these properties, some combinations will just make no sense. In order to clean up your inputs a bit, you want to mark certain combinations as invalid, blocking them from modification and possibly display.
780
781 Validity is assumed. If you modify validity, you actually save B<invalidity>.
782 Invalidity is saved as a function of config_id, and the trans_id
783
784 In the naive way, disable an attribute for a specific id (simple)
785
786 =cut