ActionBar: Verwendung bei »System« → »Historiensuchmaschine«
[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 = (
231           1  => "Umsatzerlöse",
232           2  => "sonstige Erlöse",
233           3  => "Privatanteile",
234           4  => "Zinserträge",
235           5  => "Ausserordentliche Erträge",
236           6  => "Vereinnahmte Umsatzst.",
237           7  => "Umsatzsteuererstattungen",
238           8  => "Wareneingänge",
239           9  => "Löhne und Gehälter",
240           10 => "Gesetzl. sozialer Aufw.",
241           11 => "Mieten",
242           12 => "Gas, Strom, Wasser",
243           13 => "Instandhaltung",
244           14 => "Steuern, Versich., Beiträge",
245           15 => "Kfz-Steuern",
246           16 => "Kfz-Versicherungen",
247           17 => "Sonst. Fahrzeugkosten",
248           18 => "Werbe- und Reisekosten",
249           19 => "Instandhaltung u. Werkzeuge",
250           20 => "Fachzeitschriften, Bücher",
251           21 => "Miete für Einrichtungen",
252           22 => "Rechts- und Beratungskosten",
253           23 => "Bürobedarf, Porto, Telefon",
254           24 => "Sonstige Aufwendungen",
255           25 => "Abschreibungen auf Anlagever.",
256           26 => "Abschreibungen auf GWG",
257           27 => "Vorsteuer",
258           28 => "Umsatzsteuerzahlungen",
259           29 => "Zinsaufwand",
260           30 => "Ausserordentlicher Aufwand",
261           31 => "Betriebliche Steuern");
262   foreach my $item (sort({ $a <=> $b } keys(%eur))) {
263     my $text = H($::locale->{iconv_utf8}->convert($eur{$item}));
264     if ($item == $form->{pos_eur}) {
265       $select_eur .= qq|<option value=$item selected>|. sprintf("%.2d", $item) .qq|. $text</option>\n|;
266     } else {
267       $select_eur .= qq|<option value=$item>|. sprintf("%.2d", $item) .qq|. $text</option>\n|;
268     }
269
270   }
271
272   my $select_er = q|<option value=""> |. $locale->text('None') .q|</option>\n|;
273   my %er = (
274        1  => "Ertrag",
275        6  => "Aufwand");
276   foreach my $item (sort({ $a <=> $b } keys(%er))) {
277     my $text = H($::locale->{iconv_utf8}->convert($er{$item}));
278     if ($item == $form->{pos_er}) {
279       $select_er .= qq|<option value=$item selected>|. sprintf("%.2d", $item) .qq|. $text</option>\n|;
280     } else {
281       $select_er .= qq|<option value=$item>|. sprintf("%.2d", $item) .qq|. $text</option>\n|;
282     }
283
284   }
285
286   my $select_bwa = q|<option value=""> |. $locale->text('None') .q|</option>\n|;
287
288   my %bwapos = (
289              1  => 'Umsatzerlöse',
290              2  => 'Best.Verdg.FE/UE',
291              3  => 'Aktiv.Eigenleistung',
292              4  => 'Mat./Wareneinkauf',
293              5  => 'So.betr.Erlöse',
294              10 => 'Personalkosten',
295              11 => 'Raumkosten',
296              12 => 'Betriebl.Steuern',
297              13 => 'Vers./Beiträge',
298              14 => 'Kfz.Kosten o.St.',
299              15 => 'Werbe-Reisek.',
300              16 => 'Kosten Warenabgabe',
301              17 => 'Abschreibungen',
302              18 => 'Rep./instandhlt.',
303              19 => 'Übrige Steuern',
304              20 => 'Sonst.Kosten',
305              30 => 'Zinsauwand',
306              31 => 'Sonst.neutr.Aufw.',
307              32 => 'Zinserträge',
308              33 => 'Sonst.neutr.Ertrag',
309              34 => 'Verr.kalk.Kosten',
310              35 => 'Steuern Eink.u.Ertr.');
311   foreach my $item (sort({ $a <=> $b } keys %bwapos)) {
312     my $text = H($::locale->{iconv_utf8}->convert($bwapos{$item}));
313     if ($item == $form->{pos_bwa}) {
314       $select_bwa .= qq|<option value="$item" selected>|. sprintf("%.2d", $item) .qq|. $text\n|;
315     } else {
316       $select_bwa .= qq|<option value="$item">|. sprintf("%.2d", $item) .qq|. $text\n|;
317     }
318
319   }
320
321 # Wieder hinzugefügt zu evaluationszwecken (us) 09.03.2007
322   my $select_bilanz = q|<option value=""> |. $locale->text('None') .q|</option>\n|;
323   foreach my $item ((1, 2, 3, 4)) {
324     if ($item == $form->{pos_bilanz}) {
325       $select_bilanz .= qq|<option value=$item selected>|. sprintf("%.2d", $item) .qq|.\n|;
326     } else {
327       $select_bilanz .= qq|<option value=$item>|. sprintf("%.2d", $item) .qq|.\n|;
328     }
329
330   }
331
332   # this is for our parser only! Do not remove.
333   # type=submit $locale->text('Add Account')
334   # type=submit $locale->text('Edit Account')
335
336   $form->{type} = "account";
337
338   # preselections category
339
340   my $select_category = q|<option value=""> |. $locale->text('None') .q|</option>\n|;
341
342   my %category = (
343       'A'  => $locale->text('Asset'),
344       'L'  => $locale->text('Liability'),
345       'Q'  => $locale->text('Equity'),
346       'I'  => $locale->text('Revenue'),
347       'E'  => $locale->text('Expense'),
348       'C'  => $locale->text('Costs'),
349   );
350   foreach my $item ( sort({ $a <=> $b } keys %category) ) {
351     if ($item eq $form->{category}) {
352       $select_category .= qq|<option value="$item" selected="selected">$category{$item} (|. sprintf("%s", $item) .qq|)\n|;
353     } else {
354       $select_category .= qq|<option value="$item">$category{$item} (|. sprintf("%s", $item) .qq|)\n|;
355     }
356
357   }
358
359   # preselection chart type
360   my @all_charttypes = ({'name' => $locale->text('Account'), 'value' => 'A'},
361                         {'name' => $locale->text('Heading'), 'value' => 'H'},
362     );
363   my $selected_charttype = $form->{charttype};
364
365
366   # account where AR_tax or AP_tax is set are not orphaned if they are used as
367   # tax-o-matic account
368   if ( $form->{id} && $form->{orphaned} && ($form->{link} =~ m/(AP_tax|AR_tax)/) ) {
369     if (SL::DB::Manager::Tax->find_by(chart_id => $form->{id})) {
370       $form->{orphaned} = 0;
371     }
372   }
373
374   my $ChartTypeIsAccount = ($form->{charttype} eq "A") ? "1":"";
375   my $AccountIsPosted = ($form->{orphaned} ) ? "":"1";
376
377   setup_am_edit_account_action_bar();
378
379   $form->header();
380
381   my $parameters_ref = {
382     ChartTypeIsAccount         => $ChartTypeIsAccount,
383     AccountIsPosted            => $AccountIsPosted,
384     select_category            => $select_category,
385     all_charttypes             => \@all_charttypes,
386     selected_charttype         => $selected_charttype,
387     select_bwa                 => $select_bwa,
388     select_bilanz              => $select_bilanz,
389     select_eur                 => $select_eur,
390     select_er                  => $select_er,
391   };
392
393   # Ausgabe des Templates
394   print($form->parse_html_template('am/edit_accounts', $parameters_ref));
395
396
397   $main::lxdebug->leave_sub();
398 }
399
400 sub form_footer {
401   $::lxdebug->enter_sub;
402   $::auth->assert('config');
403
404   print $::form->parse_html_template('am/form_footer', {
405     show_save        => !$::form->{id}
406                      || ($::form->{id} && $::form->{orphaned})
407                      || ($::form->{type} eq "account" && !$::form->{new_chart_valid}),
408     show_delete      => $::form->{id} && $::form->{orphaned},
409     show_save_as_new => $::form->{id} && $::form->{type} eq "account",
410   });
411
412   $::lxdebug->leave_sub;
413 }
414
415 sub save_account {
416   $main::lxdebug->enter_sub();
417
418   my $form     = $main::form;
419   my %myconfig = %main::myconfig;
420   my $locale   = $main::locale;
421
422   $main::auth->assert('config');
423
424   $form->isblank("accno",       $locale->text('Account Number missing!'));
425   $form->isblank("description", $locale->text('Account Description missing!'));
426
427   if ($form->{charttype} eq 'A'){
428     $form->isblank("category",  $locale->text('Account Type missing!'));
429
430     my $found_valid_taxkey = 0;
431     foreach my $i (0 .. 10) { # 10 is maximum count of taxkeys in form
432       if ($form->{"taxkey_startdate_$i"} and !$form->{"taxkey_del_$i"}) {
433         $found_valid_taxkey = 1;
434         last;
435       }
436     }
437     if ($found_valid_taxkey == 0) {
438       $form->error($locale->text('A valid taxkey is missing!'));
439     }
440   }
441
442   $form->redirect($locale->text('Account saved!'))
443     if (AM->save_account(\%myconfig, \%$form));
444   $form->error($locale->text('Cannot save account!'));
445
446   $main::lxdebug->leave_sub();
447 }
448
449 sub save_as_new_account {
450   $main::lxdebug->enter_sub();
451
452   my $form     = $main::form;
453   my %myconfig = %main::myconfig;
454   my $locale   = $main::locale;
455
456   $main::auth->assert('config');
457
458   $form->isblank("accno",       $locale->text('Account Number missing!'));
459   $form->isblank("description", $locale->text('Account Description missing!'));
460
461   if ($form->{charttype} eq 'A'){
462     $form->isblank("category",  $locale->text('Account Type missing!'));
463   }
464
465   for my $taxkey (0 .. 9) {
466     if ($form->{"taxkey_id_$taxkey"}) {
467       $form->{"taxkey_id_$taxkey"} = "NEW";
468     }
469   }
470
471   $form->{id} = 0;
472   $form->redirect($locale->text('Account saved!'))
473     if (AM->save_account(\%myconfig, \%$form));
474   $form->error($locale->text('Cannot save account!'));
475
476   $main::lxdebug->leave_sub();
477 }
478
479 sub list_account {
480   $main::lxdebug->enter_sub();
481
482   my $form     = $main::form;
483   my %myconfig = %main::myconfig;
484   my $locale   = $main::locale;
485
486   $main::auth->assert('config');
487
488   $form->{callback}     = build_std_url('action=list_account');
489   my $link_edit_account = build_std_url('action=edit_account', 'callback');
490
491   CA->all_accounts(\%myconfig, \%$form);
492
493   foreach my $ca (@{ $form->{CA} }) {
494
495     $ca->{debit}  = "";
496     $ca->{credit} = "";
497
498     if ($ca->{amount} > 0) {
499       $ca->{credit} = $form->format_amount(\%myconfig, $ca->{amount}, 2);
500     }
501     if ($ca->{amount} < 0) {
502       $ca->{debit} = $form->format_amount(\%myconfig, -1 * $ca->{amount}, 2);
503     }
504     $ca->{heading}   = ( $ca->{charttype} eq 'H' ) ? 1:'';
505     $ca->{link_edit_account} = $link_edit_account . '&id=' . E($ca->{id});
506   }
507
508   $::request->{layout}->use_stylesheet("list_accounts.css");
509   $form->{title}       = $locale->text('Chart of Accounts');
510
511   $form->header;
512
513
514   my $parameters_ref = {
515   #   hidden_variables                => $_hidden_variables_ref,
516   };
517
518   # Ausgabe des Templates
519   print($form->parse_html_template('am/list_accounts', $parameters_ref));
520
521   $main::lxdebug->leave_sub();
522
523 }
524
525
526 sub list_account_details {
527 # Ajax Funktion aus list_account_details
528   $main::lxdebug->enter_sub();
529
530   my $form     = $main::form;
531   my %myconfig = %main::myconfig;
532   my $locale   = $main::locale;
533
534   $main::auth->assert('config');
535
536   my $chart_id = $form->{args};
537
538   CA->all_accounts(\%myconfig, \%$form, $chart_id);
539
540   foreach my $ca (@{ $form->{CA} }) {
541
542     $ca->{debit}  = "&nbsp;";
543     $ca->{credit} = "&nbsp;";
544
545     if ($ca->{amount} > 0) {
546       $ca->{credit} =
547         $form->format_amount(\%myconfig, $ca->{amount}, 2, "&nbsp;");
548     }
549     if ($ca->{amount} < 0) {
550       $ca->{debit} =
551         $form->format_amount(\%myconfig, -1 * $ca->{amount}, 2, "&nbsp;");
552     }
553
554     my @links = split( q{:}, $ca->{link});
555
556     $ca->{link} = q{};
557
558     foreach my $link (@links){
559       $link =    ( $link eq 'AR')             ? $locale->text('Account Link AR')
560                : ( $link eq 'AP')             ? $locale->text('Account Link AP')
561                : ( $link eq 'IC')             ? $locale->text('Account Link IC')
562                : ( $link eq 'AR_amount' )     ? $locale->text('Account Link AR_amount')
563                : ( $link eq 'AR_paid' )       ? $locale->text('Account Link AR_paid')
564                : ( $link eq 'AR_tax' )        ? $locale->text('Account Link AR_tax')
565                : ( $link eq 'AP_amount' )     ? $locale->text('Account Link AP_amount')
566                : ( $link eq 'AP_paid' )       ? $locale->text('Account Link AP_paid')
567                : ( $link eq 'AP_tax' )        ? $locale->text('Account Link AP_tax')
568                : ( $link eq 'IC_sale' )       ? $locale->text('Account Link IC_sale')
569                : ( $link eq 'IC_cogs' )       ? $locale->text('Account Link IC_cogs')
570                : ( $link eq 'IC_taxpart' )    ? $locale->text('Account Link IC_taxpart')
571                : ( $link eq 'IC_income' )     ? $locale->text('Account Link IC_income')
572                : ( $link eq 'IC_expense' )    ? $locale->text('Account Link IC_expense')
573                : ( $link eq 'IC_taxservice' ) ? $locale->text('Account Link IC_taxservice')
574                : $locale->text('Unknown Link') . ': ' . $link;
575       $ca->{link} .= ($link ne '') ?  "[$link] ":'';
576     }
577
578     $ca->{category} = ($ca->{category} eq 'A') ? $locale->text('Account Category A')
579                     : ($ca->{category} eq 'E') ? $locale->text('Account Category E')
580                     : ($ca->{category} eq 'L') ? $locale->text('Account Category L')
581                     : ($ca->{category} eq 'I') ? $locale->text('Account Category I')
582                     : ($ca->{category} eq 'Q') ? $locale->text('Account Category Q')
583                     : ($ca->{category} eq 'C') ? $locale->text('Account Category C')
584                     : ($ca->{category} eq 'G') ? $locale->text('Account Category G')
585                     : $locale->text('Unknown Category') . ': ' . $ca->{category};
586   }
587
588   $form->{title} = $locale->text('Chart of Accounts');
589
590   print $form->ajax_response_header, $form->parse_html_template('am/list_account_details');
591
592   $main::lxdebug->leave_sub();
593
594 }
595
596 sub delete_account {
597   $main::lxdebug->enter_sub();
598
599   my $form     = $main::form;
600   my %myconfig = %main::myconfig;
601   my $locale   = $main::locale;
602
603   $main::auth->assert('config');
604
605   $form->{title} = $locale->text('Delete Account');
606
607   foreach my $id (
608     qw(inventory_accno_id income_accno_id expense_accno_id fxgain_accno_id fxloss_accno_id rndgain_accno_id rndloss_accno_id)
609     ) {
610     if ($form->{id} == $form->{$id}) {
611       $form->error($locale->text('Cannot delete default account!'));
612     }
613   }
614
615   $form->redirect($locale->text('Account deleted!'))
616     if (AM->delete_account(\%myconfig, \%$form));
617   $form->error($locale->text('Cannot delete account!'));
618
619   $main::lxdebug->leave_sub();
620 }
621
622 sub _build_cfg_options {
623   my $form     = $main::form;
624   my %myconfig = %main::myconfig;
625
626   my $idx   = shift;
627   my $array = uc($idx) . 'S';
628
629   $form->{$array} = [];
630   foreach my $item (@_) {
631     push @{ $form->{$array} }, {
632       'name'     => $item,
633       'value'    => $item,
634       'selected' => $item eq $myconfig{$idx},
635     };
636   }
637 }
638
639 sub config {
640   $main::lxdebug->enter_sub();
641
642   my $form     = $main::form;
643   my %myconfig = %main::myconfig;
644   my $locale   = $main::locale;
645
646   _build_cfg_options('dateformat', qw(mm/dd/yy dd/mm/yy dd.mm.yy yyyy-mm-dd));
647   _build_cfg_options('timeformat', qw(hh:mm hh:mm:ss));
648   _build_cfg_options('numberformat', ('1,000.00', '1000.00', '1.000,00', '1000,00', "1'000.00"));
649
650   my @formats = ();
651   if ($::lx_office_conf{print_templates}->{opendocument}
652       && $::lx_office_conf{applications}->{openofficeorg_writer} && (-x $::lx_office_conf{applications}->{openofficeorg_writer})
653       && $::lx_office_conf{applications}->{xvfb}                 && (-x $::lx_office_conf{applications}->{xvfb})) {
654     push(@formats, { "name" => $locale->text("PDF (OpenDocument/OASIS)"),
655                      "value" => "opendocument_pdf" });
656   }
657   if ($::lx_office_conf{print_templates}->{latex}) {
658     push(@formats, { "name" => $locale->text("PDF"), "value" => "pdf" });
659   }
660   push(@formats, { "name" => "HTML", "value" => "html" });
661   if ($::lx_office_conf{print_templates}->{latex}) {
662     push(@formats, { "name" => $locale->text("Postscript"),
663                      "value" => "postscript" });
664   }
665   if ($::lx_office_conf{print_templates}->{opendocument}) {
666     push(@formats, { "name" => $locale->text("OpenDocument/OASIS"),
667                      "value" => "opendocument" });
668   }
669
670   if (!$myconfig{"template_format"}) {
671     $myconfig{"template_format"} = "pdf";
672   }
673   $form->{TEMPLATE_FORMATS} = [];
674   foreach my $item (@formats) {
675     push @{ $form->{TEMPLATE_FORMATS} }, {
676       'name'     => $item->{name},
677       'value'    => $item->{value},
678       'selected' => $item->{value} eq $myconfig{template_format},
679     };
680   }
681
682   if (!$myconfig{"default_media"}) {
683     $myconfig{"default_media"} = "screen";
684   }
685
686   my %selected = ($myconfig{"default_media"} => "selected");
687   $form->{MEDIA} = [
688     { 'name' => $locale->text('Screen'),  'value' => 'screen',  'selected' => $selected{screen}, },
689     { 'name' => $locale->text('Printer'), 'value' => 'printer', 'selected' => $selected{printer}, },
690     { 'name' => $locale->text('Queue'),   'value' => 'queue',   'selected' => $selected{queue}, },
691     ];
692
693   $form->{PRINTERS} = SL::DB::Manager::Printer->get_all_sorted;
694
695   my %countrycodes = User->country_codes;
696
697   $form->{COUNTRYCODES} = [];
698   foreach my $countrycode (sort { $countrycodes{$a} cmp $countrycodes{$b} } keys %countrycodes) {
699     push @{ $form->{COUNTRYCODES} }, {
700       'name'     => $countrycodes{$countrycode},
701       'value'    => $countrycode,
702       'selected' => $countrycode eq $myconfig{countrycode},
703     };
704   }
705
706   $form->{STYLESHEETS} = [];
707   foreach my $item (qw(lx-office-erp.css kivitendo.css)) {
708     push @{ $form->{STYLESHEETS} }, {
709       'name'     => $item,
710       'value'    => $item,
711       'selected' => $item eq $myconfig{stylesheet},
712     };
713   }
714
715   $myconfig{show_form_details} = 1 unless (defined($myconfig{show_form_details}));
716   $form->{CAN_CHANGE_PASSWORD} = $main::auth->can_change_password();
717   $form->{todo_cfg}            = { TODO->get_user_config('login' => $::myconfig{login}) };
718
719   $form->{title}               = $locale->text('Edit Preferences for #1', $::myconfig{login});
720
721   setup_am_config_action_bar();
722
723   $form->header();
724
725   $form->{full_signature} = $form->create_email_signature();
726
727   print $form->parse_html_template('am/config');
728
729   $main::lxdebug->leave_sub();
730 }
731
732 sub save_preferences {
733   $main::lxdebug->enter_sub();
734
735   my $form     = $main::form;
736   my %myconfig = %main::myconfig;
737   my $locale   = $main::locale;
738
739   $form->{stylesheet} = $form->{usestylesheet};
740
741   TODO->save_user_config('login' => $::myconfig{login}, %{ $form->{todo_cfg} || { } });
742
743   if (AM->save_preferences($form)) {
744     if ($::auth->can_change_password()
745         && defined $form->{new_password}
746         && ($form->{new_password} ne '********')) {
747       my $verifier = SL::Auth::PasswordPolicy->new;
748       my $result   = $verifier->verify($form->{new_password});
749
750       if ($result != SL::Auth::PasswordPolicy->OK()) {
751         $form->error($::locale->text('The settings were saved, but the password was not changed.') . ' ' . join(' ', $verifier->errors($result)));
752       }
753
754       $::auth->change_password($::myconfig{login}, $form->{new_password});
755     }
756
757     $form->redirect($locale->text('Preferences saved!'));
758   }
759
760   $form->error($locale->text('Cannot save preferences!'));
761
762   $main::lxdebug->leave_sub();
763 }
764
765 sub audit_control {
766   $::lxdebug->enter_sub;
767   $::auth->assert('config');
768
769   $::form->{title} = $::locale->text('Audit Control');
770
771   AM->closedto(\%::myconfig, $::form);
772
773   setup_am_audit_control_action_bar();
774
775   $::form->header;
776   print $::form->parse_html_template('am/audit_control');
777
778   $::lxdebug->leave_sub;
779 }
780
781 sub doclose {
782   $main::lxdebug->enter_sub();
783
784   my $form     = $main::form;
785   my %myconfig = %main::myconfig;
786   my $locale   = $main::locale;
787
788   $main::auth->assert('config');
789
790   AM->closebooks(\%myconfig, \%$form);
791
792   if ($form->{closedto}) {
793     $form->redirect(
794                     $locale->text('Books closed up to') . " "
795                       . $locale->date(\%myconfig, $form->{closedto}, 1));
796   } else {
797     $form->redirect($locale->text('Books are open'));
798   }
799
800   $main::lxdebug->leave_sub();
801 }
802
803 sub add_unit {
804   $::auth->assert('config');
805
806   # my $units = AM->retrieve_units(\%::myconfig, $::form, "resolved_");
807   # # AM->units_in_use(\%::myconfig, $::form, $units);
808
809   # $units->{$_}->{BASE_UNIT_DDBOX} = AM->unit_select_data($units, $units->{$_}->{base_unit}, 1) for keys %{$units};
810
811   my @languages = @{ SL::DB::Manager::Language->get_all_sorted };
812
813   my $units = AM->retrieve_units(\%::myconfig, $::form);
814   my $ddbox = AM->unit_select_data($units, undef, 1);
815
816   setup_am_add_unit_action_bar();
817
818   $::form->{title} = $::locale->text("Add unit");
819   $::form->header();
820   print($::form->parse_html_template("am/add_unit", {
821     NEW_BASE_UNIT_DDBOX => $ddbox,
822     LANGUAGES           => \@languages,
823   }));
824 }
825
826 sub edit_units {
827   $main::lxdebug->enter_sub();
828
829   my $form     = $main::form;
830   my %myconfig = %main::myconfig;
831   my $locale   = $main::locale;
832
833   $main::auth->assert('config');
834
835   my $units = AM->retrieve_units(\%myconfig, $form, "resolved_");
836   AM->units_in_use(\%myconfig, $form, $units);
837   map({ $units->{$_}->{"BASE_UNIT_DDBOX"} = AM->unit_select_data($units, $units->{$_}->{"base_unit"}, 1); } keys(%{$units}));
838
839   my @languages = @{ SL::DB::Manager::Language->get_all_sorted };
840
841   my @unit_list = sort({ $a->{"sortkey"} <=> $b->{"sortkey"} } values(%{$units}));
842
843   my $i = 1;
844   foreach (@unit_list) {
845     $_->{"factor"} = $form->format_amount(\%myconfig, $_->{"factor"} * 1) if ($_->{"factor"});
846     $_->{"UNITLANGUAGES"} = [];
847     foreach my $lang (@languages) {
848       push(@{ $_->{"UNITLANGUAGES"} },
849            { "idx"              => $i,
850              "unit"             => $_->{"name"},
851              "language_id"      => $lang->id,
852              "localized"        => $_->{"LANGUAGES"}->{$lang->template_code}->{"localized"},
853              "localized_plural" => $_->{"LANGUAGES"}->{$lang->template_code}->{"localized_plural"},
854            });
855     }
856     $i++;
857   }
858
859   $units = AM->retrieve_units(\%myconfig, $form);
860   my $ddbox = AM->unit_select_data($units, undef, 1);
861
862   setup_am_edit_units_action_bar();
863
864   $form->{"title"} = $locale->text("Edit units");
865   $form->header();
866   print($form->parse_html_template("am/edit_units",
867                                    { "UNITS"               => \@unit_list,
868                                      "NEW_BASE_UNIT_DDBOX" => $ddbox,
869                                      "LANGUAGES"           => \@languages,
870                                    }));
871
872   $main::lxdebug->leave_sub();
873 }
874
875 sub create_unit {
876   $main::lxdebug->enter_sub();
877
878   my $form     = $main::form;
879   my %myconfig = %main::myconfig;
880   my $locale   = $main::locale;
881
882   $main::auth->assert('config');
883
884   $form->isblank("new_name", $locale->text("The name is missing."));
885   my $units = AM->retrieve_units(\%myconfig, $form);
886   my $all_units = AM->retrieve_units(\%myconfig, $form);
887   $form->show_generic_error($locale->text("A unit with this name does already exist.")) if ($all_units->{$form->{"new_name"}});
888
889   my ($base_unit, $factor);
890   if ($form->{"new_base_unit"}) {
891     $form->show_generic_error($locale->text("The base unit does not exist.")) unless (defined($units->{$form->{"new_base_unit"}}));
892
893     $form->isblank("new_factor", $locale->text("The factor is missing."));
894     $factor = $form->parse_amount(\%myconfig, $form->{"new_factor"});
895     $form->show_generic_error($locale->text("The factor is missing.")) unless ($factor);
896     $base_unit = $form->{"new_base_unit"};
897   }
898
899   my @languages;
900   foreach my $lang (@{ SL::DB::Manager::Language->get_all_sorted }) {
901     next unless ($form->{"new_localized_$lang->{id}"} || $form->{"new_localized_plural_$lang->{id}"});
902     push(@languages, { "id"               => $lang->id,
903                        "localized"        => $form->{"new_localized_" . $lang->id},
904                        "localized_plural" => $form->{"new_localized_plural_" . $lang->id},
905          });
906   }
907
908   AM->add_unit(\%myconfig, $form, $form->{"new_name"}, $base_unit, $factor, \@languages);
909
910   flash_later('info', $locale->text("The unit has been added."));
911
912   print $form->redirect_header('am.pl?action=edit_units');
913
914   $main::lxdebug->leave_sub();
915 }
916
917 sub set_unit_languages {
918   $main::lxdebug->enter_sub();
919
920   my $form     = $main::form;
921
922   $main::auth->assert('config');
923
924   my ($unit, $languages, $idx) = @_;
925
926   $unit->{"LANGUAGES"} = [];
927
928   foreach my $lang (@{$languages}) {
929     push(@{ $unit->{"LANGUAGES"} },
930          { "id"               => $lang->id,
931            "localized"        => $form->{"localized_${idx}_" . $lang->id},
932            "localized_plural" => $form->{"localized_plural_${idx}_" . $lang->id},
933          });
934   }
935
936   $main::lxdebug->leave_sub();
937 }
938
939 sub save_unit {
940   $main::lxdebug->enter_sub();
941
942   my $form     = $main::form;
943   my %myconfig = %main::myconfig;
944   my $locale   = $main::locale;
945
946   $main::auth->assert('config');
947
948   my $old_units = AM->retrieve_units(\%myconfig, $form, "resolved_");
949   AM->units_in_use(\%myconfig, $form, $old_units);
950
951   my @languages = @{ SL::DB::Manager::Language->get_all_sorted };
952
953   my $new_units = {};
954   my @delete_units = ();
955   foreach my $i (1..($form->{"rowcount"} * 1)) {
956     my $old_unit = $old_units->{$form->{"old_name_$i"}};
957     if (!$old_unit) {
958       $form->show_generic_error(sprintf($locale->text("The unit in row %d has been deleted in the meantime."), $i));
959     }
960
961     if ($form->{"unchangeable_$i"}) {
962       $new_units->{$form->{"old_name_$i"}} = $old_units->{$form->{"old_name_$i"}};
963       $new_units->{$form->{"old_name_$i"}}->{"unchanged_unit"} = 1;
964       set_unit_languages($new_units->{$form->{"old_name_$i"}}, \@languages, $i);
965       next;
966     }
967
968     if ($old_unit->{"in_use"}) {
969       $form->show_generic_error(sprintf($locale->text("The unit in row %d has been used in the meantime and cannot be changed anymore."), $i));
970     }
971
972     if ($form->{"delete_$i"}) {
973       push(@delete_units, $old_unit->{"name"});
974       next;
975     }
976
977     $form->isblank("name_$i", sprintf($locale->text("The name is missing in row %d."), $i));
978
979     $form->show_generic_error(sprintf($locale->text("The name in row %d has already been used before."), $i)) if ($new_units->{$form->{"name_$i"}});
980     my %h = map({ $_ => $form->{"${_}_$i"} } qw(name base_unit factor old_name));
981     $new_units->{$form->{"name_$i"}} = \%h;
982     $new_units->{$form->{"name_$i"}}->{"row"} = $i;
983     set_unit_languages($new_units->{$form->{"old_name_$i"}}, \@languages, $i);
984   }
985
986   foreach my $unit (values(%{$new_units})) {
987     next unless ($unit->{"old_name"});
988     if ($unit->{"base_unit"}) {
989       $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"}))
990         unless (defined($new_units->{$unit->{"base_unit"}}));
991       $unit->{"factor"} = $form->parse_amount(\%myconfig, $unit->{"factor"});
992       $form->show_generic_error(sprintf($locale->text("The factor is missing in row %d."), $unit->{"row"})) unless ($unit->{"factor"} >= 1.0);
993     } else {
994       $unit->{"base_unit"} = undef;
995       $unit->{"factor"} = undef;
996     }
997   }
998
999   foreach my $unit (values(%{$new_units})) {
1000     next if ($unit->{"unchanged_unit"});
1001
1002     map({ $_->{"seen"} = 0; } values(%{$new_units}));
1003     my $new_unit = $unit;
1004     while ($new_unit->{"base_unit"}) {
1005       $new_unit->{"seen"} = 1;
1006       $new_unit = $new_units->{$new_unit->{"base_unit"}};
1007       if ($new_unit->{"seen"}) {
1008         $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, " .
1009                                                         "B's base unit is C and C's base unit is A) in row %d."), $unit->{"row"}));
1010       }
1011     }
1012   }
1013
1014   AM->save_units(\%myconfig, $form, $new_units, \@delete_units);
1015
1016   flash_later('info', $locale->text("The units have been saved."));
1017
1018   print $form->redirect_header('am.pl?action=edit_units');
1019
1020   $main::lxdebug->leave_sub();
1021 }
1022
1023 sub show_history_search {
1024   $main::lxdebug->enter_sub();
1025
1026   my $form     = $main::form;
1027   my $locale   = $main::locale;
1028
1029   $main::auth->assert('config');
1030
1031   setup_am_show_history_search_action_bar();
1032
1033   $form->{title} = $locale->text("History Search");
1034   $form->header();
1035
1036   print $form->parse_html_template("common/search_history");
1037
1038   $main::lxdebug->leave_sub();
1039 }
1040
1041 sub show_am_history {
1042   $main::lxdebug->enter_sub();
1043
1044   my $form     = $main::form;
1045   my %myconfig = %main::myconfig;
1046   my $locale   = $main::locale;
1047
1048   $main::auth->assert('config');
1049
1050   my $callback     = build_std_url(qw(action einschraenkungen fromdate todate mitarbeiter searchid what2search));
1051   $form->{order} ||= 'h.itime--1';
1052
1053   # my %search = ( "Artikelnummer"          => "parts",
1054   #                "Kundennummer"           => "customer",
1055   #                "Lieferantennummer"      => "vendor",
1056   #                "Projektnummer"          => "project",
1057   #                "Auftragsnummer"         => "oe",
1058   #                "Angebotsnummer"         => "oe",
1059   #                "Eingangsrechnungnummer" => "ap",
1060   #                "Ausgangsrechnungnummer" => "ar",
1061   #                "Mahnungsnummer"         => "dunning",
1062   #                "Buchungsnummer"         => "gl",
1063   # );
1064
1065   my %searchNo = ( "Artikelnummer"          => "partnumber",
1066                    "Kundennummer"           => "customernumber",
1067                    "Lieferantennummer"      => "vendornumber",
1068                    "Projektnummer"          => "projectnumber",
1069                    "Auftragsnummer"         => "ordnumber",
1070                    "Angebotsnummer"         => "quonumber",
1071                    "Eingangsrechnungnummer" => "invnumber",
1072                    "Ausgangsrechnungnummer" => "invnumber",
1073                    "Mahnungsnummer"         => "dunning_id",
1074                    "Buchungsnummer"         => "gltransaction"
1075     );
1076
1077   my $dbh = $form->dbconnect(\%myconfig);
1078
1079   my $restriction;
1080   $restriction     = qq| AND (| . join(' OR ', map { " addition = " . $dbh->quote($_) } split(m/\,/, $form->{einschraenkungen})) . qq|)| if $form->{einschraenkungen};
1081   $restriction    .= qq| AND h.itime::date >= | . conv_dateq($form->{fromdate})                                                          if $form->{fromdate};
1082   $restriction    .= qq| AND h.itime::date <= | . conv_dateq($form->{todate})                                                            if $form->{todate};
1083   if ($form->{mitarbeiter} =~ m/^\d+$/) {
1084     $restriction  .= qq| AND employee_id = |    . $form->{mitarbeiter};
1085   } elsif ($form->{mitarbeiter}) {
1086     $restriction  .= qq| AND employee_id = (SELECT id FROM employee WHERE name ILIKE | . $dbh->quote('%' . $form->{mitarbeiter} . '%') . qq|)|;
1087   }
1088
1089   my $snumbers_where = '';
1090   my $snumbers_value;
1091   if ($form->{'searchid'}) {
1092     $snumbers_where = ' WHERE snumbers = ?';
1093     $snumbers_value = $searchNo{$form->{'what2search'}} . '_' . $form->{'searchid'};
1094   } else {
1095     $snumbers_where = ' WHERE snumbers ~ ?';
1096     $snumbers_value = '^' . $searchNo{$form->{'what2search'}};
1097   }
1098   my $query = qq|SELECT trans_id AS id FROM history_erp $snumbers_where|;
1099
1100   my @ids    = grep { $_ * 1 } selectall_array_query($form, $dbh, $query, $snumbers_value);
1101   my $daten .= shift @ids;
1102   if (scalar(@ids) > 0 ) {
1103     $daten  .= ' OR trans_id IN (' . join(',', @ids) . ')';
1104   }
1105   my ($sort, $sortby) = split(/\-\-/, $form->{order});
1106   $sort =~ s/.*\.(.*)$/$1/;
1107
1108   setup_am_show_am_history_action_bar();
1109
1110   $form->{title} = $locale->text("History Search");
1111   $form->header();
1112
1113   print $form->parse_html_template("common/show_history",
1114                                    { "DATEN"          => $form->get_history($dbh, $daten, $restriction, $form->{order}),
1115                                      "SUCCESS"        => ($form->get_history($dbh, $daten, $restriction, $form->{order}) ne "0"),
1116                                      "NONEWWINDOW"    => 1,
1117                                      uc($sort)        => 1,
1118                                      uc($sort) . "BY" => $sortby,
1119                                      'callback'       => $callback,
1120                                    });
1121   $dbh->disconnect();
1122
1123   $main::lxdebug->leave_sub();
1124 }
1125
1126 sub add_tax {
1127   $main::lxdebug->enter_sub();
1128
1129   my $form     = $main::form;
1130   my $locale   = $main::locale;
1131
1132   $main::auth->assert('config');
1133
1134   $form->{title} =  $locale->text('Add');
1135
1136   $form->{callback} ||= "am.pl?action=add_tax";
1137
1138   _get_taxaccount_selection();
1139
1140   $form->{asset}      = 1;
1141   $form->{liability}  = 1;
1142   $form->{equity}     = 1;
1143   $form->{revenue}    = 1;
1144   $form->{expense}    = 1;
1145   $form->{costs}      = 1;
1146
1147   setup_am_edit_tax_action_bar();
1148   $form->header();
1149
1150   my $parameters_ref = {
1151     LANGUAGES => SL::DB::Manager::Language->get_all_sorted,
1152   };
1153
1154   # Ausgabe des Templates
1155   print($form->parse_html_template('am/edit_tax', $parameters_ref));
1156
1157   $main::lxdebug->leave_sub();
1158 }
1159
1160 sub edit_tax {
1161   $main::lxdebug->enter_sub();
1162
1163   my $form     = $main::form;
1164   my %myconfig = %main::myconfig;
1165   my $locale   = $main::locale;
1166
1167   $main::auth->assert('config');
1168
1169   $form->{title} =  $locale->text('Edit');
1170
1171   AM->get_tax(\%myconfig, \%$form);
1172
1173   _get_taxaccount_selection();
1174
1175   $form->{asset}      = $form->{chart_categories} =~ 'A' ? 1 : 0;
1176   $form->{liability}  = $form->{chart_categories} =~ 'L' ? 1 : 0;
1177   $form->{equity}     = $form->{chart_categories} =~ 'Q' ? 1 : 0;
1178   $form->{revenue}    = $form->{chart_categories} =~ 'I' ? 1 : 0;
1179   $form->{expense}    = $form->{chart_categories} =~ 'E' ? 1 : 0;
1180   $form->{costs}      = $form->{chart_categories} =~ 'C' ? 1 : 0;
1181
1182   $form->{rate} = $form->format_amount(\%myconfig, $form->{rate}, 2);
1183
1184   setup_am_edit_tax_action_bar();
1185   $form->header();
1186
1187   my $parameters_ref = {
1188     LANGUAGES => SL::DB::Manager::Language->get_all_sorted,
1189     TAX       => SL::DB::Manager::Tax->find_by(id => $form->{id}),
1190   };
1191
1192   # Ausgabe des Templates
1193   print($form->parse_html_template('am/edit_tax', $parameters_ref));
1194
1195   $main::lxdebug->leave_sub();
1196 }
1197
1198 sub list_tax {
1199   $main::lxdebug->enter_sub();
1200
1201   my $form     = $main::form;
1202   my %myconfig = %main::myconfig;
1203   my $locale   = $main::locale;
1204
1205   $main::auth->assert('config');
1206
1207   AM->taxes(\%myconfig, \%$form);
1208
1209   map { $_->{rate} = $form->format_amount(\%myconfig, $_->{rate}, 2) } @{ $form->{TAX} };
1210
1211   $form->{callback} = build_std_url('action=list_tax');
1212
1213   $form->{title} = $locale->text('Tax-O-Matic');
1214
1215   setup_am_list_tax_action_bar();
1216   $form->header();
1217
1218   # Ausgabe des Templates
1219   print($form->parse_html_template('am/list_tax'));
1220
1221   $main::lxdebug->leave_sub();
1222 }
1223
1224 sub _get_taxaccount_selection{
1225   $main::lxdebug->enter_sub();
1226
1227   my $form     = $main::form;
1228   my %myconfig = %main::myconfig;
1229
1230   $main::auth->assert('config');
1231
1232   AM->get_tax_accounts(\%myconfig, \%$form);
1233
1234   map { $_->{selected} = $form->{chart_id} == $_->{id} } @{ $form->{ACCOUNTS} };
1235
1236   $main::lxdebug->leave_sub();
1237 }
1238
1239 sub save_tax {
1240   $main::lxdebug->enter_sub();
1241
1242   my $form     = $main::form;
1243   my %myconfig = %main::myconfig;
1244   my $locale   = $main::locale;
1245
1246   $main::auth->assert('config');
1247
1248   $form->error($locale->text('Taxkey  missing!')) unless length($form->{taxkey}) != 0;
1249   $form->error($locale->text('Taxdescription  missing!')) unless length($form->{taxdescription}) != 0;
1250   $form->error($locale->text('Taxrate missing!')) unless length($form->{rate}) != 0;
1251
1252   $form->{rate} = $form->parse_amount(\%myconfig, $form->{rate});
1253
1254   if ($form->{taxkey} == 0 and $form->{rate} > 0) {
1255     $form->error($locale->text('Taxkey 0 is reserved for rate 0'));
1256   }
1257
1258   if ( $form->{rate} < 0 || $form->{rate} >= 100 ) {
1259     $form->error($locale->text('Tax Percent is a number between 0 and 100'));
1260   }
1261
1262   if ( $form->{rate} <= 0.99 && $form->{rate} > 0 ) {
1263     $form->error($locale->text('Tax Percent is a number between 0 and 100'));
1264   }
1265
1266   my @translation_keys  =  grep { $_ =~ '^translation_\d+' } keys %$form;
1267   $form->{translations} = { map { $_ =~ '^translation_(\d+)'; $1 => $form->{$_} } @translation_keys };
1268
1269   AM->save_tax(\%myconfig, \%$form);
1270   $form->redirect($locale->text('Tax saved!'));
1271
1272   $main::lxdebug->leave_sub();
1273 }
1274
1275 sub delete_tax {
1276   $main::lxdebug->enter_sub();
1277
1278   my $form     = $main::form;
1279   my %myconfig = %main::myconfig;
1280   my $locale   = $main::locale;
1281
1282   $main::auth->assert('config');
1283
1284   AM->delete_tax(\%myconfig, \%$form);
1285   $form->redirect($locale->text('Tax deleted!'));
1286
1287   $main::lxdebug->leave_sub();
1288 }
1289
1290 sub add_warehouse {
1291   $main::lxdebug->enter_sub();
1292
1293   my $form     = $main::form;
1294   my $locale   = $main::locale;
1295
1296   $main::auth->assert('config');
1297
1298   $form->{title}      = $locale->text('Add Warehouse');
1299   $form->{callback} ||= build_std_url('action=add_warehouse');
1300
1301   setup_am_edit_warehouse_action_bar();
1302
1303   $form->header();
1304   print $form->parse_html_template('am/edit_warehouse');
1305
1306   $main::lxdebug->leave_sub();
1307 }
1308
1309 sub edit_warehouse {
1310   $main::lxdebug->enter_sub();
1311
1312   my $form     = $main::form;
1313   my %myconfig = %main::myconfig;
1314   my $locale   = $main::locale;
1315
1316   $main::auth->assert('config');
1317
1318   AM->get_warehouse(\%myconfig, $form);
1319
1320   $form->get_lists('employees' => 'EMPLOYEES');
1321
1322   $form->{title}      = $locale->text('Edit Warehouse');
1323   $form->{callback} ||= build_std_url('action=list_warehouses');
1324
1325   setup_am_edit_warehouse_action_bar(id => $::form->{id}, in_use => any { $_->{in_use} } @{ $::form->{BINS} });
1326
1327   $form->header();
1328   print $form->parse_html_template('am/edit_warehouse');
1329
1330   $main::lxdebug->leave_sub();
1331 }
1332
1333 sub edit_bins {
1334   $::auth->assert('config');
1335
1336   AM->get_warehouse(\%::myconfig, $::form);
1337
1338   $::form->{title}      = $::locale->text('Edit Bins for Warehouse \'#1\'', $::form->{description});
1339   $::form->{callback} ||= build_std_url('action=list_warehouses');
1340
1341   setup_am_edit_bins_action_bar(id => $::form->{id});
1342
1343   $::form->header;
1344   print $::form->parse_html_template('am/edit_bins');
1345 }
1346
1347 sub list_warehouses {
1348   $main::lxdebug->enter_sub();
1349
1350   my $form     = $main::form;
1351   my %myconfig = %main::myconfig;
1352   my $locale   = $main::locale;
1353
1354   $main::auth->assert('config');
1355
1356   AM->get_all_warehouses(\%myconfig, $form);
1357
1358   $form->{callback} = build_std_url('action=list_warehouses');
1359   $form->{title}    = $locale->text('Warehouses');
1360   $form->{url_base} = build_std_url('callback');
1361
1362   setup_am_list_warehouses_action_bar();
1363
1364   $form->header();
1365   print $form->parse_html_template('am/list_warehouses');
1366
1367   $main::lxdebug->leave_sub();
1368 }
1369
1370 sub save_warehouse {
1371   $main::lxdebug->enter_sub();
1372
1373   my $form     = $main::form;
1374   my %myconfig = %main::myconfig;
1375   my $locale   = $main::locale;
1376
1377   $main::auth->assert('config');
1378
1379   $form->isblank("description", $locale->text('Description missing!'));
1380
1381   $form->{number_of_new_bins} = $form->parse_amount(\%myconfig, $form->{number_of_new_bins});
1382
1383   AM->save_warehouse(\%myconfig, $form);
1384
1385   $form->{callback} .= '&saved_message=' . E($locale->text('Warehouse saved.')) if ($form->{callback});
1386
1387   $form->redirect($locale->text('Warehouse saved.'));
1388
1389   $main::lxdebug->leave_sub();
1390 }
1391
1392 sub delete_warehouse {
1393   $main::lxdebug->enter_sub();
1394
1395   my $form     = $main::form;
1396   my %myconfig = %main::myconfig;
1397   my $locale   = $main::locale;
1398
1399   $main::auth->assert('config');
1400
1401   if (AM->delete_warehouse(\%myconfig, $form)) {
1402     $form->{callback} .= '&saved_message=' . E($locale->text('Warehouse deleted.')) if ($form->{callback});
1403     $form->redirect($locale->text('Warehouse deleted.'));
1404
1405   } else {
1406     $form->error($locale->text('The warehouse could not be deleted because it has already been used.'));
1407   }
1408
1409   $main::lxdebug->leave_sub();
1410 }
1411
1412 sub save_bin {
1413   $main::lxdebug->enter_sub();
1414
1415   my $form     = $main::form;
1416   my %myconfig = %main::myconfig;
1417   my $locale   = $main::locale;
1418
1419   $main::auth->assert('config');
1420
1421   AM->save_bins(\%myconfig, $form);
1422
1423   $form->{callback} .= '&saved_message=' . E($locale->text('Bins saved.')) if ($form->{callback});
1424
1425   $form->redirect($locale->text('Bins saved.'));
1426
1427   $main::lxdebug->leave_sub();
1428 }
1429
1430 sub setup_am_config_action_bar {
1431   my %params = @_;
1432
1433   for my $bar ($::request->layout->get('actionbar')) {
1434     $bar->add(
1435       action => [
1436         t8('Save'),
1437         submit    => [ '#form', { action => "save_preferences" } ],
1438         accesskey => 'enter',
1439       ],
1440     );
1441   }
1442 }
1443
1444 sub setup_am_edit_account_action_bar {
1445   my %params = @_;
1446
1447   for my $bar ($::request->layout->get('actionbar')) {
1448     $bar->add(
1449       combobox => [
1450         action => [
1451           t8('Save'),
1452           submit    => [ '#form', { action => "save_account" } ],
1453           disabled  => $::form->{id} && !$::form->{orphaned} ? t8('The object is in use and cannot be changed.')
1454                      :                                         undef,
1455           accesskey => 'enter',
1456         ],
1457
1458         action => [
1459           t8('Save as new'),
1460           submit   => [ '#form', { action => "save_as_new_account" } ],
1461           disabled => !$::form->{id} ? t8('The object has not been saved yet.') : undef,
1462         ],
1463       ],
1464
1465       action => [
1466         t8('Delete'),
1467         submit   => [ '#form', { action => "delete_account" } ],
1468         disabled => !$::form->{id}                         ? t8('The object has not been saved yet.')
1469                   :  $::form->{id} && !$::form->{orphaned} ? t8('The object is in use and cannot be deleted.')
1470                   :                                          undef,
1471         confirm  => t8('Do you really want to delete this object?'),
1472       ],
1473     );
1474   }
1475 }
1476
1477 sub setup_am_list_tax_action_bar {
1478   my %params = @_;
1479
1480   for my $bar ($::request->layout->get('actionbar')) {
1481     $bar->add(
1482       link => [
1483         t8('Add'),
1484         link => 'am.pl?action=add_tax',
1485       ],
1486     );
1487   }
1488 }
1489
1490 sub setup_am_edit_tax_action_bar {
1491   my %params = @_;
1492
1493   for my $bar ($::request->layout->get('actionbar')) {
1494     $bar->add(
1495       action => [
1496         t8('Save'),
1497         submit    => [ '#form', { action => "save_tax" } ],
1498         accesskey => 'enter',
1499       ],
1500
1501       action => [
1502         t8('Delete'),
1503         submit   => [ '#form', { action => "delete_tax" } ],
1504         disabled => !$::form->{id}                                      ? t8('The object has not been saved yet.')
1505                   : !$::form->{orphaned} || $::form->{tax_already_used} ? t8('The object is in use and cannot be deleted.')
1506                   :                                                       undef,
1507         confirm  => t8('Do you really want to delete this object?'),
1508       ],
1509     );
1510   }
1511 }
1512
1513 sub setup_am_add_unit_action_bar {
1514   my %params = @_;
1515
1516   for my $bar ($::request->layout->get('actionbar')) {
1517     $bar->add(
1518       action => [
1519         t8('Save'),
1520         submit    => [ '#form', { action => "create_unit" } ],
1521         accesskey => 'enter',
1522       ],
1523
1524       'separator',
1525
1526       link => [
1527         t8('Back'),
1528         link => 'am.pl?action=edit_units',
1529       ],
1530     );
1531   }
1532 }
1533
1534 sub setup_am_edit_units_action_bar {
1535   my %params = @_;
1536
1537   for my $bar ($::request->layout->get('actionbar')) {
1538     $bar->add(
1539       action => [
1540         t8('Save'),
1541         submit    => [ '#form', { action => "save_unit" } ],
1542         accesskey => 'enter',
1543       ],
1544
1545       'separator',
1546
1547       link => [
1548         t8('Add'),
1549         link => 'am.pl?action=add_unit',
1550       ],
1551     );
1552   }
1553 }
1554
1555 sub setup_am_list_warehouses_action_bar {
1556   my %params = @_;
1557
1558   for my $bar ($::request->layout->get('actionbar')) {
1559     $bar->add(
1560       link => [
1561         t8('Add'),
1562         link      => 'am.pl?action=add&type=warehouse&callback=' . E($::form->{callback}),
1563         accesskey => 'enter',
1564       ],
1565     );
1566   }
1567 }
1568
1569 sub setup_am_edit_warehouse_action_bar {
1570   my %params = @_;
1571
1572   for my $bar ($::request->layout->get('actionbar')) {
1573     $bar->add(
1574       action => [
1575         t8('Save'),
1576         submit    => [ '#form', { action => 'save_warehouse' } ],
1577         accesskey => 'enter',
1578       ],
1579
1580       action => [
1581         t8('Delete'),
1582         submit   => [ '#form', { action => 'delete_warehouse' } ],
1583         disabled => !$params{id}    ? t8('The object has not been saved yet.')
1584                   : $params{in_use} ? t8('The object is in use and cannot be deleted.')
1585                   :                   undef,
1586         confirm  => t8('Do you really want to delete this object?'),
1587       ],
1588
1589       'separator',
1590
1591       link => [
1592         t8('Bins'),
1593         link    => 'am.pl?action=edit_bins&id=' . E($params{id}),
1594         only_if => $params{id},
1595       ],
1596
1597       link => [
1598         t8('Abort'),
1599         link => $::form->{callback} || 'am.pl?action=list_warehouses',
1600       ],
1601     );
1602   }
1603 }
1604
1605 sub setup_am_edit_bins_action_bar {
1606   my %params = @_;
1607
1608   for my $bar ($::request->layout->get('actionbar')) {
1609     $bar->add(
1610       action => [
1611         t8('Save'),
1612         submit    => [ '#form', { action => 'save_bin' } ],
1613         accesskey => 'enter',
1614       ],
1615
1616       'separator',
1617
1618       link => [
1619         t8('Abort'),
1620         link => 'am.pl?action=edit_warehouse&id=' . E($params{id}),
1621       ],
1622     );
1623   }
1624 }
1625
1626 sub setup_am_audit_control_action_bar {
1627   my %params = @_;
1628
1629   for my $bar ($::request->layout->get('actionbar')) {
1630     $bar->add(
1631       action => [
1632         t8('Save'),
1633         submit    => [ '#form', { action => 'doclose' } ],
1634         accesskey => 'enter',
1635       ],
1636     );
1637   }
1638 }
1639
1640 sub setup_am_show_history_search_action_bar {
1641   my %params = @_;
1642
1643   for my $bar ($::request->layout->get('actionbar')) {
1644     $bar->add(
1645       action => [
1646         t8('Show'),
1647         submit    => [ '#form' ],
1648         accesskey => 'enter',
1649       ],
1650     );
1651   }
1652 }
1653
1654 sub setup_am_show_am_history_action_bar {
1655   my %params = @_;
1656
1657   for my $bar ($::request->layout->get('actionbar')) {
1658     $bar->add(
1659       action => [
1660         t8('Back'),
1661         call => [ 'kivi.history_back' ],
1662       ],
1663     );
1664   }
1665 }