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