Konteneinstellungen wieder änderbar bei bebuchten Konten
[kivitendo-erp.git] / bin / mozilla / am.pl
1 #=====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (c) 1998-2002
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 #
16 # This program is free software; you can redistribute it and/or modify
17 # it under the terms of the GNU General Public License as published by
18 # the Free Software Foundation; either version 2 of the License, or
19 # (at your option) any later version.
20 #
21 # This program is distributed in the hope that it will be useful,
22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 # GNU General Public License for more details.
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
28 # MA 02110-1335, USA.
29 #======================================================================
30 #
31 # administration
32 #
33 #======================================================================
34
35 use utf8;
36
37 use List::MoreUtils qw(any);
38
39 use SL::Auth;
40 use SL::Auth::PasswordPolicy;
41 use SL::AM;
42 use SL::CA;
43 use SL::Form;
44 use SL::Helper::Flash;
45 use SL::User;
46 use SL::USTVA;
47 use SL::Iconv;
48 use SL::Locale::String qw(t8);
49 use SL::TODO;
50 use SL::DB::Printer;
51 use SL::DB::Tax;
52 use SL::DB::Language;
53 use SL::DB::Default;
54 use SL::DBUtils qw(selectall_array_query conv_dateq);
55 use CGI;
56
57 require "bin/mozilla/common.pl";
58
59 use strict;
60
61 1;
62
63 # end of main
64
65 sub add      { call_sub("add_$main::form->{type}"); }
66 sub delete   { call_sub("delete_$main::form->{type}"); }
67 sub save     { call_sub("save_$main::form->{type}"); }
68 sub edit     { call_sub("edit_$main::form->{type}"); }
69 sub continue { call_sub($main::form->{"nextsub"}); }
70 sub save_as_new { call_sub("save_as_new_$main::form->{type}"); }
71
72 sub add_account {
73   $main::lxdebug->enter_sub();
74
75   my $form     = $main::form;
76   my %myconfig = %main::myconfig;
77
78   $main::auth->assert('config');
79
80   $form->{title}     = "Add";
81   $form->{charttype} = "A";
82   AM->get_account(\%myconfig, \%$form);
83
84   $form->{callback} = "am.pl?action=list_account" unless $form->{callback};
85
86   &account_header;
87   &form_footer;
88
89   $main::lxdebug->leave_sub();
90 }
91
92 sub edit_account {
93   $main::lxdebug->enter_sub();
94
95   my $form     = $main::form;
96   my %myconfig = %main::myconfig;
97   my $defaults = SL::DB::Default->get;
98
99   $main::auth->assert('config');
100
101   $form->{title} = "Edit";
102   $form->{feature_balance} = $defaults->feature_balance;
103   $form->{feature_datev} = $defaults->feature_datev;
104   $form->{feature_erfolgsrechnung} = $defaults->feature_erfolgsrechnung;
105   $form->{feature_eurechnung} = $defaults->feature_eurechnung;
106   $form->{feature_ustva} = $defaults->feature_ustva;
107
108   AM->get_account(\%myconfig, \%$form);
109
110   foreach my $item (split(/:/, $form->{link})) {
111     $form->{$item} = "checked";
112   }
113
114   &account_header;
115
116   $main::lxdebug->leave_sub();
117 }
118
119 sub account_header {
120   $main::lxdebug->enter_sub();
121
122   my $form     = $main::form;
123   my %myconfig = %main::myconfig;
124   my $locale   = $main::locale;
125
126   $main::auth->assert('config');
127
128   if ( $form->{action} eq 'edit_account') {
129     $form->{account_exists} = '1';
130   }
131
132   $form->{title} = $locale->text("$form->{title} Account");
133
134   $form->{"$form->{charttype}_checked"} = "checked";
135   $form->{"$form->{category}_checked"}  = "checked";
136
137   $form->{select_tax} = "";
138
139   my @tax_report_pos = USTVA->report_variables({
140       myconfig   => \%myconfig,
141       form       => $form,
142       type       => '',
143       attribute  => 'position',
144       calc       => '',
145   });
146
147   if (@{ $form->{TAXKEY} }) {
148     foreach my $item (@{ $form->{TAXKEY} }) {
149       $item->{rate} = $item->{rate} * 100 . '%';
150     }
151
152     # Fill in empty row for new Taxkey
153     my $newtaxkey_ref = {
154       id             => '',
155       chart_id       => '',
156       accno          => '',
157       tax_id         => '',
158       taxdescription => '',
159       rate           => '',
160       taxkey_id      => '',
161       pos_ustva      => '',
162       startdate      => $form->{account_exists} ? '' : DateTime->new(year => 1970, month => 1, day => 1)->to_lxoffice,
163     };
164
165     push @{ $form->{ACCOUNT_TAXKEYS} }, $newtaxkey_ref;
166
167     my $i = 0;
168     foreach my $taxkey_used (@{ $form->{ACCOUNT_TAXKEYS} } ) {
169
170       # Fill in a runningnumber
171       $form->{ACCOUNT_TAXKEYS}[$i]{runningnumber} = $i;
172
173       # Fill in the Taxkeys as select options
174       foreach my $item (@{ $form->{TAXKEY} }) {
175         if ($item->{id} == $taxkey_used->{tax_id}) {
176           $form->{ACCOUNT_TAXKEYS}[$i]{selecttaxkey} .=
177             qq|<option value="$item->{id}" selected="selected">|
178             . sprintf("%.2d", $item->{taxkey})
179             . qq|. $item->{taxdescription} ($item->{rate}) |
180             . $locale->text('Tax-o-matic Account')
181             . qq|: $item->{chart_accno}\n|;
182         }
183         else {
184           $form->{ACCOUNT_TAXKEYS}[$i]{selecttaxkey} .=
185             qq|<option value="$item->{id}">|
186             . sprintf("%.2d", $item->{taxkey})
187             . qq|. $item->{taxdescription} ($item->{rate}) |
188             . $locale->text('Tax-o-matic Account')
189             . qq|: $item->{chart_accno}\n|;
190         }
191
192       }
193
194       # Fill in the USTVA Numbers as select options
195       foreach my $item ( '', sort({ $a cmp $b } @tax_report_pos) ) {
196         if ($item eq ''){
197           $form->{ACCOUNT_TAXKEYS}[$i]{select_tax} .= qq|<option value="" selected="selected">-\n|;
198         }
199         elsif ( $item eq $taxkey_used->{pos_ustva} ) {
200           $form->{ACCOUNT_TAXKEYS}[$i]{select_tax} .= qq|<option value="$item" selected="selected">$item\n|;
201         }
202         else {
203           $form->{ACCOUNT_TAXKEYS}[$i]{select_tax} .= qq|<option value="$item">$item\n|;
204         }
205
206       }
207
208       $i++;
209     }
210   }
211
212   # Newaccount Folgekonto
213   if (@{ $form->{NEWACCOUNT} || [] }) {
214     if (!$form->{new_chart_valid}) {
215       $form->{selectnewaccount} = qq|<option value=""> |. $locale->text('None') .q|</option>|;
216     }
217     foreach my $item (@{ $form->{NEWACCOUNT} }) {
218       if ($item->{id} == $form->{new_chart_id}) {
219         $form->{selectnewaccount} .=
220           qq|<option value="$item->{id}" selected>$item->{accno}--$item->{description}</option>|;
221       } elsif (!$form->{new_chart_valid}) {
222         $form->{selectnewaccount} .=
223           qq|<option value="$item->{id}">$item->{accno}--$item->{description}</option>|;
224       }
225
226     }
227   }
228
229   my $select_eur = q|<option value=""> |. $locale->text('None') .q|</option>\n|;
230   my %eur = %{ AM->get_eur_categories(\%myconfig, $form) };
231   foreach my $item (sort({ $a <=> $b } keys(%eur))) {
232     my $text = H($::locale->{iconv_utf8}->convert($eur{$item}));
233     if ($item == $form->{pos_eur}) {
234       $select_eur .= qq|<option value=$item selected>|. sprintf("%.2d", $item) .qq|. $text</option>\n|;
235     } else {
236       $select_eur .= qq|<option value=$item>|. sprintf("%.2d", $item) .qq|. $text</option>\n|;
237     }
238
239   }
240
241   my $select_er = q|<option value=""> |. $locale->text('None') .q|</option>\n|;
242   my %er = (
243        1  => "Ertrag",
244        6  => "Aufwand");
245   foreach my $item (sort({ $a <=> $b } keys(%er))) {
246     my $text = H($::locale->{iconv_utf8}->convert($er{$item}));
247     if ($item == $form->{pos_er}) {
248       $select_er .= qq|<option value=$item selected>|. sprintf("%.2d", $item) .qq|. $text</option>\n|;
249     } else {
250       $select_er .= qq|<option value=$item>|. sprintf("%.2d", $item) .qq|. $text</option>\n|;
251     }
252
253   }
254
255   my $select_bwa = q|<option value=""> |. $locale->text('None') .q|</option>\n|;
256
257   my %bwapos = %{ AM->get_bwa_categories(\%myconfig, $form) };
258   foreach my $item (sort({ $a <=> $b } keys %bwapos)) {
259     my $text = H($::locale->{iconv_utf8}->convert($bwapos{$item}));
260     if ($item == $form->{pos_bwa}) {
261       $select_bwa .= qq|<option value="$item" selected>|. sprintf("%.2d", $item) .qq|. $text\n|;
262     } else {
263       $select_bwa .= qq|<option value="$item">|. sprintf("%.2d", $item) .qq|. $text\n|;
264     }
265
266   }
267
268 # Wieder hinzugefügt zu evaluationszwecken (us) 09.03.2007
269   my $select_bilanz = q|<option value=""> |. $locale->text('None') .q|</option>\n|;
270   foreach my $item ((1, 2, 3, 4)) {
271     if ($item == $form->{pos_bilanz}) {
272       $select_bilanz .= qq|<option value=$item selected>|. sprintf("%.2d", $item) .qq|.\n|;
273     } else {
274       $select_bilanz .= qq|<option value=$item>|. sprintf("%.2d", $item) .qq|.\n|;
275     }
276
277   }
278
279   # this is for our parser only! Do not remove.
280   # type=submit $locale->text('Add Account')
281   # type=submit $locale->text('Edit Account')
282
283   $form->{type} = "account";
284
285   # preselections category
286
287   my $select_category = q|<option value=""> |. $locale->text('None') .q|</option>\n|;
288
289   my %category = (
290       'A'  => $locale->text('Asset'),
291       'L'  => $locale->text('Liability'),
292       'Q'  => $locale->text('Equity'),
293       'I'  => $locale->text('Revenue'),
294       'E'  => $locale->text('Expense'),
295       'C'  => $locale->text('Costs'),
296   );
297   foreach my $item ( sort({ $a <=> $b } keys %category) ) {
298     if ($item eq $form->{category}) {
299       $select_category .= qq|<option value="$item" selected="selected">$category{$item} (|. sprintf("%s", $item) .qq|)\n|;
300     } else {
301       $select_category .= qq|<option value="$item">$category{$item} (|. sprintf("%s", $item) .qq|)\n|;
302     }
303
304   }
305
306   # preselection chart type
307   my @all_charttypes = ({'name' => $locale->text('Account'), 'value' => 'A'},
308                         {'name' => $locale->text('Heading'), 'value' => 'H'},
309     );
310   my $selected_charttype = $form->{charttype};
311
312
313   # account where AR_tax or AP_tax is set are not orphaned if they are used as
314   # tax-o-matic account
315   if ( $form->{id} && $form->{orphaned} && ($form->{link} =~ m/(AP_tax|AR_tax)/) ) {
316     if (SL::DB::Manager::Tax->find_by(chart_id => $form->{id})) {
317       $form->{orphaned} = 0;
318     }
319   }
320
321   my $ChartTypeIsAccount = ($form->{charttype} eq "A") ? "1":"";
322   my $AccountIsPosted = ($form->{orphaned} ) ? "":"1";
323
324   setup_am_edit_account_action_bar();
325
326   $form->header();
327
328   my $parameters_ref = {
329     ChartTypeIsAccount         => $ChartTypeIsAccount,
330     AccountIsPosted            => $AccountIsPosted,
331     select_category            => $select_category,
332     all_charttypes             => \@all_charttypes,
333     selected_charttype         => $selected_charttype,
334     select_bwa                 => $select_bwa,
335     select_bilanz              => $select_bilanz,
336     select_eur                 => $select_eur,
337     select_er                  => $select_er,
338   };
339
340   # Ausgabe des Templates
341   print($form->parse_html_template('am/edit_accounts', $parameters_ref));
342
343
344   $main::lxdebug->leave_sub();
345 }
346
347 sub form_footer {
348   $::lxdebug->enter_sub;
349   $::auth->assert('config');
350
351   print $::form->parse_html_template('am/form_footer', {
352     show_save        => !$::form->{id}
353                      || ($::form->{id} && $::form->{orphaned})
354                      || ($::form->{type} eq "account" && !$::form->{new_chart_valid}),
355     show_delete      => $::form->{id} && $::form->{orphaned},
356     show_save_as_new => $::form->{id} && $::form->{type} eq "account",
357   });
358
359   $::lxdebug->leave_sub;
360 }
361
362 sub save_account {
363   $main::lxdebug->enter_sub();
364
365   my $form     = $main::form;
366   my %myconfig = %main::myconfig;
367   my $locale   = $main::locale;
368
369   $main::auth->assert('config');
370
371   $form->isblank("accno",       $locale->text('Account Number missing!'));
372   $form->isblank("description", $locale->text('Account Description missing!'));
373
374   if ($form->{charttype} eq 'A'){
375     $form->isblank("category",  $locale->text('Account Type missing!'));
376
377     my $found_valid_taxkey = 0;
378     foreach my $i (0 .. 10) { # 10 is maximum count of taxkeys in form
379       if ($form->{"taxkey_startdate_$i"} and !$form->{"taxkey_del_$i"}) {
380         $found_valid_taxkey = 1;
381         last;
382       }
383     }
384     if ($found_valid_taxkey == 0) {
385       $form->error($locale->text('A valid taxkey is missing!'));
386     }
387   }
388
389   $form->redirect($locale->text('Account saved!'))
390     if (AM->save_account(\%myconfig, \%$form));
391   $form->error($locale->text('Cannot save account!'));
392
393   $main::lxdebug->leave_sub();
394 }
395
396 sub save_as_new_account {
397   $main::lxdebug->enter_sub();
398
399   my $form     = $main::form;
400   my %myconfig = %main::myconfig;
401   my $locale   = $main::locale;
402
403   $main::auth->assert('config');
404
405   $form->isblank("accno",       $locale->text('Account Number missing!'));
406   $form->isblank("description", $locale->text('Account Description missing!'));
407
408   if ($form->{charttype} eq 'A'){
409     $form->isblank("category",  $locale->text('Account Type missing!'));
410   }
411
412   for my $taxkey (0 .. 9) {
413     if ($form->{"taxkey_id_$taxkey"}) {
414       $form->{"taxkey_id_$taxkey"} = "NEW";
415     }
416   }
417
418   $form->{id} = 0;
419   $form->redirect($locale->text('Account saved!'))
420     if (AM->save_account(\%myconfig, \%$form));
421   $form->error($locale->text('Cannot save account!'));
422
423   $main::lxdebug->leave_sub();
424 }
425
426 sub list_account {
427   $main::lxdebug->enter_sub();
428
429   my $form     = $main::form;
430   my %myconfig = %main::myconfig;
431   my $locale   = $main::locale;
432
433   $main::auth->assert('config');
434
435   $form->{callback}     = build_std_url('action=list_account');
436   my $link_edit_account = build_std_url('action=edit_account', 'callback');
437
438   CA->all_accounts(\%myconfig, \%$form);
439
440   foreach my $ca (@{ $form->{CA} }) {
441
442     $ca->{debit}  = "";
443     $ca->{credit} = "";
444
445     if ($ca->{amount} > 0) {
446       $ca->{credit} = $form->format_amount(\%myconfig, $ca->{amount}, 2);
447     }
448     if ($ca->{amount} < 0) {
449       $ca->{debit} = $form->format_amount(\%myconfig, -1 * $ca->{amount}, 2);
450     }
451     $ca->{heading}   = ( $ca->{charttype} eq 'H' ) ? 1:'';
452     $ca->{link_edit_account} = $link_edit_account . '&id=' . E($ca->{id});
453   }
454
455   $::request->{layout}->use_stylesheet("list_accounts.css");
456   $form->{title}       = $locale->text('Chart of Accounts');
457
458   $form->header;
459
460
461   my $parameters_ref = {
462   #   hidden_variables                => $_hidden_variables_ref,
463   };
464
465   # Ausgabe des Templates
466   print($form->parse_html_template('am/list_accounts', $parameters_ref));
467
468   $main::lxdebug->leave_sub();
469
470 }
471
472
473 sub list_account_details {
474 # Ajax Funktion aus list_account_details
475   $main::lxdebug->enter_sub();
476
477   my $form     = $main::form;
478   my %myconfig = %main::myconfig;
479   my $locale   = $main::locale;
480
481   $main::auth->assert('config');
482
483   my $chart_id = $form->{args};
484
485   CA->all_accounts(\%myconfig, \%$form, $chart_id);
486
487   foreach my $ca (@{ $form->{CA} }) {
488
489     $ca->{debit}  = "&nbsp;";
490     $ca->{credit} = "&nbsp;";
491
492     if ($ca->{amount} > 0) {
493       $ca->{credit} =
494         $form->format_amount(\%myconfig, $ca->{amount}, 2, "&nbsp;");
495     }
496     if ($ca->{amount} < 0) {
497       $ca->{debit} =
498         $form->format_amount(\%myconfig, -1 * $ca->{amount}, 2, "&nbsp;");
499     }
500
501     my @links = split( q{:}, $ca->{link});
502
503     $ca->{link} = q{};
504
505     foreach my $link (@links){
506       $link =    ( $link eq 'AR')             ? $locale->text('Account Link AR')
507                : ( $link eq 'AP')             ? $locale->text('Account Link AP')
508                : ( $link eq 'IC')             ? $locale->text('Account Link IC')
509                : ( $link eq 'AR_amount' )     ? $locale->text('Account Link AR_amount')
510                : ( $link eq 'AR_paid' )       ? $locale->text('Account Link AR_paid')
511                : ( $link eq 'AR_tax' )        ? $locale->text('Account Link AR_tax')
512                : ( $link eq 'AP_amount' )     ? $locale->text('Account Link AP_amount')
513                : ( $link eq 'AP_paid' )       ? $locale->text('Account Link AP_paid')
514                : ( $link eq 'AP_tax' )        ? $locale->text('Account Link AP_tax')
515                : ( $link eq 'IC_sale' )       ? $locale->text('Account Link IC_sale')
516                : ( $link eq 'IC_cogs' )       ? $locale->text('Account Link IC_cogs')
517                : ( $link eq 'IC_taxpart' )    ? $locale->text('Account Link IC_taxpart')
518                : ( $link eq 'IC_income' )     ? $locale->text('Account Link IC_income')
519                : ( $link eq 'IC_expense' )    ? $locale->text('Account Link IC_expense')
520                : ( $link eq 'IC_taxservice' ) ? $locale->text('Account Link IC_taxservice')
521                : $locale->text('Unknown Link') . ': ' . $link;
522       $ca->{link} .= ($link ne '') ?  "[$link] ":'';
523     }
524
525     $ca->{category} = ($ca->{category} eq 'A') ? $locale->text('Account Category A')
526                     : ($ca->{category} eq 'E') ? $locale->text('Account Category E')
527                     : ($ca->{category} eq 'L') ? $locale->text('Account Category L')
528                     : ($ca->{category} eq 'I') ? $locale->text('Account Category I')
529                     : ($ca->{category} eq 'Q') ? $locale->text('Account Category Q')
530                     : ($ca->{category} eq 'C') ? $locale->text('Account Category C')
531                     : ($ca->{category} eq 'G') ? $locale->text('Account Category G')
532                     : $locale->text('Unknown Category') . ': ' . $ca->{category};
533   }
534
535   $form->{title} = $locale->text('Chart of Accounts');
536
537   print $form->ajax_response_header, $form->parse_html_template('am/list_account_details');
538
539   $main::lxdebug->leave_sub();
540
541 }
542
543 sub delete_account {
544   $main::lxdebug->enter_sub();
545
546   my $form     = $main::form;
547   my %myconfig = %main::myconfig;
548   my $locale   = $main::locale;
549
550   $main::auth->assert('config');
551
552   $form->{title} = $locale->text('Delete Account');
553
554   foreach my $id (
555     qw(inventory_accno_id income_accno_id expense_accno_id fxgain_accno_id fxloss_accno_id rndgain_accno_id rndloss_accno_id)
556     ) {
557     if ($form->{id} == $form->{$id}) {
558       $form->error($locale->text('Cannot delete default account!'));
559     }
560   }
561
562   $form->redirect($locale->text('Account deleted!'))
563     if (AM->delete_account(\%myconfig, \%$form));
564   $form->error($locale->text('Cannot delete account!'));
565
566   $main::lxdebug->leave_sub();
567 }
568
569 sub _build_cfg_options {
570   my $form     = $main::form;
571   my %myconfig = %main::myconfig;
572
573   my $idx   = shift;
574   my $array = uc($idx) . 'S';
575
576   $form->{$array} = [];
577   foreach my $item (@_) {
578     push @{ $form->{$array} }, {
579       'name'     => $item,
580       'value'    => $item,
581       'selected' => $item eq $myconfig{$idx},
582     };
583   }
584 }
585
586 sub config {
587   $main::lxdebug->enter_sub();
588
589   my $form     = $main::form;
590   my %myconfig = %main::myconfig;
591   my $locale   = $main::locale;
592
593   _build_cfg_options('dateformat', qw(mm/dd/yy dd/mm/yy dd.mm.yy yyyy-mm-dd));
594   _build_cfg_options('timeformat', qw(hh:mm hh:mm:ss));
595   _build_cfg_options('numberformat', ('1,000.00', '1000.00', '1.000,00', '1000,00', "1'000.00"));
596
597   my @formats = ();
598   if ($::lx_office_conf{print_templates}->{opendocument}
599       && $::lx_office_conf{applications}->{openofficeorg_writer} && (-x $::lx_office_conf{applications}->{openofficeorg_writer})
600       && $::lx_office_conf{applications}->{xvfb}                 && (-x $::lx_office_conf{applications}->{xvfb})) {
601     push(@formats, { "name" => $locale->text("PDF (OpenDocument/OASIS)"),
602                      "value" => "opendocument_pdf" });
603   }
604   if ($::lx_office_conf{print_templates}->{latex}) {
605     push(@formats, { "name" => $locale->text("PDF"), "value" => "pdf" });
606   }
607   push(@formats, { "name" => "HTML", "value" => "html" });
608   if ($::lx_office_conf{print_templates}->{latex}) {
609     push(@formats, { "name" => $locale->text("Postscript"),
610                      "value" => "postscript" });
611   }
612   if ($::lx_office_conf{print_templates}->{opendocument}) {
613     push(@formats, { "name" => $locale->text("OpenDocument/OASIS"),
614                      "value" => "opendocument" });
615   }
616
617   if (!$myconfig{"template_format"}) {
618     $myconfig{"template_format"} = "pdf";
619   }
620   $form->{TEMPLATE_FORMATS} = [];
621   foreach my $item (@formats) {
622     push @{ $form->{TEMPLATE_FORMATS} }, {
623       'name'     => $item->{name},
624       'value'    => $item->{value},
625       'selected' => $item->{value} eq $myconfig{template_format},
626     };
627   }
628
629   if (!$myconfig{"default_media"}) {
630     $myconfig{"default_media"} = "screen";
631   }
632
633   my %selected = ($myconfig{"default_media"} => "selected");
634   $form->{MEDIA} = [
635     { 'name' => $locale->text('Screen'),  'value' => 'screen',  'selected' => $selected{screen}, },
636     { 'name' => $locale->text('Printer'), 'value' => 'printer', 'selected' => $selected{printer}, },
637     { 'name' => $locale->text('Queue'),   'value' => 'queue',   'selected' => $selected{queue}, },
638     ];
639
640   $form->{PRINTERS} = SL::DB::Manager::Printer->get_all_sorted;
641
642   my %countrycodes = User->country_codes;
643
644   $form->{COUNTRYCODES} = [];
645   foreach my $countrycode (sort { $countrycodes{$a} cmp $countrycodes{$b} } keys %countrycodes) {
646     push @{ $form->{COUNTRYCODES} }, {
647       'name'     => $countrycodes{$countrycode},
648       'value'    => $countrycode,
649       'selected' => $countrycode eq $myconfig{countrycode},
650     };
651   }
652
653   $form->{STYLESHEETS} = [];
654   foreach my $item (qw(lx-office-erp.css kivitendo.css)) {
655     push @{ $form->{STYLESHEETS} }, {
656       'name'     => $item,
657       'value'    => $item,
658       'selected' => $item eq $myconfig{stylesheet},
659     };
660   }
661
662   $myconfig{show_form_details} = 1 unless (defined($myconfig{show_form_details}));
663   $form->{CAN_CHANGE_PASSWORD} = $main::auth->can_change_password();
664   $form->{todo_cfg}            = { TODO->get_user_config('login' => $::myconfig{login}) };
665
666   $form->{title}               = $locale->text('Edit Preferences for #1', $::myconfig{login});
667
668   setup_am_config_action_bar();
669
670   $form->header();
671
672   $form->{full_signature} = $form->create_email_signature();
673
674   print $form->parse_html_template('am/config');
675
676   $main::lxdebug->leave_sub();
677 }
678
679 sub save_preferences {
680   $main::lxdebug->enter_sub();
681
682   my $form     = $main::form;
683   my %myconfig = %main::myconfig;
684   my $locale   = $main::locale;
685
686   $form->{stylesheet} = $form->{usestylesheet};
687
688   TODO->save_user_config('login' => $::myconfig{login}, %{ $form->{todo_cfg} || { } });
689
690   if (AM->save_preferences($form)) {
691     if ($::auth->can_change_password()
692         && defined $form->{new_password}
693         && ($form->{new_password} ne '********')) {
694       my $verifier = SL::Auth::PasswordPolicy->new;
695       my $result   = $verifier->verify($form->{new_password});
696
697       if ($result != SL::Auth::PasswordPolicy->OK()) {
698         $form->error($::locale->text('The settings were saved, but the password was not changed.') . ' ' . join(' ', $verifier->errors($result)));
699       }
700
701       $::auth->change_password($::myconfig{login}, $form->{new_password});
702     }
703
704     $form->redirect($locale->text('Preferences saved!'));
705   }
706
707   $form->error($locale->text('Cannot save preferences!'));
708
709   $main::lxdebug->leave_sub();
710 }
711
712 sub audit_control {
713   $::lxdebug->enter_sub;
714   $::auth->assert('config');
715
716   $::form->{title} = $::locale->text('Audit Control');
717
718   AM->closedto(\%::myconfig, $::form);
719
720   setup_am_audit_control_action_bar();
721
722   $::form->header;
723   print $::form->parse_html_template('am/audit_control');
724
725   $::lxdebug->leave_sub;
726 }
727
728 sub doclose {
729   $main::lxdebug->enter_sub();
730
731   my $form     = $main::form;
732   my %myconfig = %main::myconfig;
733   my $locale   = $main::locale;
734
735   $main::auth->assert('config');
736
737   AM->closebooks(\%myconfig, \%$form);
738
739   if ($form->{closedto}) {
740     $form->redirect(
741                     $locale->text('Books closed up to') . " "
742                       . $locale->date(\%myconfig, $form->{closedto}, 1));
743   } else {
744     $form->redirect($locale->text('Books are open'));
745   }
746
747   $main::lxdebug->leave_sub();
748 }
749
750 sub add_unit {
751   $::auth->assert('config');
752
753   # my $units = AM->retrieve_units(\%::myconfig, $::form, "resolved_");
754   # # AM->units_in_use(\%::myconfig, $::form, $units);
755
756   # $units->{$_}->{BASE_UNIT_DDBOX} = AM->unit_select_data($units, $units->{$_}->{base_unit}, 1) for keys %{$units};
757
758   my @languages = @{ SL::DB::Manager::Language->get_all_sorted };
759
760   my $units = AM->retrieve_units(\%::myconfig, $::form);
761   my $ddbox = AM->unit_select_data($units, undef, 1);
762
763   setup_am_add_unit_action_bar();
764
765   $::form->{title} = $::locale->text("Add unit");
766   $::form->header();
767   print($::form->parse_html_template("am/add_unit", {
768     NEW_BASE_UNIT_DDBOX => $ddbox,
769     LANGUAGES           => \@languages,
770   }));
771 }
772
773 sub edit_units {
774   $main::lxdebug->enter_sub();
775
776   my $form     = $main::form;
777   my %myconfig = %main::myconfig;
778   my $locale   = $main::locale;
779
780   $main::auth->assert('config');
781
782   my $units = AM->retrieve_units(\%myconfig, $form, "resolved_");
783   AM->units_in_use(\%myconfig, $form, $units);
784   map({ $units->{$_}->{"BASE_UNIT_DDBOX"} = AM->unit_select_data($units, $units->{$_}->{"base_unit"}, 1); } keys(%{$units}));
785
786   my @languages = @{ SL::DB::Manager::Language->get_all_sorted };
787
788   my @unit_list = sort({ $a->{"sortkey"} <=> $b->{"sortkey"} } values(%{$units}));
789
790   my $i = 1;
791   foreach (@unit_list) {
792     $_->{"factor"} = $form->format_amount(\%myconfig, $_->{"factor"} * 1) if ($_->{"factor"});
793     $_->{"UNITLANGUAGES"} = [];
794     foreach my $lang (@languages) {
795       push(@{ $_->{"UNITLANGUAGES"} },
796            { "idx"              => $i,
797              "unit"             => $_->{"name"},
798              "language_id"      => $lang->id,
799              "localized"        => $_->{"LANGUAGES"}->{$lang->template_code}->{"localized"},
800              "localized_plural" => $_->{"LANGUAGES"}->{$lang->template_code}->{"localized_plural"},
801            });
802     }
803     $i++;
804   }
805
806   $units = AM->retrieve_units(\%myconfig, $form);
807   my $ddbox = AM->unit_select_data($units, undef, 1);
808
809   setup_am_edit_units_action_bar();
810
811   $form->{"title"} = $locale->text("Edit units");
812   $form->header();
813   print($form->parse_html_template("am/edit_units",
814                                    { "UNITS"               => \@unit_list,
815                                      "NEW_BASE_UNIT_DDBOX" => $ddbox,
816                                      "LANGUAGES"           => \@languages,
817                                    }));
818
819   $main::lxdebug->leave_sub();
820 }
821
822 sub create_unit {
823   $main::lxdebug->enter_sub();
824
825   my $form     = $main::form;
826   my %myconfig = %main::myconfig;
827   my $locale   = $main::locale;
828
829   $main::auth->assert('config');
830
831   $form->isblank("new_name", $locale->text("The name is missing."));
832   my $units = AM->retrieve_units(\%myconfig, $form);
833   my $all_units = AM->retrieve_units(\%myconfig, $form);
834   $form->show_generic_error($locale->text("A unit with this name does already exist.")) if ($all_units->{$form->{"new_name"}});
835
836   my ($base_unit, $factor);
837   if ($form->{"new_base_unit"}) {
838     $form->show_generic_error($locale->text("The base unit does not exist.")) unless (defined($units->{$form->{"new_base_unit"}}));
839
840     $form->isblank("new_factor", $locale->text("The factor is missing."));
841     $factor = $form->parse_amount(\%myconfig, $form->{"new_factor"});
842     $form->show_generic_error($locale->text("The factor is missing.")) unless ($factor);
843     $base_unit = $form->{"new_base_unit"};
844   }
845
846   my @languages;
847   foreach my $lang (@{ SL::DB::Manager::Language->get_all_sorted }) {
848     next unless ($form->{"new_localized_$lang->{id}"} || $form->{"new_localized_plural_$lang->{id}"});
849     push(@languages, { "id"               => $lang->id,
850                        "localized"        => $form->{"new_localized_" . $lang->id},
851                        "localized_plural" => $form->{"new_localized_plural_" . $lang->id},
852          });
853   }
854
855   AM->add_unit(\%myconfig, $form, $form->{"new_name"}, $base_unit, $factor, \@languages);
856
857   flash_later('info', $locale->text("The unit has been added."));
858
859   print $form->redirect_header('am.pl?action=edit_units');
860
861   $main::lxdebug->leave_sub();
862 }
863
864 sub set_unit_languages {
865   $main::lxdebug->enter_sub();
866
867   my $form     = $main::form;
868
869   $main::auth->assert('config');
870
871   my ($unit, $languages, $idx) = @_;
872
873   $unit->{"LANGUAGES"} = [];
874
875   foreach my $lang (@{$languages}) {
876     push(@{ $unit->{"LANGUAGES"} },
877          { "id"               => $lang->id,
878            "localized"        => $form->{"localized_${idx}_" . $lang->id},
879            "localized_plural" => $form->{"localized_plural_${idx}_" . $lang->id},
880          });
881   }
882
883   $main::lxdebug->leave_sub();
884 }
885
886 sub save_unit {
887   $main::lxdebug->enter_sub();
888
889   my $form     = $main::form;
890   my %myconfig = %main::myconfig;
891   my $locale   = $main::locale;
892
893   $main::auth->assert('config');
894
895   my $old_units = AM->retrieve_units(\%myconfig, $form, "resolved_");
896   AM->units_in_use(\%myconfig, $form, $old_units);
897
898   my @languages = @{ SL::DB::Manager::Language->get_all_sorted };
899
900   my $new_units = {};
901   my @delete_units = ();
902   foreach my $i (1..($form->{"rowcount"} * 1)) {
903     my $old_unit = $old_units->{$form->{"old_name_$i"}};
904     if (!$old_unit) {
905       $form->show_generic_error(sprintf($locale->text("The unit in row %d has been deleted in the meantime."), $i));
906     }
907
908     if ($form->{"unchangeable_$i"}) {
909       $new_units->{$form->{"old_name_$i"}} = $old_units->{$form->{"old_name_$i"}};
910       $new_units->{$form->{"old_name_$i"}}->{"unchanged_unit"} = 1;
911       set_unit_languages($new_units->{$form->{"old_name_$i"}}, \@languages, $i);
912       next;
913     }
914
915     if ($old_unit->{"in_use"}) {
916       $form->show_generic_error(sprintf($locale->text("The unit in row %d has been used in the meantime and cannot be changed anymore."), $i));
917     }
918
919     if ($form->{"delete_$i"}) {
920       push(@delete_units, $old_unit->{"name"});
921       next;
922     }
923
924     $form->isblank("name_$i", sprintf($locale->text("The name is missing in row %d."), $i));
925
926     $form->show_generic_error(sprintf($locale->text("The name in row %d has already been used before."), $i)) if ($new_units->{$form->{"name_$i"}});
927     my %h = map({ $_ => $form->{"${_}_$i"} } qw(name base_unit factor old_name));
928     $new_units->{$form->{"name_$i"}} = \%h;
929     $new_units->{$form->{"name_$i"}}->{"row"} = $i;
930     set_unit_languages($new_units->{$form->{"old_name_$i"}}, \@languages, $i);
931   }
932
933   foreach my $unit (values(%{$new_units})) {
934     next unless ($unit->{"old_name"});
935     if ($unit->{"base_unit"}) {
936       $form->show_generic_error(sprintf($locale->text("The base unit does not exist or it is about to be deleted in row %d."), $unit->{"row"}))
937         unless (defined($new_units->{$unit->{"base_unit"}}));
938       $unit->{"factor"} = $form->parse_amount(\%myconfig, $unit->{"factor"});
939       $form->show_generic_error(sprintf($locale->text("The factor is missing in row %d."), $unit->{"row"})) unless ($unit->{"factor"} >= 1.0);
940     } else {
941       $unit->{"base_unit"} = undef;
942       $unit->{"factor"} = undef;
943     }
944   }
945
946   foreach my $unit (values(%{$new_units})) {
947     next if ($unit->{"unchanged_unit"});
948
949     map({ $_->{"seen"} = 0; } values(%{$new_units}));
950     my $new_unit = $unit;
951     while ($new_unit->{"base_unit"}) {
952       $new_unit->{"seen"} = 1;
953       $new_unit = $new_units->{$new_unit->{"base_unit"}};
954       if ($new_unit->{"seen"}) {
955         $form->show_generic_error(sprintf($locale->text("The base unit relations must not contain loops (e.g. by saying that unit A's base unit is B, " .
956                                                         "B's base unit is C and C's base unit is A) in row %d."), $unit->{"row"}));
957       }
958     }
959   }
960
961   AM->save_units(\%myconfig, $form, $new_units, \@delete_units);
962
963   flash_later('info', $locale->text("The units have been saved."));
964
965   print $form->redirect_header('am.pl?action=edit_units');
966
967   $main::lxdebug->leave_sub();
968 }
969
970 sub show_history_search {
971   $main::lxdebug->enter_sub();
972
973   my $form     = $main::form;
974   my $locale   = $main::locale;
975
976   $main::auth->assert('config');
977
978   setup_am_show_history_search_action_bar();
979
980   $form->{title} = $locale->text("History Search");
981   $form->header();
982
983   print $form->parse_html_template("common/search_history");
984
985   $main::lxdebug->leave_sub();
986 }
987
988 sub show_am_history {
989   $main::lxdebug->enter_sub();
990
991   my $form     = $main::form;
992   my %myconfig = %main::myconfig;
993   my $locale   = $main::locale;
994
995   $main::auth->assert('config');
996
997   my $callback     = build_std_url(qw(action einschraenkungen fromdate todate mitarbeiter searchid what2search));
998   $form->{order} ||= 'h.itime--1';
999
1000   # my %search = ( "Artikelnummer"          => "parts",
1001   #                "Kundennummer"           => "customer",
1002   #                "Lieferantennummer"      => "vendor",
1003   #                "Projektnummer"          => "project",
1004   #                "Auftragsnummer"         => "oe",
1005   #                "Angebotsnummer"         => "oe",
1006   #                "Eingangsrechnungnummer" => "ap",
1007   #                "Ausgangsrechnungnummer" => "ar",
1008   #                "Mahnungsnummer"         => "dunning",
1009   #                "Buchungsnummer"         => "gl",
1010   # );
1011
1012   my %searchNo = ( "Artikelnummer"          => "partnumber",
1013                    "Kundennummer"           => "customernumber",
1014                    "Lieferantennummer"      => "vendornumber",
1015                    "Projektnummer"          => "projectnumber",
1016                    "Auftragsnummer"         => "ordnumber",
1017                    "Angebotsnummer"         => "quonumber",
1018                    "Eingangsrechnungnummer" => "invnumber",
1019                    "Ausgangsrechnungnummer" => "invnumber",
1020                    "Mahnungsnummer"         => "dunning_id",
1021                    "Buchungsnummer"         => "gltransaction"
1022     );
1023
1024   my $dbh = $form->dbconnect(\%myconfig);
1025
1026   my $restriction;
1027   $restriction     = qq| AND (| . join(' OR ', map { " addition = " . $dbh->quote($_) } split(m/\,/, $form->{einschraenkungen})) . qq|)| if $form->{einschraenkungen};
1028   $restriction    .= qq| AND h.itime::date >= | . conv_dateq($form->{fromdate})                                                          if $form->{fromdate};
1029   $restriction    .= qq| AND h.itime::date <= | . conv_dateq($form->{todate})                                                            if $form->{todate};
1030   if ($form->{mitarbeiter} =~ m/^\d+$/) {
1031     $restriction  .= qq| AND employee_id = |    . $form->{mitarbeiter};
1032   } elsif ($form->{mitarbeiter}) {
1033     $restriction  .= qq| AND employee_id = (SELECT id FROM employee WHERE name ILIKE | . $dbh->quote('%' . $form->{mitarbeiter} . '%') . qq|)|;
1034   }
1035
1036   my $snumbers_where = '';
1037   my $snumbers_value;
1038   if ($form->{'searchid'}) {
1039     $snumbers_where = ' WHERE snumbers = ?';
1040     $snumbers_value = $searchNo{$form->{'what2search'}} . '_' . $form->{'searchid'};
1041   } else {
1042     $snumbers_where = ' WHERE snumbers ~ ?';
1043     $snumbers_value = '^' . $searchNo{$form->{'what2search'}};
1044   }
1045   my $query = qq|SELECT trans_id AS id FROM history_erp $snumbers_where|;
1046
1047   my @ids    = grep { $_ * 1 } selectall_array_query($form, $dbh, $query, $snumbers_value);
1048   my $daten .= shift @ids;
1049   if (scalar(@ids) > 0 ) {
1050     $daten  .= ' OR trans_id IN (' . join(',', @ids) . ')';
1051   }
1052   my ($sort, $sortby) = split(/\-\-/, $form->{order});
1053   $sort =~ s/.*\.(.*)$/$1/;
1054
1055   setup_am_show_am_history_action_bar();
1056
1057   $form->{title} = $locale->text("History Search");
1058   $form->header();
1059
1060   print $form->parse_html_template("common/show_history",
1061                                    { "DATEN"          => $form->get_history($dbh, $daten, $restriction, $form->{order}),
1062                                      "SUCCESS"        => ($form->get_history($dbh, $daten, $restriction, $form->{order}) ne "0"),
1063                                      "NONEWWINDOW"    => 1,
1064                                      uc($sort)        => 1,
1065                                      uc($sort) . "BY" => $sortby,
1066                                      'callback'       => $callback,
1067                                    });
1068   $dbh->disconnect();
1069
1070   $main::lxdebug->leave_sub();
1071 }
1072
1073 sub add_tax {
1074   $main::lxdebug->enter_sub();
1075
1076   my $form     = $main::form;
1077   my $locale   = $main::locale;
1078
1079   $main::auth->assert('config');
1080
1081   $form->{title} =  $locale->text('Add');
1082
1083   $form->{callback} ||= "am.pl?action=add_tax";
1084
1085   _get_taxaccount_selection();
1086
1087   $form->{asset}      = 1;
1088   $form->{liability}  = 1;
1089   $form->{equity}     = 1;
1090   $form->{revenue}    = 1;
1091   $form->{expense}    = 1;
1092   $form->{costs}      = 1;
1093
1094   setup_am_edit_tax_action_bar();
1095   $form->header();
1096
1097   my $parameters_ref = {
1098     LANGUAGES => SL::DB::Manager::Language->get_all_sorted,
1099   };
1100
1101   # Ausgabe des Templates
1102   print($form->parse_html_template('am/edit_tax', $parameters_ref));
1103
1104   $main::lxdebug->leave_sub();
1105 }
1106
1107 sub edit_tax {
1108   $main::lxdebug->enter_sub();
1109
1110   my $form     = $main::form;
1111   my %myconfig = %main::myconfig;
1112   my $locale   = $main::locale;
1113
1114   $main::auth->assert('config');
1115
1116   $form->{title} =  $locale->text('Edit');
1117
1118   AM->get_tax(\%myconfig, \%$form);
1119
1120   _get_taxaccount_selection();
1121
1122   $form->{asset}      = $form->{chart_categories} =~ 'A' ? 1 : 0;
1123   $form->{liability}  = $form->{chart_categories} =~ 'L' ? 1 : 0;
1124   $form->{equity}     = $form->{chart_categories} =~ 'Q' ? 1 : 0;
1125   $form->{revenue}    = $form->{chart_categories} =~ 'I' ? 1 : 0;
1126   $form->{expense}    = $form->{chart_categories} =~ 'E' ? 1 : 0;
1127   $form->{costs}      = $form->{chart_categories} =~ 'C' ? 1 : 0;
1128
1129   $form->{rate} = $form->format_amount(\%myconfig, $form->{rate}, 2);
1130
1131   setup_am_edit_tax_action_bar();
1132   $form->header();
1133
1134   my $parameters_ref = {
1135     LANGUAGES => SL::DB::Manager::Language->get_all_sorted,
1136     TAX       => SL::DB::Manager::Tax->find_by(id => $form->{id}),
1137   };
1138
1139   # Ausgabe des Templates
1140   print($form->parse_html_template('am/edit_tax', $parameters_ref));
1141
1142   $main::lxdebug->leave_sub();
1143 }
1144
1145 sub list_tax {
1146   $main::lxdebug->enter_sub();
1147
1148   my $form     = $main::form;
1149   my %myconfig = %main::myconfig;
1150   my $locale   = $main::locale;
1151
1152   $main::auth->assert('config');
1153
1154   AM->taxes(\%myconfig, \%$form);
1155
1156   map { $_->{rate} = $form->format_amount(\%myconfig, $_->{rate}, 2) } @{ $form->{TAX} };
1157
1158   $form->{callback} = build_std_url('action=list_tax');
1159
1160   $form->{title} = $locale->text('Tax-O-Matic');
1161
1162   setup_am_list_tax_action_bar();
1163   $form->header();
1164
1165   # Ausgabe des Templates
1166   print($form->parse_html_template('am/list_tax'));
1167
1168   $main::lxdebug->leave_sub();
1169 }
1170
1171 sub _get_taxaccount_selection{
1172   $main::lxdebug->enter_sub();
1173
1174   my $form     = $main::form;
1175   my %myconfig = %main::myconfig;
1176
1177   $main::auth->assert('config');
1178
1179   AM->get_tax_accounts(\%myconfig, \%$form);
1180
1181   map { $_->{selected} = $form->{chart_id} == $_->{id} } @{ $form->{ACCOUNTS} };
1182
1183   $main::lxdebug->leave_sub();
1184 }
1185
1186 sub save_tax {
1187   $main::lxdebug->enter_sub();
1188
1189   my $form     = $main::form;
1190   my %myconfig = %main::myconfig;
1191   my $locale   = $main::locale;
1192
1193   $main::auth->assert('config');
1194
1195   $form->error($locale->text('Taxkey  missing!')) unless length($form->{taxkey}) != 0;
1196   $form->error($locale->text('Taxdescription  missing!')) unless length($form->{taxdescription}) != 0;
1197   $form->error($locale->text('Taxrate missing!')) unless length($form->{rate}) != 0;
1198
1199   $form->{rate} = $form->parse_amount(\%myconfig, $form->{rate});
1200
1201   if ($form->{taxkey} == 0 and $form->{rate} > 0) {
1202     $form->error($locale->text('Taxkey 0 is reserved for rate 0'));
1203   }
1204
1205   if ( $form->{rate} < 0 || $form->{rate} >= 100 ) {
1206     $form->error($locale->text('Tax Percent is a number between 0 and 100'));
1207   }
1208
1209   if ( $form->{rate} <= 0.99 && $form->{rate} > 0 ) {
1210     $form->error($locale->text('Tax Percent is a number between 0 and 100'));
1211   }
1212
1213   my @translation_keys  =  grep { $_ =~ '^translation_\d+' } keys %$form;
1214   $form->{translations} = { map { $_ =~ '^translation_(\d+)'; $1 => $form->{$_} } @translation_keys };
1215
1216   AM->save_tax(\%myconfig, \%$form);
1217   $form->redirect($locale->text('Tax saved!'));
1218
1219   $main::lxdebug->leave_sub();
1220 }
1221
1222 sub delete_tax {
1223   $main::lxdebug->enter_sub();
1224
1225   my $form     = $main::form;
1226   my %myconfig = %main::myconfig;
1227   my $locale   = $main::locale;
1228
1229   $main::auth->assert('config');
1230
1231   AM->delete_tax(\%myconfig, \%$form);
1232   $form->redirect($locale->text('Tax deleted!'));
1233
1234   $main::lxdebug->leave_sub();
1235 }
1236
1237 sub add_warehouse {
1238   $main::lxdebug->enter_sub();
1239
1240   my $form     = $main::form;
1241   my $locale   = $main::locale;
1242
1243   $main::auth->assert('config');
1244
1245   $form->{title}      = $locale->text('Add Warehouse');
1246   $form->{callback} ||= build_std_url('action=add_warehouse');
1247
1248   setup_am_edit_warehouse_action_bar();
1249
1250   $form->header();
1251   print $form->parse_html_template('am/edit_warehouse');
1252
1253   $main::lxdebug->leave_sub();
1254 }
1255
1256 sub edit_warehouse {
1257   $main::lxdebug->enter_sub();
1258
1259   my $form     = $main::form;
1260   my %myconfig = %main::myconfig;
1261   my $locale   = $main::locale;
1262
1263   $main::auth->assert('config');
1264
1265   AM->get_warehouse(\%myconfig, $form);
1266
1267   $form->get_lists('employees' => 'EMPLOYEES');
1268
1269   $form->{title}      = $locale->text('Edit Warehouse');
1270   $form->{callback} ||= build_std_url('action=list_warehouses');
1271
1272   setup_am_edit_warehouse_action_bar(id => $::form->{id}, in_use => any { $_->{in_use} } @{ $::form->{BINS} });
1273
1274   $form->header();
1275   print $form->parse_html_template('am/edit_warehouse');
1276
1277   $main::lxdebug->leave_sub();
1278 }
1279
1280 sub edit_bins {
1281   $::auth->assert('config');
1282
1283   AM->get_warehouse(\%::myconfig, $::form);
1284
1285   $::form->{title}      = $::locale->text('Edit Bins for Warehouse \'#1\'', $::form->{description});
1286   $::form->{callback} ||= build_std_url('action=list_warehouses');
1287
1288   setup_am_edit_bins_action_bar(id => $::form->{id});
1289
1290   $::form->header;
1291   print $::form->parse_html_template('am/edit_bins');
1292 }
1293
1294 sub list_warehouses {
1295   $main::lxdebug->enter_sub();
1296
1297   my $form     = $main::form;
1298   my %myconfig = %main::myconfig;
1299   my $locale   = $main::locale;
1300
1301   $main::auth->assert('config');
1302
1303   AM->get_all_warehouses(\%myconfig, $form);
1304
1305   $form->{callback} = build_std_url('action=list_warehouses');
1306   $form->{title}    = $locale->text('Warehouses');
1307   $form->{url_base} = build_std_url('callback');
1308
1309   setup_am_list_warehouses_action_bar();
1310
1311   $form->header();
1312   print $form->parse_html_template('am/list_warehouses');
1313
1314   $main::lxdebug->leave_sub();
1315 }
1316
1317 sub save_warehouse {
1318   $main::lxdebug->enter_sub();
1319
1320   my $form     = $main::form;
1321   my %myconfig = %main::myconfig;
1322   my $locale   = $main::locale;
1323
1324   $main::auth->assert('config');
1325
1326   $form->isblank("description", $locale->text('Description missing!'));
1327
1328   $form->{number_of_new_bins} = $form->parse_amount(\%myconfig, $form->{number_of_new_bins});
1329
1330   AM->save_warehouse(\%myconfig, $form);
1331
1332   $form->{callback} .= '&saved_message=' . E($locale->text('Warehouse saved.')) if ($form->{callback});
1333
1334   $form->redirect($locale->text('Warehouse saved.'));
1335
1336   $main::lxdebug->leave_sub();
1337 }
1338
1339 sub delete_warehouse {
1340   $main::lxdebug->enter_sub();
1341
1342   my $form     = $main::form;
1343   my %myconfig = %main::myconfig;
1344   my $locale   = $main::locale;
1345
1346   $main::auth->assert('config');
1347
1348   if (AM->delete_warehouse(\%myconfig, $form)) {
1349     $form->{callback} .= '&saved_message=' . E($locale->text('Warehouse deleted.')) if ($form->{callback});
1350     $form->redirect($locale->text('Warehouse deleted.'));
1351
1352   } else {
1353     $form->error($locale->text('The warehouse could not be deleted because it has already been used.'));
1354   }
1355
1356   $main::lxdebug->leave_sub();
1357 }
1358
1359 sub save_bin {
1360   $main::lxdebug->enter_sub();
1361
1362   my $form     = $main::form;
1363   my %myconfig = %main::myconfig;
1364   my $locale   = $main::locale;
1365
1366   $main::auth->assert('config');
1367
1368   AM->save_bins(\%myconfig, $form);
1369
1370   $form->{callback} .= '&saved_message=' . E($locale->text('Bins saved.')) if ($form->{callback});
1371
1372   $form->redirect($locale->text('Bins saved.'));
1373
1374   $main::lxdebug->leave_sub();
1375 }
1376
1377 sub setup_am_config_action_bar {
1378   my %params = @_;
1379
1380   for my $bar ($::request->layout->get('actionbar')) {
1381     $bar->add(
1382       action => [
1383         t8('Save'),
1384         submit    => [ '#form', { action => "save_preferences" } ],
1385         accesskey => 'enter',
1386       ],
1387     );
1388   }
1389 }
1390
1391 sub setup_am_edit_account_action_bar {
1392   my %params = @_;
1393
1394   for my $bar ($::request->layout->get('actionbar')) {
1395     $bar->add(
1396       combobox => [
1397         action => [
1398           t8('Save'),
1399           submit    => [ '#form', { action => "save_account" } ],
1400           accesskey => 'enter',
1401         ],
1402
1403         action => [
1404           t8('Save as new'),
1405           submit   => [ '#form', { action => "save_as_new_account" } ],
1406           disabled => !$::form->{id} ? t8('The object has not been saved yet.') : undef,
1407         ],
1408       ],
1409
1410       action => [
1411         t8('Delete'),
1412         submit   => [ '#form', { action => "delete_account" } ],
1413         disabled => !$::form->{id}                         ? t8('The object has not been saved yet.')
1414                   :  $::form->{id} && !$::form->{orphaned} ? t8('The object is in use and cannot be deleted.')
1415                   :                                          undef,
1416         confirm  => t8('Do you really want to delete this object?'),
1417       ],
1418     );
1419   }
1420 }
1421
1422 sub setup_am_list_tax_action_bar {
1423   my %params = @_;
1424
1425   for my $bar ($::request->layout->get('actionbar')) {
1426     $bar->add(
1427       link => [
1428         t8('Add'),
1429         link => 'am.pl?action=add_tax',
1430       ],
1431     );
1432   }
1433 }
1434
1435 sub setup_am_edit_tax_action_bar {
1436   my %params = @_;
1437
1438   for my $bar ($::request->layout->get('actionbar')) {
1439     $bar->add(
1440       action => [
1441         t8('Save'),
1442         submit    => [ '#form', { action => "save_tax" } ],
1443         accesskey => 'enter',
1444       ],
1445
1446       action => [
1447         t8('Delete'),
1448         submit   => [ '#form', { action => "delete_tax" } ],
1449         disabled => !$::form->{id}                                      ? t8('The object has not been saved yet.')
1450                   : !$::form->{orphaned} || $::form->{tax_already_used} ? t8('The object is in use and cannot be deleted.')
1451                   :                                                       undef,
1452         confirm  => t8('Do you really want to delete this object?'),
1453       ],
1454     );
1455   }
1456 }
1457
1458 sub setup_am_add_unit_action_bar {
1459   my %params = @_;
1460
1461   for my $bar ($::request->layout->get('actionbar')) {
1462     $bar->add(
1463       action => [
1464         t8('Save'),
1465         submit    => [ '#form', { action => "create_unit" } ],
1466         accesskey => 'enter',
1467       ],
1468
1469       'separator',
1470
1471       link => [
1472         t8('Back'),
1473         link => 'am.pl?action=edit_units',
1474       ],
1475     );
1476   }
1477 }
1478
1479 sub setup_am_edit_units_action_bar {
1480   my %params = @_;
1481
1482   for my $bar ($::request->layout->get('actionbar')) {
1483     $bar->add(
1484       action => [
1485         t8('Save'),
1486         submit    => [ '#form', { action => "save_unit" } ],
1487         accesskey => 'enter',
1488       ],
1489
1490       'separator',
1491
1492       link => [
1493         t8('Add'),
1494         link => 'am.pl?action=add_unit',
1495       ],
1496     );
1497   }
1498 }
1499
1500 sub setup_am_list_warehouses_action_bar {
1501   my %params = @_;
1502
1503   for my $bar ($::request->layout->get('actionbar')) {
1504     $bar->add(
1505       link => [
1506         t8('Add'),
1507         link      => 'am.pl?action=add&type=warehouse&callback=' . E($::form->{callback}),
1508         accesskey => 'enter',
1509       ],
1510     );
1511   }
1512 }
1513
1514 sub setup_am_edit_warehouse_action_bar {
1515   my %params = @_;
1516
1517   for my $bar ($::request->layout->get('actionbar')) {
1518     $bar->add(
1519       action => [
1520         t8('Save'),
1521         submit    => [ '#form', { action => 'save_warehouse' } ],
1522         accesskey => 'enter',
1523       ],
1524
1525       action => [
1526         t8('Delete'),
1527         submit   => [ '#form', { action => 'delete_warehouse' } ],
1528         disabled => !$params{id}    ? t8('The object has not been saved yet.')
1529                   : $params{in_use} ? t8('The object is in use and cannot be deleted.')
1530                   :                   undef,
1531         confirm  => t8('Do you really want to delete this object?'),
1532       ],
1533
1534       'separator',
1535
1536       link => [
1537         t8('Bins'),
1538         link    => 'am.pl?action=edit_bins&id=' . E($params{id}),
1539         only_if => $params{id},
1540       ],
1541
1542       link => [
1543         t8('Abort'),
1544         link => $::form->{callback} || 'am.pl?action=list_warehouses',
1545       ],
1546     );
1547   }
1548 }
1549
1550 sub setup_am_edit_bins_action_bar {
1551   my %params = @_;
1552
1553   for my $bar ($::request->layout->get('actionbar')) {
1554     $bar->add(
1555       action => [
1556         t8('Save'),
1557         submit    => [ '#form', { action => 'save_bin' } ],
1558         accesskey => 'enter',
1559       ],
1560
1561       'separator',
1562
1563       link => [
1564         t8('Abort'),
1565         link => 'am.pl?action=edit_warehouse&id=' . E($params{id}),
1566       ],
1567     );
1568   }
1569 }
1570
1571 sub setup_am_audit_control_action_bar {
1572   my %params = @_;
1573
1574   for my $bar ($::request->layout->get('actionbar')) {
1575     $bar->add(
1576       action => [
1577         t8('Save'),
1578         submit    => [ '#form', { action => 'doclose' } ],
1579         accesskey => 'enter',
1580       ],
1581     );
1582   }
1583 }
1584
1585 sub setup_am_show_history_search_action_bar {
1586   my %params = @_;
1587
1588   for my $bar ($::request->layout->get('actionbar')) {
1589     $bar->add(
1590       action => [
1591         t8('Show'),
1592         submit    => [ '#form' ],
1593         accesskey => 'enter',
1594       ],
1595     );
1596   }
1597 }
1598
1599 sub setup_am_show_am_history_action_bar {
1600   my %params = @_;
1601
1602   for my $bar ($::request->layout->get('actionbar')) {
1603     $bar->add(
1604       action => [
1605         t8('Back'),
1606         call => [ 'kivi.history_back' ],
1607       ],
1608     );
1609   }
1610 }