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