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