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