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