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