37d865ae9b4faacb757401841604bc3b454a021b
[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     my @values = (conv_i($config->{id}), "$params{sub_module}", conv_i($params{trans_id}));
248
249     my $value  = $params{variables}->{"$params{name_prefix}cvar_$config->{name}$params{name_postfix}"};
250
251     if (($config->{type} eq 'text') || ($config->{type} eq 'textfield') || ($config->{type} eq 'select')) {
252       push @values, undef, undef, $value, undef;
253
254     } elsif (($config->{type} eq 'date') || ($config->{type} eq 'timestamp')) {
255       push @values, undef, conv_date($value), undef, undef;
256
257     } elsif ($config->{type} eq 'number') {
258       push @values, undef, undef, undef, conv_i($form->parse_amount($myconfig, $value));
259
260     } elsif ($config->{type} eq 'bool') {
261       push @values, $value ? 't' : 'f', undef, undef, undef;
262     } elsif (any { $config->{type} eq $_ } qw(customer vendor part)) {
263       push @values, undef, undef, undef, $value * 1;
264     }
265
266     do_statement($form, $sth, $query, @values);
267
268     if ($params{save_validity}) {
269       my $valid_index = "$params{name_prefix}cvar_$config->{name}$params{name_postfix}_valid";
270       $self->save_custom_variables_validity(trans_id  => $params{trans_id},
271                                             config_id => $config->{id},
272                                             validity  => ($params{variables}{$valid_index} || $params{always_valid} ? 1 : 0)
273                                            );
274     }
275   }
276
277   $sth->finish();
278
279   return 1;
280 }
281
282 sub render_inputs {
283   $main::lxdebug->enter_sub(2);
284
285   my $self     = shift;
286   my %params   = @_;
287
288   Common::check_params(\%params, qw(variables));
289
290   my $myconfig = \%main::myconfig;
291   my $form     = $main::form;
292
293   my %options  = ( name_prefix           => "$params{name_prefix}",
294                    name_postfix          => "$params{name_postfix}",
295                    hide_non_editable     => $params{hide_non_editable},
296                    show_disabled_message => $params{show_disabled_message},
297                  );
298
299   # should this cvar be filtered by partsgroups?
300   foreach my $var (@{ $params{variables} }) {
301     if ($var->{flag_partsgroup_filter}) {
302       if (!$params{partsgroup_id} || (!grep {$params{partsgroup_id} == $_} @{ $var->{partsgroups} })) {
303         $var->{partsgroup_filtered} = 1;
304       }
305     }
306
307     $var->{HTML_CODE} = $form->parse_html_template('amcvar/render_inputs',     { var => $var, %options });
308     $var->{VALID_BOX} = $form->parse_html_template('amcvar/render_checkboxes', { var => $var, %options });
309   }
310
311   $main::lxdebug->leave_sub(2);
312 }
313
314 sub render_search_options {
315   $main::lxdebug->enter_sub();
316
317   my $self     = shift;
318   my %params   = @_;
319
320   Common::check_params(\%params, qw(variables));
321
322   my $myconfig = \%main::myconfig;
323   my $form     = $main::form;
324
325   $params{hidden_cvar_filters} = $myconfig->{hide_cvar_search_options};
326
327   $params{include_prefix}   = 'l_' unless defined($params{include_prefix});
328   $params{include_value}  ||= '1';
329   $params{filter_prefix}  ||= '';
330
331   my $filter  = $form->parse_html_template('amcvar/search_filter',  \%params);
332   my $include = $form->parse_html_template('amcvar/search_include', \%params);
333
334   $main::lxdebug->leave_sub();
335
336   return ($filter, $include);
337 }
338
339 sub build_filter_query {
340   $main::lxdebug->enter_sub();
341
342   my $self     = shift;
343   my %params   = @_;
344
345   Common::check_params(\%params, qw(module trans_id_field filter));
346
347   my $myconfig = \%main::myconfig;
348   my $form     = $main::form;
349
350   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
351
352   my $configs  = $self->get_configs(%params);
353
354   my (@where, @values);
355
356   foreach my $config (@{ $configs }) {
357     next unless ($config->{searchable});
358
359     my $name = "cvar_$config->{name}";
360
361     my (@sub_values, @sub_where, $not);
362
363     if (($config->{type} eq 'text') || ($config->{type} eq 'textfield')) {
364       next unless ($params{filter}->{$name});
365
366       push @sub_where,  qq|cvar.text_value ILIKE ?|;
367       push @sub_values, like($params{filter}->{$name});
368
369     } elsif ($config->{type} eq 'select') {
370       next unless ($params{filter}->{$name});
371
372       push @sub_where,  qq|cvar.text_value = ?|;
373       push @sub_values, $params{filter}->{$name};
374
375     } elsif (($config->{type} eq 'date') || ($config->{type} eq 'timestamp')) {
376       my $name_from = "${name}_from";
377       my $name_to   = "${name}_to";
378
379       if ($params{filter}->{$name_from}) {
380         push @sub_where,  qq|cvar.timestamp_value >= ?|;
381         push @sub_values, conv_date($params{filter}->{$name_from});
382       }
383
384       if ($params{filter}->{$name_to}) {
385         push @sub_where,  qq|cvar.timestamp_value <= ?|;
386         push @sub_values, conv_date($params{filter}->{$name_to});
387       }
388
389     } elsif ($config->{type} eq 'number') {
390       next if ($params{filter}->{$name} eq '');
391
392       my $f_op = $params{filter}->{"${name}_qtyop"};
393
394       my $op;
395       if ($f_op eq '==') {
396         $op  = '=';
397
398       } elsif ($f_op eq '=/=') {
399         $not = 'NOT';
400         $op  = '<>';
401
402       } elsif ($f_op eq '<') {
403         $not = 'NOT';
404         $op  = '>=';
405
406       } elsif ($f_op eq '<=') {
407         $not = 'NOT';
408         $op  = '>';
409
410       } elsif (($f_op eq '>') || ($f_op eq '>=')) {
411         $op  = $f_op;
412
413       } else {
414         $op  = '=';
415       }
416
417       push @sub_where,  qq|cvar.number_value $op ?|;
418       push @sub_values, $form->parse_amount($myconfig, trim($params{filter}->{$name}));
419
420     } elsif ($config->{type} eq 'bool') {
421       next unless ($params{filter}->{$name});
422
423       $not = 'NOT' if ($params{filter}->{$name} eq 'no');
424       push @sub_where,  qq|COALESCE(cvar.bool_value, false) = TRUE|;
425     } elsif (any { $config->{type} eq $_ } qw(customer vendor)) {
426       next unless $params{filter}->{$name};
427
428       my $table = $config->{type};
429       push @sub_where, qq|cvar.number_value * 1 IN (SELECT id FROM $table WHERE name ILIKE ?)|;
430       push @sub_values, like($params{filter}->{$name});
431     } elsif ($config->{type} eq 'part') {
432       next unless $params{filter}->{$name};
433
434       push @sub_where, qq|cvar.number_value * 1 IN (SELECT id FROM parts WHERE partnumber ILIKE ?)|;
435       push @sub_values, like($params{filter}->{$name});
436     }
437
438     if (@sub_where) {
439       add_token(\@sub_where, \@sub_values, col => 'cvar.sub_module', val => $params{sub_module} || '');
440
441       push @where,
442         qq|$not EXISTS(
443              SELECT cvar.id
444              FROM custom_variables cvar
445              LEFT JOIN custom_variable_configs cvarcfg ON (cvar.config_id = cvarcfg.id)
446              WHERE (cvarcfg.module = ?)
447                AND (cvarcfg.id     = ?)
448                AND (cvar.trans_id  = $params{trans_id_field})
449                AND | . join(' AND ', map { "($_)" } @sub_where) . qq|)|;
450       push @values, $params{module}, conv_i($config->{id}), @sub_values;
451     }
452   }
453
454   my $query = join ' AND ', @where;
455
456   $main::lxdebug->leave_sub();
457
458   return ($query, @values);
459 }
460
461 sub add_custom_variables_to_report {
462   $main::lxdebug->enter_sub();
463
464   my $self      = shift;
465   my %params    = @_;
466
467   Common::check_params(\%params, qw(module trans_id_field column_defs data configs));
468
469   my $myconfig  = \%main::myconfig;
470   my $form      = $main::form;
471   my $locale    = $main::locale;
472
473   my $dbh       = $params{dbh} || $form->get_standard_dbh($myconfig);
474
475   my $configs   = [ grep { $_->{includeable} && $params{column_defs}->{"cvar_$_->{name}"}->{visible} } @{ $params{configs} } ];
476
477   if (!scalar(@{ $params{data} }) || ! scalar(@{ $configs })) {
478     $main::lxdebug->leave_sub();
479     return;
480   }
481
482   # allow sub_module to be a coderef or a fixed value
483   if (ref $params{sub_module} ne 'CODE') {
484     my $sub_module = "$params{sub_module}";
485     $params{sub_module} = sub { $sub_module };
486   }
487
488   my %cfg_map   = map { $_->{id} => $_ } @{ $configs };
489   my @cfg_ids   = keys %cfg_map;
490
491   my $query     =
492     qq|SELECT text_value, timestamp_value, timestamp_value::date AS date_value, number_value, bool_value, config_id
493        FROM custom_variables
494        WHERE (config_id IN (| . join(', ', ('?') x scalar(@cfg_ids)) . qq|))
495          AND (trans_id = ?)
496          AND (sub_module = ?)|;
497   my $sth       = prepare_query($form, $dbh, $query);
498
499   foreach my $row (@{ $params{data} }) {
500     do_statement($form, $sth, $query, @cfg_ids, conv_i($row->{$params{trans_id_field}}), $params{sub_module}->($row));
501
502     while (my $ref = $sth->fetchrow_hashref()) {
503       my $cfg = $cfg_map{$ref->{config_id}};
504
505       $row->{"cvar_$cfg->{name}"} =
506           $cfg->{type} eq 'date'      ? $ref->{date_value}
507         : $cfg->{type} eq 'timestamp' ? $ref->{timestamp_value}
508         : $cfg->{type} eq 'number'    ? $form->format_amount($myconfig, $ref->{number_value} * 1, $cfg->{precision})
509         : $cfg->{type} eq 'customer'  ? (SL::DB::Manager::Customer->find_by(id => 1*$ref->{number_value}) || SL::DB::Customer->new)->name
510         : $cfg->{type} eq 'vendor'    ? (SL::DB::Manager::Vendor->find_by(id => 1*$ref->{number_value})   || SL::DB::Vendor->new)->name
511         : $cfg->{type} eq 'part'      ? (SL::DB::Manager::Part->find_by(id => 1*$ref->{number_value})     || SL::DB::Part->new)->partnumber
512         : $cfg->{type} eq 'bool'      ? ($ref->{bool_value} ? $locale->text('Yes') : $locale->text('No'))
513         :                               $ref->{text_value};
514     }
515   }
516
517   $sth->finish();
518
519   $main::lxdebug->leave_sub();
520 }
521
522 sub get_field_format_list {
523   $main::lxdebug->enter_sub();
524
525   my $self          = shift;
526   my %params        = @_;
527
528   Common::check_params(\%params, qw(module));
529
530   my $myconfig      = \%main::myconfig;
531   my $form          = $main::form;
532
533   my $dbh           = $params{dbh} || $form->get_standard_dbh($myconfig);
534
535   my $configs       = $self->get_configs(%params);
536
537   my $date_fields   = [];
538   my $number_fields = {};
539
540   foreach my $config (@{ $configs }) {
541     my $name = "$params{prefix}cvar_$config->{name}";
542
543     if ($config->{type} eq 'date') {
544       push @{ $date_fields }, $name;
545
546     } elsif ($config->{type} eq 'number') {
547       $number_fields->{$config->{precision}} ||= [];
548       push @{ $number_fields->{$config->{precision}} }, $name;
549     }
550   }
551
552   $main::lxdebug->leave_sub();
553
554   return ($date_fields, $number_fields);
555 }
556
557 sub save_custom_variables_validity {
558   my ($self, %params) = @_;
559   $main::lxdebug->enter_sub();
560
561   my $rc = SL::DB->client->with_transaction(\&_save_custom_variables_validity, $self, %params);
562
563   $::lxdebug->leave_sub;
564   return $rc;
565 }
566
567 sub _save_custom_variables_validity {
568   my $self     = shift;
569   my %params   = @_;
570
571   Common::check_params(\%params, qw(config_id trans_id validity));
572
573   my $myconfig = \%main::myconfig;
574   my $form     = $main::form;
575
576   my $dbh      = $params{dbh} || SL::DB->client->dbh;
577
578   my (@where, @values);
579   add_token(\@where, \@values, col => "config_id", val => $params{config_id}, esc => \&conv_i);
580   add_token(\@where, \@values, col => "trans_id",  val => $params{trans_id},  esc => \&conv_i);
581
582   my $where = scalar @where ? "WHERE " . join ' AND ', @where : '';
583   my $query = qq|DELETE FROM custom_variables_validity $where|;
584
585   do_query($form, $dbh, $query, @values);
586
587   $query  =
588     qq|INSERT INTO custom_variables_validity (config_id, trans_id)
589        VALUES                                (?,         ?       )|;
590   my $sth = prepare_query($form, $dbh, $query);
591
592   unless ($params{validity}) {
593     foreach my $config_id (listify($params{config_id})) {
594       foreach my $trans_id (listify($params{trans_id})) {
595         do_statement($form, $sth, $query, conv_i($config_id), conv_i($trans_id));
596       }
597     }
598   }
599
600   $sth->finish();
601
602   return 1;
603 }
604
605 my %_validity_sub_module_mapping = (
606   orderitems           => { table => 'orderitems',           result_column => 'parts_id', trans_id_column => 'id', },
607   delivery_order_items => { table => 'delivery_order_items', result_column => 'parts_id', trans_id_column => 'id', },
608   invoice              => { table => 'invoice',              result_column => 'parts_id', trans_id_column => 'id', },
609 );
610
611 sub get_custom_variables_validity {
612   my $self     = shift;
613   my %params   = @_;
614
615   Common::check_params(\%params, qw(config_id trans_id));
616
617   my $myconfig = \%main::myconfig;
618   my $form     = $main::form;
619
620   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
621
622   my $query;
623
624   if ($params{sub_module}) {
625     my %mapping = %{ $_validity_sub_module_mapping{ $params{sub_module} } || croak("Invalid sub_module '" . $params{sub_module} . "'") };
626     $query = <<SQL;
627       SELECT cvv.id
628       FROM $mapping{table} mt
629       LEFT JOIN custom_variables_validity cvv ON (cvv.trans_id = mt.$mapping{result_column})
630       WHERE (cvv.config_id                = ?)
631         AND (mt.$mapping{trans_id_column} = ?)
632       LIMIT 1
633 SQL
634   } else {
635     $query = <<SQL;
636       SELECT id
637       FROM custom_variables_validity
638       WHERE (config_id = ?)
639         AND (trans_id  = ?)
640       LIMIT 1
641 SQL
642   }
643
644   my ($invalid) = selectfirst_array_query($form, $dbh, $query, conv_i($params{config_id}), conv_i($params{trans_id}));
645
646   return !$invalid;
647 }
648
649 sub custom_variables_validity_by_trans_id {
650   $main::lxdebug->enter_sub(2);
651
652   my $self     = shift;
653   my %params   = @_;
654
655   return sub { 0 } unless $params{trans_id};
656
657   my $myconfig = \%main::myconfig;
658   my $form     = $main::form;
659
660   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
661
662   my $query    = qq|SELECT DISTINCT config_id FROM custom_variables_validity WHERE trans_id = ?|;
663
664   my %invalids = map { +($_->{config_id} => 1) } selectall_hashref_query($form, $dbh, $query, $params{trans_id});
665
666   $main::lxdebug->leave_sub(2);
667
668   return sub { !$invalids{+shift} };
669 }
670
671 sub parse {
672   my ($self, $value, $config) = @_;
673
674   return $::form->parse_amount(\%::myconfig, $value)          if $config->{type} eq 'number';
675   return DateTime->from_lxoffice($value)                      if $config->{type} eq 'date';
676   return !ref $value ? SL::DB::Manager::Customer->find_by(id => $value * 1) : $value  if $config->{type} eq 'customer';
677   return !ref $value ? SL::DB::Manager::Vendor->find_by(id => $value * 1)   : $value  if $config->{type} eq 'vendor';
678   return !ref $value ? SL::DB::Manager::Part->find_by(id => $value * 1)     : $value  if $config->{type} eq 'part';
679   return $value;
680 }
681
682 sub format_to_template {
683   my ($self, $value, $config) = @_;
684   # stupid template expects everything formated. except objects
685   # do not use outside of print routines for legacy templates
686
687   return $::form->format_amount(\%::myconfig, $value) if $config->{type} eq 'number';
688   return $value->to_lxoffice if $config->{type} eq 'date' && blessed $value && $value->can('to_lxoffice');
689   return $value;
690 }
691
692 sub get_non_editable_ic_cvars {
693   $main::lxdebug->enter_sub(2);
694   my $self     = shift;
695   my %params   = @_;
696
697   Common::check_params(\%params, qw(form dbh row sub_module may_converted_from));
698   my $form               = $params{form};
699   my $dbh                = $params{dbh};
700   my $row                = $params{row};
701   my $sub_module         = $params{sub_module};
702   my $may_converted_from = $params{may_converted_from};
703
704   my $cvars;
705   if (! $form->{"${sub_module}_id_${row}"}) {
706     my $conv_from = 0;
707     foreach (@{ $may_converted_from }) {
708       if ($form->{"converted_from_${_}_id_$row"}) {
709         $cvars = CVar->get_custom_variables(dbh        => $dbh,
710                                             module     => 'IC',
711                                             sub_module => $_,
712                                             trans_id   => $form->{"converted_from_${_}_id_$row"},
713                                            );
714         $conv_from = 1;
715         last;
716       }
717     }
718     # get values for CVars from master data for new items
719     if (!$conv_from) {
720       $cvars = CVar->get_custom_variables(dbh      => $dbh,
721                                           module   => 'IC',
722                                           trans_id => $form->{"id_$row"},
723                                          );
724     }
725   } else {
726     # get values for CVars from custom_variables for existing items
727     $cvars = CVar->get_custom_variables(dbh        => $dbh,
728                                         module     => 'IC',
729                                         sub_module => $sub_module,
730                                         trans_id   => $form->{"${sub_module}_id_${row}"},
731                                        );
732   }
733   # map only non-editable CVars to form
734   foreach (@{ $cvars }) {
735     next if $_->{flag_editable};
736     $form->{"ic_cvar_$_->{name}_$row"} = $_->{value}
737   }
738
739   $main::lxdebug->leave_sub(2);
740 }
741
742 1;
743
744 __END__
745
746 =head1 NAME
747
748 SL::CVar.pm - Custom Variables module
749
750 =head1 SYNOPSIS
751
752   # dealing with configs
753
754   my $all_configs = CVar->get_configs()
755
756   # dealing with custom vars
757
758   CVar->get_custom_variables(module => 'ic')
759
760 =head2 VALIDITY
761
762 Suppose the following scenario:
763
764 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.
765
766 Validity is assumed. If you modify validity, you actually save B<invalidity>.
767 Invalidity is saved as a function of config_id, and the trans_id
768
769 In the naive way, disable an attribute for a specific id (simple)
770
771 =cut