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