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