ActionBar: Verwendung bei »System« → »Lager«
[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   $::form->header;
774   print $::form->parse_html_template('am/audit_control');
775
776   $::lxdebug->leave_sub;
777 }
778
779 sub doclose {
780   $main::lxdebug->enter_sub();
781
782   my $form     = $main::form;
783   my %myconfig = %main::myconfig;
784   my $locale   = $main::locale;
785
786   $main::auth->assert('config');
787
788   AM->closebooks(\%myconfig, \%$form);
789
790   if ($form->{closedto}) {
791     $form->redirect(
792                     $locale->text('Books closed up to') . " "
793                       . $locale->date(\%myconfig, $form->{closedto}, 1));
794   } else {
795     $form->redirect($locale->text('Books are open'));
796   }
797
798   $main::lxdebug->leave_sub();
799 }
800
801 sub add_unit {
802   $::auth->assert('config');
803
804   # my $units = AM->retrieve_units(\%::myconfig, $::form, "resolved_");
805   # # AM->units_in_use(\%::myconfig, $::form, $units);
806
807   # $units->{$_}->{BASE_UNIT_DDBOX} = AM->unit_select_data($units, $units->{$_}->{base_unit}, 1) for keys %{$units};
808
809   my @languages = @{ SL::DB::Manager::Language->get_all_sorted };
810
811   my $units = AM->retrieve_units(\%::myconfig, $::form);
812   my $ddbox = AM->unit_select_data($units, undef, 1);
813
814   setup_am_add_unit_action_bar();
815
816   $::form->{title} = $::locale->text("Add unit");
817   $::form->header();
818   print($::form->parse_html_template("am/add_unit", {
819     NEW_BASE_UNIT_DDBOX => $ddbox,
820     LANGUAGES           => \@languages,
821   }));
822 }
823
824 sub edit_units {
825   $main::lxdebug->enter_sub();
826
827   my $form     = $main::form;
828   my %myconfig = %main::myconfig;
829   my $locale   = $main::locale;
830
831   $main::auth->assert('config');
832
833   my $units = AM->retrieve_units(\%myconfig, $form, "resolved_");
834   AM->units_in_use(\%myconfig, $form, $units);
835   map({ $units->{$_}->{"BASE_UNIT_DDBOX"} = AM->unit_select_data($units, $units->{$_}->{"base_unit"}, 1); } keys(%{$units}));
836
837   my @languages = @{ SL::DB::Manager::Language->get_all_sorted };
838
839   my @unit_list = sort({ $a->{"sortkey"} <=> $b->{"sortkey"} } values(%{$units}));
840
841   my $i = 1;
842   foreach (@unit_list) {
843     $_->{"factor"} = $form->format_amount(\%myconfig, $_->{"factor"} * 1) if ($_->{"factor"});
844     $_->{"UNITLANGUAGES"} = [];
845     foreach my $lang (@languages) {
846       push(@{ $_->{"UNITLANGUAGES"} },
847            { "idx"              => $i,
848              "unit"             => $_->{"name"},
849              "language_id"      => $lang->id,
850              "localized"        => $_->{"LANGUAGES"}->{$lang->template_code}->{"localized"},
851              "localized_plural" => $_->{"LANGUAGES"}->{$lang->template_code}->{"localized_plural"},
852            });
853     }
854     $i++;
855   }
856
857   $units = AM->retrieve_units(\%myconfig, $form);
858   my $ddbox = AM->unit_select_data($units, undef, 1);
859
860   setup_am_edit_units_action_bar();
861
862   $form->{"title"} = $locale->text("Edit units");
863   $form->header();
864   print($form->parse_html_template("am/edit_units",
865                                    { "UNITS"               => \@unit_list,
866                                      "NEW_BASE_UNIT_DDBOX" => $ddbox,
867                                      "LANGUAGES"           => \@languages,
868                                    }));
869
870   $main::lxdebug->leave_sub();
871 }
872
873 sub create_unit {
874   $main::lxdebug->enter_sub();
875
876   my $form     = $main::form;
877   my %myconfig = %main::myconfig;
878   my $locale   = $main::locale;
879
880   $main::auth->assert('config');
881
882   $form->isblank("new_name", $locale->text("The name is missing."));
883   my $units = AM->retrieve_units(\%myconfig, $form);
884   my $all_units = AM->retrieve_units(\%myconfig, $form);
885   $form->show_generic_error($locale->text("A unit with this name does already exist.")) if ($all_units->{$form->{"new_name"}});
886
887   my ($base_unit, $factor);
888   if ($form->{"new_base_unit"}) {
889     $form->show_generic_error($locale->text("The base unit does not exist.")) unless (defined($units->{$form->{"new_base_unit"}}));
890
891     $form->isblank("new_factor", $locale->text("The factor is missing."));
892     $factor = $form->parse_amount(\%myconfig, $form->{"new_factor"});
893     $form->show_generic_error($locale->text("The factor is missing.")) unless ($factor);
894     $base_unit = $form->{"new_base_unit"};
895   }
896
897   my @languages;
898   foreach my $lang (@{ SL::DB::Manager::Language->get_all_sorted }) {
899     next unless ($form->{"new_localized_$lang->{id}"} || $form->{"new_localized_plural_$lang->{id}"});
900     push(@languages, { "id"               => $lang->id,
901                        "localized"        => $form->{"new_localized_" . $lang->id},
902                        "localized_plural" => $form->{"new_localized_plural_" . $lang->id},
903          });
904   }
905
906   AM->add_unit(\%myconfig, $form, $form->{"new_name"}, $base_unit, $factor, \@languages);
907
908   flash_later('info', $locale->text("The unit has been added."));
909
910   print $form->redirect_header('am.pl?action=edit_units');
911
912   $main::lxdebug->leave_sub();
913 }
914
915 sub set_unit_languages {
916   $main::lxdebug->enter_sub();
917
918   my $form     = $main::form;
919
920   $main::auth->assert('config');
921
922   my ($unit, $languages, $idx) = @_;
923
924   $unit->{"LANGUAGES"} = [];
925
926   foreach my $lang (@{$languages}) {
927     push(@{ $unit->{"LANGUAGES"} },
928          { "id"               => $lang->id,
929            "localized"        => $form->{"localized_${idx}_" . $lang->id},
930            "localized_plural" => $form->{"localized_plural_${idx}_" . $lang->id},
931          });
932   }
933
934   $main::lxdebug->leave_sub();
935 }
936
937 sub save_unit {
938   $main::lxdebug->enter_sub();
939
940   my $form     = $main::form;
941   my %myconfig = %main::myconfig;
942   my $locale   = $main::locale;
943
944   $main::auth->assert('config');
945
946   my $old_units = AM->retrieve_units(\%myconfig, $form, "resolved_");
947   AM->units_in_use(\%myconfig, $form, $old_units);
948
949   my @languages = @{ SL::DB::Manager::Language->get_all_sorted };
950
951   my $new_units = {};
952   my @delete_units = ();
953   foreach my $i (1..($form->{"rowcount"} * 1)) {
954     my $old_unit = $old_units->{$form->{"old_name_$i"}};
955     if (!$old_unit) {
956       $form->show_generic_error(sprintf($locale->text("The unit in row %d has been deleted in the meantime."), $i));
957     }
958
959     if ($form->{"unchangeable_$i"}) {
960       $new_units->{$form->{"old_name_$i"}} = $old_units->{$form->{"old_name_$i"}};
961       $new_units->{$form->{"old_name_$i"}}->{"unchanged_unit"} = 1;
962       set_unit_languages($new_units->{$form->{"old_name_$i"}}, \@languages, $i);
963       next;
964     }
965
966     if ($old_unit->{"in_use"}) {
967       $form->show_generic_error(sprintf($locale->text("The unit in row %d has been used in the meantime and cannot be changed anymore."), $i));
968     }
969
970     if ($form->{"delete_$i"}) {
971       push(@delete_units, $old_unit->{"name"});
972       next;
973     }
974
975     $form->isblank("name_$i", sprintf($locale->text("The name is missing in row %d."), $i));
976
977     $form->show_generic_error(sprintf($locale->text("The name in row %d has already been used before."), $i)) if ($new_units->{$form->{"name_$i"}});
978     my %h = map({ $_ => $form->{"${_}_$i"} } qw(name base_unit factor old_name));
979     $new_units->{$form->{"name_$i"}} = \%h;
980     $new_units->{$form->{"name_$i"}}->{"row"} = $i;
981     set_unit_languages($new_units->{$form->{"old_name_$i"}}, \@languages, $i);
982   }
983
984   foreach my $unit (values(%{$new_units})) {
985     next unless ($unit->{"old_name"});
986     if ($unit->{"base_unit"}) {
987       $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"}))
988         unless (defined($new_units->{$unit->{"base_unit"}}));
989       $unit->{"factor"} = $form->parse_amount(\%myconfig, $unit->{"factor"});
990       $form->show_generic_error(sprintf($locale->text("The factor is missing in row %d."), $unit->{"row"})) unless ($unit->{"factor"} >= 1.0);
991     } else {
992       $unit->{"base_unit"} = undef;
993       $unit->{"factor"} = undef;
994     }
995   }
996
997   foreach my $unit (values(%{$new_units})) {
998     next if ($unit->{"unchanged_unit"});
999
1000     map({ $_->{"seen"} = 0; } values(%{$new_units}));
1001     my $new_unit = $unit;
1002     while ($new_unit->{"base_unit"}) {
1003       $new_unit->{"seen"} = 1;
1004       $new_unit = $new_units->{$new_unit->{"base_unit"}};
1005       if ($new_unit->{"seen"}) {
1006         $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, " .
1007                                                         "B's base unit is C and C's base unit is A) in row %d."), $unit->{"row"}));
1008       }
1009     }
1010   }
1011
1012   AM->save_units(\%myconfig, $form, $new_units, \@delete_units);
1013
1014   flash_later('info', $locale->text("The units have been saved."));
1015
1016   print $form->redirect_header('am.pl?action=edit_units');
1017
1018   $main::lxdebug->leave_sub();
1019 }
1020
1021 sub show_history_search {
1022   $main::lxdebug->enter_sub();
1023
1024   my $form     = $main::form;
1025   my $locale   = $main::locale;
1026
1027   $main::auth->assert('config');
1028
1029   $form->{title} = $locale->text("History Search");
1030   $form->header();
1031
1032   print $form->parse_html_template("common/search_history");
1033
1034   $main::lxdebug->leave_sub();
1035 }
1036
1037 sub show_am_history {
1038   $main::lxdebug->enter_sub();
1039
1040   my $form     = $main::form;
1041   my %myconfig = %main::myconfig;
1042   my $locale   = $main::locale;
1043
1044   $main::auth->assert('config');
1045
1046   my $callback     = build_std_url(qw(action einschraenkungen fromdate todate mitarbeiter searchid what2search));
1047   $form->{order} ||= 'h.itime--1';
1048
1049   # my %search = ( "Artikelnummer"          => "parts",
1050   #                "Kundennummer"           => "customer",
1051   #                "Lieferantennummer"      => "vendor",
1052   #                "Projektnummer"          => "project",
1053   #                "Auftragsnummer"         => "oe",
1054   #                "Angebotsnummer"         => "oe",
1055   #                "Eingangsrechnungnummer" => "ap",
1056   #                "Ausgangsrechnungnummer" => "ar",
1057   #                "Mahnungsnummer"         => "dunning",
1058   #                "Buchungsnummer"         => "gl",
1059   # );
1060
1061   my %searchNo = ( "Artikelnummer"          => "partnumber",
1062                    "Kundennummer"           => "customernumber",
1063                    "Lieferantennummer"      => "vendornumber",
1064                    "Projektnummer"          => "projectnumber",
1065                    "Auftragsnummer"         => "ordnumber",
1066                    "Angebotsnummer"         => "quonumber",
1067                    "Eingangsrechnungnummer" => "invnumber",
1068                    "Ausgangsrechnungnummer" => "invnumber",
1069                    "Mahnungsnummer"         => "dunning_id",
1070                    "Buchungsnummer"         => "gltransaction"
1071     );
1072
1073   my $dbh = $form->dbconnect(\%myconfig);
1074
1075   my $restriction;
1076   $restriction     = qq| AND (| . join(' OR ', map { " addition = " . $dbh->quote($_) } split(m/\,/, $form->{einschraenkungen})) . qq|)| if $form->{einschraenkungen};
1077   $restriction    .= qq| AND h.itime::date >= | . conv_dateq($form->{fromdate})                                                          if $form->{fromdate};
1078   $restriction    .= qq| AND h.itime::date <= | . conv_dateq($form->{todate})                                                            if $form->{todate};
1079   if ($form->{mitarbeiter} =~ m/^\d+$/) {
1080     $restriction  .= qq| AND employee_id = |    . $form->{mitarbeiter};
1081   } elsif ($form->{mitarbeiter}) {
1082     $restriction  .= qq| AND employee_id = (SELECT id FROM employee WHERE name ILIKE | . $dbh->quote('%' . $form->{mitarbeiter} . '%') . qq|)|;
1083   }
1084
1085   my $snumbers_where = '';
1086   my $snumbers_value;
1087   if ($form->{'searchid'}) {
1088     $snumbers_where = ' WHERE snumbers = ?';
1089     $snumbers_value = $searchNo{$form->{'what2search'}} . '_' . $form->{'searchid'};
1090   } else {
1091     $snumbers_where = ' WHERE snumbers ~ ?';
1092     $snumbers_value = '^' . $searchNo{$form->{'what2search'}};
1093   }
1094   my $query = qq|SELECT trans_id AS id FROM history_erp $snumbers_where|;
1095
1096   my @ids    = grep { $_ * 1 } selectall_array_query($form, $dbh, $query, $snumbers_value);
1097   my $daten .= shift @ids;
1098   if (scalar(@ids) > 0 ) {
1099     $daten  .= ' OR trans_id IN (' . join(',', @ids) . ')';
1100   }
1101   my ($sort, $sortby) = split(/\-\-/, $form->{order});
1102   $sort =~ s/.*\.(.*)$/$1/;
1103
1104   $form->{title} = $locale->text("History Search");
1105   $form->header();
1106
1107   print $form->parse_html_template("common/show_history",
1108                                    { "DATEN"          => $form->get_history($dbh, $daten, $restriction, $form->{order}),
1109                                      "SUCCESS"        => ($form->get_history($dbh, $daten, $restriction, $form->{order}) ne "0"),
1110                                      "NONEWWINDOW"    => 1,
1111                                      uc($sort)        => 1,
1112                                      uc($sort) . "BY" => $sortby,
1113                                      'callback'       => $callback,
1114                                    });
1115   $dbh->disconnect();
1116
1117   $main::lxdebug->leave_sub();
1118 }
1119
1120 sub add_tax {
1121   $main::lxdebug->enter_sub();
1122
1123   my $form     = $main::form;
1124   my $locale   = $main::locale;
1125
1126   $main::auth->assert('config');
1127
1128   $form->{title} =  $locale->text('Add');
1129
1130   $form->{callback} ||= "am.pl?action=add_tax";
1131
1132   _get_taxaccount_selection();
1133
1134   $form->{asset}      = 1;
1135   $form->{liability}  = 1;
1136   $form->{equity}     = 1;
1137   $form->{revenue}    = 1;
1138   $form->{expense}    = 1;
1139   $form->{costs}      = 1;
1140
1141   setup_am_edit_tax_action_bar();
1142   $form->header();
1143
1144   my $parameters_ref = {
1145     LANGUAGES => SL::DB::Manager::Language->get_all_sorted,
1146   };
1147
1148   # Ausgabe des Templates
1149   print($form->parse_html_template('am/edit_tax', $parameters_ref));
1150
1151   $main::lxdebug->leave_sub();
1152 }
1153
1154 sub edit_tax {
1155   $main::lxdebug->enter_sub();
1156
1157   my $form     = $main::form;
1158   my %myconfig = %main::myconfig;
1159   my $locale   = $main::locale;
1160
1161   $main::auth->assert('config');
1162
1163   $form->{title} =  $locale->text('Edit');
1164
1165   AM->get_tax(\%myconfig, \%$form);
1166
1167   _get_taxaccount_selection();
1168
1169   $form->{asset}      = $form->{chart_categories} =~ 'A' ? 1 : 0;
1170   $form->{liability}  = $form->{chart_categories} =~ 'L' ? 1 : 0;
1171   $form->{equity}     = $form->{chart_categories} =~ 'Q' ? 1 : 0;
1172   $form->{revenue}    = $form->{chart_categories} =~ 'I' ? 1 : 0;
1173   $form->{expense}    = $form->{chart_categories} =~ 'E' ? 1 : 0;
1174   $form->{costs}      = $form->{chart_categories} =~ 'C' ? 1 : 0;
1175
1176   $form->{rate} = $form->format_amount(\%myconfig, $form->{rate}, 2);
1177
1178   setup_am_edit_tax_action_bar();
1179   $form->header();
1180
1181   my $parameters_ref = {
1182     LANGUAGES => SL::DB::Manager::Language->get_all_sorted,
1183     TAX       => SL::DB::Manager::Tax->find_by(id => $form->{id}),
1184   };
1185
1186   # Ausgabe des Templates
1187   print($form->parse_html_template('am/edit_tax', $parameters_ref));
1188
1189   $main::lxdebug->leave_sub();
1190 }
1191
1192 sub list_tax {
1193   $main::lxdebug->enter_sub();
1194
1195   my $form     = $main::form;
1196   my %myconfig = %main::myconfig;
1197   my $locale   = $main::locale;
1198
1199   $main::auth->assert('config');
1200
1201   AM->taxes(\%myconfig, \%$form);
1202
1203   map { $_->{rate} = $form->format_amount(\%myconfig, $_->{rate}, 2) } @{ $form->{TAX} };
1204
1205   $form->{callback} = build_std_url('action=list_tax');
1206
1207   $form->{title} = $locale->text('Tax-O-Matic');
1208
1209   setup_am_list_tax_action_bar();
1210   $form->header();
1211
1212   # Ausgabe des Templates
1213   print($form->parse_html_template('am/list_tax'));
1214
1215   $main::lxdebug->leave_sub();
1216 }
1217
1218 sub _get_taxaccount_selection{
1219   $main::lxdebug->enter_sub();
1220
1221   my $form     = $main::form;
1222   my %myconfig = %main::myconfig;
1223
1224   $main::auth->assert('config');
1225
1226   AM->get_tax_accounts(\%myconfig, \%$form);
1227
1228   map { $_->{selected} = $form->{chart_id} == $_->{id} } @{ $form->{ACCOUNTS} };
1229
1230   $main::lxdebug->leave_sub();
1231 }
1232
1233 sub save_tax {
1234   $main::lxdebug->enter_sub();
1235
1236   my $form     = $main::form;
1237   my %myconfig = %main::myconfig;
1238   my $locale   = $main::locale;
1239
1240   $main::auth->assert('config');
1241
1242   $form->error($locale->text('Taxkey  missing!')) unless length($form->{taxkey}) != 0;
1243   $form->error($locale->text('Taxdescription  missing!')) unless length($form->{taxdescription}) != 0;
1244   $form->error($locale->text('Taxrate missing!')) unless length($form->{rate}) != 0;
1245
1246   $form->{rate} = $form->parse_amount(\%myconfig, $form->{rate});
1247
1248   if ($form->{taxkey} == 0 and $form->{rate} > 0) {
1249     $form->error($locale->text('Taxkey 0 is reserved for rate 0'));
1250   }
1251
1252   if ( $form->{rate} < 0 || $form->{rate} >= 100 ) {
1253     $form->error($locale->text('Tax Percent is a number between 0 and 100'));
1254   }
1255
1256   if ( $form->{rate} <= 0.99 && $form->{rate} > 0 ) {
1257     $form->error($locale->text('Tax Percent is a number between 0 and 100'));
1258   }
1259
1260   my @translation_keys  =  grep { $_ =~ '^translation_\d+' } keys %$form;
1261   $form->{translations} = { map { $_ =~ '^translation_(\d+)'; $1 => $form->{$_} } @translation_keys };
1262
1263   AM->save_tax(\%myconfig, \%$form);
1264   $form->redirect($locale->text('Tax saved!'));
1265
1266   $main::lxdebug->leave_sub();
1267 }
1268
1269 sub delete_tax {
1270   $main::lxdebug->enter_sub();
1271
1272   my $form     = $main::form;
1273   my %myconfig = %main::myconfig;
1274   my $locale   = $main::locale;
1275
1276   $main::auth->assert('config');
1277
1278   AM->delete_tax(\%myconfig, \%$form);
1279   $form->redirect($locale->text('Tax deleted!'));
1280
1281   $main::lxdebug->leave_sub();
1282 }
1283
1284 sub add_warehouse {
1285   $main::lxdebug->enter_sub();
1286
1287   my $form     = $main::form;
1288   my $locale   = $main::locale;
1289
1290   $main::auth->assert('config');
1291
1292   $form->{title}      = $locale->text('Add Warehouse');
1293   $form->{callback} ||= build_std_url('action=add_warehouse');
1294
1295   setup_am_edit_warehouse_action_bar();
1296
1297   $form->header();
1298   print $form->parse_html_template('am/edit_warehouse');
1299
1300   $main::lxdebug->leave_sub();
1301 }
1302
1303 sub edit_warehouse {
1304   $main::lxdebug->enter_sub();
1305
1306   my $form     = $main::form;
1307   my %myconfig = %main::myconfig;
1308   my $locale   = $main::locale;
1309
1310   $main::auth->assert('config');
1311
1312   AM->get_warehouse(\%myconfig, $form);
1313
1314   $form->get_lists('employees' => 'EMPLOYEES');
1315
1316   $form->{title}      = $locale->text('Edit Warehouse');
1317   $form->{callback} ||= build_std_url('action=list_warehouses');
1318
1319   setup_am_edit_warehouse_action_bar(id => $::form->{id}, in_use => any { $_->{in_use} } @{ $::form->{BINS} });
1320
1321   $form->header();
1322   print $form->parse_html_template('am/edit_warehouse');
1323
1324   $main::lxdebug->leave_sub();
1325 }
1326
1327 sub edit_bins {
1328   $::auth->assert('config');
1329
1330   AM->get_warehouse(\%::myconfig, $::form);
1331
1332   $::form->{title}      = $::locale->text('Edit Bins for Warehouse \'#1\'', $::form->{description});
1333   $::form->{callback} ||= build_std_url('action=list_warehouses');
1334
1335   setup_am_edit_bins_action_bar(id => $::form->{id});
1336
1337   $::form->header;
1338   print $::form->parse_html_template('am/edit_bins');
1339 }
1340
1341 sub list_warehouses {
1342   $main::lxdebug->enter_sub();
1343
1344   my $form     = $main::form;
1345   my %myconfig = %main::myconfig;
1346   my $locale   = $main::locale;
1347
1348   $main::auth->assert('config');
1349
1350   AM->get_all_warehouses(\%myconfig, $form);
1351
1352   $form->{callback} = build_std_url('action=list_warehouses');
1353   $form->{title}    = $locale->text('Warehouses');
1354   $form->{url_base} = build_std_url('callback');
1355
1356   setup_am_list_warehouses_action_bar();
1357
1358   $form->header();
1359   print $form->parse_html_template('am/list_warehouses');
1360
1361   $main::lxdebug->leave_sub();
1362 }
1363
1364 sub save_warehouse {
1365   $main::lxdebug->enter_sub();
1366
1367   my $form     = $main::form;
1368   my %myconfig = %main::myconfig;
1369   my $locale   = $main::locale;
1370
1371   $main::auth->assert('config');
1372
1373   $form->isblank("description", $locale->text('Description missing!'));
1374
1375   $form->{number_of_new_bins} = $form->parse_amount(\%myconfig, $form->{number_of_new_bins});
1376
1377   AM->save_warehouse(\%myconfig, $form);
1378
1379   $form->{callback} .= '&saved_message=' . E($locale->text('Warehouse saved.')) if ($form->{callback});
1380
1381   $form->redirect($locale->text('Warehouse saved.'));
1382
1383   $main::lxdebug->leave_sub();
1384 }
1385
1386 sub delete_warehouse {
1387   $main::lxdebug->enter_sub();
1388
1389   my $form     = $main::form;
1390   my %myconfig = %main::myconfig;
1391   my $locale   = $main::locale;
1392
1393   $main::auth->assert('config');
1394
1395   if (AM->delete_warehouse(\%myconfig, $form)) {
1396     $form->{callback} .= '&saved_message=' . E($locale->text('Warehouse deleted.')) if ($form->{callback});
1397     $form->redirect($locale->text('Warehouse deleted.'));
1398
1399   } else {
1400     $form->error($locale->text('The warehouse could not be deleted because it has already been used.'));
1401   }
1402
1403   $main::lxdebug->leave_sub();
1404 }
1405
1406 sub save_bin {
1407   $main::lxdebug->enter_sub();
1408
1409   my $form     = $main::form;
1410   my %myconfig = %main::myconfig;
1411   my $locale   = $main::locale;
1412
1413   $main::auth->assert('config');
1414
1415   AM->save_bins(\%myconfig, $form);
1416
1417   $form->{callback} .= '&saved_message=' . E($locale->text('Bins saved.')) if ($form->{callback});
1418
1419   $form->redirect($locale->text('Bins saved.'));
1420
1421   $main::lxdebug->leave_sub();
1422 }
1423
1424 sub setup_am_config_action_bar {
1425   my %params = @_;
1426
1427   for my $bar ($::request->layout->get('actionbar')) {
1428     $bar->add(
1429       action => [
1430         t8('Save'),
1431         submit    => [ '#form', { action => "save_preferences" } ],
1432         accesskey => 'enter',
1433       ],
1434     );
1435   }
1436 }
1437
1438 sub setup_am_edit_account_action_bar {
1439   my %params = @_;
1440
1441   for my $bar ($::request->layout->get('actionbar')) {
1442     $bar->add(
1443       combobox => [
1444         action => [
1445           t8('Save'),
1446           submit    => [ '#form', { action => "save_account" } ],
1447           disabled  => $::form->{id} && !$::form->{orphaned} ? t8('The object is in use and cannot be changed.')
1448                      :                                         undef,
1449           accesskey => 'enter',
1450         ],
1451
1452         action => [
1453           t8('Save as new'),
1454           submit   => [ '#form', { action => "save_as_new_account" } ],
1455           disabled => !$::form->{id} ? t8('The object has not been saved yet.') : undef,
1456         ],
1457       ],
1458
1459       action => [
1460         t8('Delete'),
1461         submit   => [ '#form', { action => "delete_account" } ],
1462         disabled => !$::form->{id}                         ? t8('The object has not been saved yet.')
1463                   :  $::form->{id} && !$::form->{orphaned} ? t8('The object is in use and cannot be deleted.')
1464                   :                                          undef,
1465         confirm  => t8('Do you really want to delete this object?'),
1466       ],
1467     );
1468   }
1469 }
1470
1471 sub setup_am_list_tax_action_bar {
1472   my %params = @_;
1473
1474   for my $bar ($::request->layout->get('actionbar')) {
1475     $bar->add(
1476       link => [
1477         t8('Add'),
1478         link => 'am.pl?action=add_tax',
1479       ],
1480     );
1481   }
1482 }
1483
1484 sub setup_am_edit_tax_action_bar {
1485   my %params = @_;
1486
1487   for my $bar ($::request->layout->get('actionbar')) {
1488     $bar->add(
1489       action => [
1490         t8('Save'),
1491         submit    => [ '#form', { action => "save_tax" } ],
1492         accesskey => 'enter',
1493       ],
1494
1495       action => [
1496         t8('Delete'),
1497         submit   => [ '#form', { action => "delete_tax" } ],
1498         disabled => !$::form->{id}                                      ? t8('The object has not been saved yet.')
1499                   : !$::form->{orphaned} || $::form->{tax_already_used} ? t8('The object is in use and cannot be deleted.')
1500                   :                                                       undef,
1501         confirm  => t8('Do you really want to delete this object?'),
1502       ],
1503     );
1504   }
1505 }
1506
1507 sub setup_am_add_unit_action_bar {
1508   my %params = @_;
1509
1510   for my $bar ($::request->layout->get('actionbar')) {
1511     $bar->add(
1512       action => [
1513         t8('Save'),
1514         submit    => [ '#form', { action => "create_unit" } ],
1515         accesskey => 'enter',
1516       ],
1517
1518       'separator',
1519
1520       link => [
1521         t8('Back'),
1522         link => 'am.pl?action=edit_units',
1523       ],
1524     );
1525   }
1526 }
1527
1528 sub setup_am_edit_units_action_bar {
1529   my %params = @_;
1530
1531   for my $bar ($::request->layout->get('actionbar')) {
1532     $bar->add(
1533       action => [
1534         t8('Save'),
1535         submit    => [ '#form', { action => "save_unit" } ],
1536         accesskey => 'enter',
1537       ],
1538
1539       'separator',
1540
1541       link => [
1542         t8('Add'),
1543         link => 'am.pl?action=add_unit',
1544       ],
1545     );
1546   }
1547 }
1548
1549 sub setup_am_list_warehouses_action_bar {
1550   my %params = @_;
1551
1552   for my $bar ($::request->layout->get('actionbar')) {
1553     $bar->add(
1554       link => [
1555         t8('Add'),
1556         link      => 'am.pl?action=add&type=warehouse&callback=' . E($::form->{callback}),
1557         accesskey => 'enter',
1558       ],
1559     );
1560   }
1561 }
1562
1563 sub setup_am_edit_warehouse_action_bar {
1564   my %params = @_;
1565
1566   for my $bar ($::request->layout->get('actionbar')) {
1567     $bar->add(
1568       action => [
1569         t8('Save'),
1570         submit    => [ '#form', { action => 'save_warehouse' } ],
1571         accesskey => 'enter',
1572       ],
1573
1574       action => [
1575         t8('Delete'),
1576         submit   => [ '#form', { action => 'delete_warehouse' } ],
1577         disabled => !$params{id}    ? t8('The object has not been saved yet.')
1578                   : $params{in_use} ? t8('The object is in use and cannot be deleted.')
1579                   :                   undef,
1580         confirm  => t8('Do you really want to delete this object?'),
1581       ],
1582
1583       'separator',
1584
1585       link => [
1586         t8('Bins'),
1587         link    => 'am.pl?action=edit_bins&id=' . E($params{id}),
1588         only_if => $params{id},
1589       ],
1590
1591       link => [
1592         t8('Abort'),
1593         link => $::form->{callback} || 'am.pl?action=list_warehouses',
1594       ],
1595     );
1596   }
1597 }
1598
1599 sub setup_am_edit_bins_action_bar {
1600   my %params = @_;
1601
1602   for my $bar ($::request->layout->get('actionbar')) {
1603     $bar->add(
1604       action => [
1605         t8('Save'),
1606         submit    => [ '#form', { action => 'save_bin' } ],
1607         accesskey => 'enter',
1608       ],
1609
1610       'separator',
1611
1612       link => [
1613         t8('Abort'),
1614         link => 'am.pl?action=edit_warehouse&id=' . E($params{id}),
1615       ],
1616     );
1617   }
1618 }