Neues Feld Firmensignatur in Mandantenkonfiguration
[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
1041   $form->{full_signature} = $form->create_email_signature();
1042
1043   print $form->parse_html_template('am/config');
1044
1045   $main::lxdebug->leave_sub();
1046 }
1047
1048 sub save_preferences {
1049   $main::lxdebug->enter_sub();
1050
1051   my $form     = $main::form;
1052   my %myconfig = %main::myconfig;
1053   my $locale   = $main::locale;
1054
1055   $form->{stylesheet} = $form->{usestylesheet};
1056
1057   TODO->save_user_config('login' => $form->{login}, %{ $form->{todo_cfg} || { } });
1058
1059   if (AM->save_preferences($form)) {
1060     if ($::auth->can_change_password()
1061         && defined $form->{new_password}
1062         && ($form->{new_password} ne '********')) {
1063       my $verifier = SL::Auth::PasswordPolicy->new;
1064       my $result   = $verifier->verify($form->{new_password});
1065
1066       if ($result != SL::Auth::PasswordPolicy->OK()) {
1067         $form->error($::locale->text('The settings were saved, but the password was not changed.') . ' ' . join(' ', $verifier->errors($result)));
1068       }
1069
1070       $::auth->change_password($form->{login}, $form->{new_password});
1071     }
1072
1073     $form->redirect($locale->text('Preferences saved!'));
1074   }
1075
1076   $form->error($locale->text('Cannot save preferences!'));
1077
1078   $main::lxdebug->leave_sub();
1079 }
1080
1081 sub audit_control {
1082   $::lxdebug->enter_sub;
1083   $::auth->assert('config');
1084
1085   $::form->{title} = $::locale->text('Audit Control');
1086
1087   AM->closedto(\%::myconfig, $::form);
1088
1089   $::form->header;
1090   print $::form->parse_html_template('am/audit_control');
1091
1092   $::lxdebug->leave_sub;
1093 }
1094
1095 sub doclose {
1096   $main::lxdebug->enter_sub();
1097
1098   my $form     = $main::form;
1099   my %myconfig = %main::myconfig;
1100   my $locale   = $main::locale;
1101
1102   $main::auth->assert('config');
1103
1104   AM->closebooks(\%myconfig, \%$form);
1105
1106   if ($form->{closedto}) {
1107     $form->redirect(
1108                     $locale->text('Books closed up to') . " "
1109                       . $locale->date(\%myconfig, $form->{closedto}, 1));
1110   } else {
1111     $form->redirect($locale->text('Books are open'));
1112   }
1113
1114   $main::lxdebug->leave_sub();
1115 }
1116
1117 sub edit_units {
1118   $main::lxdebug->enter_sub();
1119
1120   my $form     = $main::form;
1121   my %myconfig = %main::myconfig;
1122   my $locale   = $main::locale;
1123
1124   $main::auth->assert('config');
1125
1126   my $units = AM->retrieve_units(\%myconfig, $form, "resolved_");
1127   AM->units_in_use(\%myconfig, $form, $units);
1128   map({ $units->{$_}->{"BASE_UNIT_DDBOX"} = AM->unit_select_data($units, $units->{$_}->{"base_unit"}, 1); } keys(%{$units}));
1129
1130   my @languages = AM->language(\%myconfig, $form, 1);
1131
1132   my @unit_list = sort({ $a->{"sortkey"} <=> $b->{"sortkey"} } values(%{$units}));
1133
1134   my $i = 1;
1135   foreach (@unit_list) {
1136     $_->{"factor"} = $form->format_amount(\%myconfig, $_->{"factor"} * 1) if ($_->{"factor"});
1137     $_->{"UNITLANGUAGES"} = [];
1138     foreach my $lang (@languages) {
1139       push(@{ $_->{"UNITLANGUAGES"} },
1140            { "idx" => $i,
1141              "unit" => $_->{"name"},
1142              "language_id" => $lang->{"id"},
1143              "localized" => $_->{"LANGUAGES"}->{$lang->{"template_code"}}->{"localized"},
1144              "localized_plural" => $_->{"LANGUAGES"}->{$lang->{"template_code"}}->{"localized_plural"},
1145            });
1146     }
1147     $i++;
1148   }
1149
1150   $units = AM->retrieve_units(\%myconfig, $form);
1151   my $ddbox = AM->unit_select_data($units, undef, 1);
1152
1153   $form->{"title"} = $locale->text("Add and edit units");
1154   $form->header();
1155   print($form->parse_html_template("am/edit_units",
1156                                    { "UNITS"               => \@unit_list,
1157                                      "NEW_BASE_UNIT_DDBOX" => $ddbox,
1158                                      "LANGUAGES"           => \@languages,
1159                                    }));
1160
1161   $main::lxdebug->leave_sub();
1162 }
1163
1164 sub add_unit {
1165   $main::lxdebug->enter_sub();
1166
1167   my $form     = $main::form;
1168   my %myconfig = %main::myconfig;
1169   my $locale   = $main::locale;
1170
1171   $main::auth->assert('config');
1172
1173   $form->isblank("new_name", $locale->text("The name is missing."));
1174   my $units = AM->retrieve_units(\%myconfig, $form);
1175   my $all_units = AM->retrieve_units(\%myconfig, $form);
1176   $form->show_generic_error($locale->text("A unit with this name does already exist.")) if ($all_units->{$form->{"new_name"}});
1177
1178   my ($base_unit, $factor);
1179   if ($form->{"new_base_unit"}) {
1180     $form->show_generic_error($locale->text("The base unit does not exist.")) unless (defined($units->{$form->{"new_base_unit"}}));
1181
1182     $form->isblank("new_factor", $locale->text("The factor is missing."));
1183     $factor = $form->parse_amount(\%myconfig, $form->{"new_factor"});
1184     $form->show_generic_error($locale->text("The factor is missing.")) unless ($factor);
1185     $base_unit = $form->{"new_base_unit"};
1186   }
1187
1188   my @languages;
1189   foreach my $lang (AM->language(\%myconfig, $form, 1)) {
1190     next unless ($form->{"new_localized_$lang->{id}"} || $form->{"new_localized_plural_$lang->{id}"});
1191     push(@languages, { "id" => $lang->{"id"},
1192                        "localized" => $form->{"new_localized_$lang->{id}"},
1193                        "localized_plural" => $form->{"new_localized_plural_$lang->{id}"},
1194          });
1195   }
1196
1197   AM->add_unit(\%myconfig, $form, $form->{"new_name"}, $base_unit, $factor, \@languages);
1198
1199   $form->{"saved_message"} = $locale->text("The unit has been saved.");
1200
1201   edit_units();
1202
1203   $main::lxdebug->leave_sub();
1204 }
1205
1206 sub set_unit_languages {
1207   $main::lxdebug->enter_sub();
1208
1209   my $form     = $main::form;
1210
1211   $main::auth->assert('config');
1212
1213   my ($unit, $languages, $idx) = @_;
1214
1215   $unit->{"LANGUAGES"} = [];
1216
1217   foreach my $lang (@{$languages}) {
1218     push(@{ $unit->{"LANGUAGES"} },
1219          { "id" => $lang->{"id"},
1220            "localized" => $form->{"localized_${idx}_$lang->{id}"},
1221            "localized_plural" => $form->{"localized_plural_${idx}_$lang->{id}"},
1222          });
1223   }
1224
1225   $main::lxdebug->leave_sub();
1226 }
1227
1228 sub save_unit {
1229   $main::lxdebug->enter_sub();
1230
1231   my $form     = $main::form;
1232   my %myconfig = %main::myconfig;
1233   my $locale   = $main::locale;
1234
1235   $main::auth->assert('config');
1236
1237   my $old_units = AM->retrieve_units(\%myconfig, $form, "resolved_");
1238   AM->units_in_use(\%myconfig, $form, $old_units);
1239
1240   my @languages = AM->language(\%myconfig, $form, 1);
1241
1242   my $new_units = {};
1243   my @delete_units = ();
1244   foreach my $i (1..($form->{"rowcount"} * 1)) {
1245     my $old_unit = $old_units->{$form->{"old_name_$i"}};
1246     if (!$old_unit) {
1247       $form->show_generic_error(sprintf($locale->text("The unit in row %d has been deleted in the meantime."), $i));
1248     }
1249
1250     if ($form->{"unchangeable_$i"}) {
1251       $new_units->{$form->{"old_name_$i"}} = $old_units->{$form->{"old_name_$i"}};
1252       $new_units->{$form->{"old_name_$i"}}->{"unchanged_unit"} = 1;
1253       set_unit_languages($new_units->{$form->{"old_name_$i"}}, \@languages, $i);
1254       next;
1255     }
1256
1257     if ($old_unit->{"in_use"}) {
1258       $form->show_generic_error(sprintf($locale->text("The unit in row %d has been used in the meantime and cannot be changed anymore."), $i));
1259     }
1260
1261     if ($form->{"delete_$i"}) {
1262       push(@delete_units, $old_unit->{"name"});
1263       next;
1264     }
1265
1266     $form->isblank("name_$i", sprintf($locale->text("The name is missing in row %d."), $i));
1267
1268     $form->show_generic_error(sprintf($locale->text("The name in row %d has already been used before."), $i)) if ($new_units->{$form->{"name_$i"}});
1269     my %h = map({ $_ => $form->{"${_}_$i"} } qw(name base_unit factor old_name));
1270     $new_units->{$form->{"name_$i"}} = \%h;
1271     $new_units->{$form->{"name_$i"}}->{"row"} = $i;
1272     set_unit_languages($new_units->{$form->{"old_name_$i"}}, \@languages, $i);
1273   }
1274
1275   foreach my $unit (values(%{$new_units})) {
1276     next unless ($unit->{"old_name"});
1277     if ($unit->{"base_unit"}) {
1278       $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"}))
1279         unless (defined($new_units->{$unit->{"base_unit"}}));
1280       $unit->{"factor"} = $form->parse_amount(\%myconfig, $unit->{"factor"});
1281       $form->show_generic_error(sprintf($locale->text("The factor is missing in row %d."), $unit->{"row"})) unless ($unit->{"factor"} >= 1.0);
1282     } else {
1283       $unit->{"base_unit"} = undef;
1284       $unit->{"factor"} = undef;
1285     }
1286   }
1287
1288   foreach my $unit (values(%{$new_units})) {
1289     next if ($unit->{"unchanged_unit"});
1290
1291     map({ $_->{"seen"} = 0; } values(%{$new_units}));
1292     my $new_unit = $unit;
1293     while ($new_unit->{"base_unit"}) {
1294       $new_unit->{"seen"} = 1;
1295       $new_unit = $new_units->{$new_unit->{"base_unit"}};
1296       if ($new_unit->{"seen"}) {
1297         $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, " .
1298                                                         "B's base unit is C and C's base unit is A) in row %d."), $unit->{"row"}));
1299       }
1300     }
1301   }
1302
1303   AM->save_units(\%myconfig, $form, $new_units, \@delete_units);
1304
1305   $form->{"saved_message"} = $locale->text("The units have been saved.");
1306
1307   edit_units();
1308
1309   $main::lxdebug->leave_sub();
1310 }
1311
1312 sub show_history_search {
1313   $main::lxdebug->enter_sub();
1314
1315   my $form     = $main::form;
1316   my $locale   = $main::locale;
1317
1318   $main::auth->assert('config');
1319
1320   $form->{title} = $locale->text("History Search");
1321   $form->header();
1322
1323   print $form->parse_html_template("common/search_history");
1324
1325   $main::lxdebug->leave_sub();
1326 }
1327
1328 sub show_am_history {
1329   $main::lxdebug->enter_sub();
1330
1331   my $form     = $main::form;
1332   my %myconfig = %main::myconfig;
1333   my $locale   = $main::locale;
1334
1335   $main::auth->assert('config');
1336
1337   my $callback     = build_std_url(qw(action einschraenkungen fromdate todate mitarbeiter searchid what2search));
1338   $form->{order} ||= 'h.itime--1';
1339
1340   my %search = ( "Artikelnummer"          => "parts",
1341                  "Kundennummer"           => "customer",
1342                  "Lieferantennummer"      => "vendor",
1343                  "Projektnummer"          => "project",
1344                  "Buchungsnummer"         => "oe",
1345                  "Eingangsrechnungnummer" => "ap",
1346                  "Ausgangsrechnungnummer" => "ar",
1347                  "Mahnungsnummer"         => "dunning"
1348     );
1349   my %searchNo = ( "Artikelnummer"          => "partnumber",
1350                    "Kundennummer"           => "customernumber",
1351                    "Lieferantennummer"      => "vendornumber",
1352                    "Projektnummer"          => "projectnumber",
1353                    "Buchungsnummer"         => "ordnumber",
1354                    "Eingangsrechnungnummer" => "invnumber",
1355                    "Ausgangsrechnungnummer" => "invnumber",
1356                    "Mahnungsnummer"         => "dunning_id"
1357     );
1358
1359   my $dbh = $form->dbconnect(\%myconfig);
1360
1361   my $restriction;
1362   $restriction     = qq| AND (| . join(' OR ', map { " addition = " . $dbh->quote($_) } split(m/\,/, $form->{einschraenkungen})) . qq|)| if $form->{einschraenkungen};
1363   $restriction    .= qq| AND h.itime::date >= | . conv_dateq($form->{fromdate})                                                          if $form->{fromdate};
1364   $restriction    .= qq| AND h.itime::date <= | . conv_dateq($form->{todate})                                                            if $form->{todate};
1365   if ($form->{mitarbeiter} =~ m/^\d+$/) {
1366     $restriction  .= qq| AND employee_id = |    . $form->{mitarbeiter};
1367   } elsif ($form->{mitarbeiter}) {
1368     $restriction  .= qq| AND employee_id = (SELECT id FROM employee WHERE name ILIKE | . $dbh->quote('%' . $form->{mitarbeiter} . '%') . qq|)|;
1369   }
1370
1371   my $query = qq|SELECT trans_id AS id FROM history_erp | .
1372     (  $form->{'searchid'} ? qq| WHERE snumbers = '|  . $searchNo{$form->{'what2search'}} . qq|_| . $form->{'searchid'} . qq|'|
1373      :                       qq| WHERE snumbers ~ '^| . $searchNo{$form->{'what2search'}} . qq|'|);
1374
1375   my @ids    = grep { $_ * 1 } selectall_array_query($form, $dbh, $query);
1376   my $daten .= shift @ids;
1377   $daten    .= join '', map { " OR trans_id = $_" } @ids;
1378
1379   my ($sort, $sortby) = split(/\-\-/, $form->{order});
1380   $sort =~ s/.*\.(.*)$/$1/;
1381
1382   $form->{title} = $locale->text("History Search");
1383   $form->header();
1384
1385   print $form->parse_html_template("common/show_history",
1386                                    { "DATEN"          => $form->get_history($dbh, $daten, $restriction, $form->{order}),
1387                                      "SUCCESS"        => ($form->get_history($dbh, $daten, $restriction, $form->{order}) ne "0"),
1388                                      "NONEWWINDOW"    => 1,
1389                                      uc($sort)        => 1,
1390                                      uc($sort) . "BY" => $sortby,
1391                                      'callback'       => $callback,
1392                                    });
1393   $dbh->disconnect();
1394
1395   $main::lxdebug->leave_sub();
1396 }
1397
1398 sub add_tax {
1399   $main::lxdebug->enter_sub();
1400
1401   my $form     = $main::form;
1402   my $locale   = $main::locale;
1403
1404   $main::auth->assert('config');
1405
1406   $form->{title} =  $locale->text('Add');
1407
1408   $form->{callback} ||= "am.pl?action=add_tax";
1409
1410   _get_taxaccount_selection();
1411
1412   $form->{asset}      = 1;
1413   $form->{liability}  = 1;
1414   $form->{equity}     = 1;
1415   $form->{revenue}    = 1;
1416   $form->{expense}    = 1;
1417   $form->{costs}      = 1;
1418
1419   $form->header();
1420
1421   my $parameters_ref = {
1422 #    ChartTypeIsAccount         => $ChartTypeIsAccount,
1423     LANGUAGES => SL::DB::Manager::Language->get_all_sorted,
1424   };
1425
1426   # Ausgabe des Templates
1427   print($form->parse_html_template('am/edit_tax', $parameters_ref));
1428
1429   $main::lxdebug->leave_sub();
1430 }
1431
1432 sub edit_tax {
1433   $main::lxdebug->enter_sub();
1434
1435   my $form     = $main::form;
1436   my %myconfig = %main::myconfig;
1437   my $locale   = $main::locale;
1438
1439   $main::auth->assert('config');
1440
1441   $form->{title} =  $locale->text('Edit');
1442
1443   AM->get_tax(\%myconfig, \%$form);
1444
1445   _get_taxaccount_selection();
1446
1447   $form->{asset}      = $form->{chart_categories} =~ 'A' ? 1 : 0;
1448   $form->{liability}  = $form->{chart_categories} =~ 'L' ? 1 : 0;
1449   $form->{equity}     = $form->{chart_categories} =~ 'Q' ? 1 : 0;
1450   $form->{revenue}    = $form->{chart_categories} =~ 'I' ? 1 : 0;
1451   $form->{expense}    = $form->{chart_categories} =~ 'E' ? 1 : 0;
1452   $form->{costs}      = $form->{chart_categories} =~ 'C' ? 1 : 0;
1453
1454   $form->{rate} = $form->format_amount(\%myconfig, $form->{rate}, 2);
1455
1456   $form->header();
1457
1458   my $parameters_ref = {
1459     LANGUAGES => SL::DB::Manager::Language->get_all_sorted,
1460     TAX       => SL::DB::Manager::Tax->find_by(id => $form->{id}),
1461   };
1462
1463   # Ausgabe des Templates
1464   print($form->parse_html_template('am/edit_tax', $parameters_ref));
1465
1466   $main::lxdebug->leave_sub();
1467 }
1468
1469 sub list_tax {
1470   $main::lxdebug->enter_sub();
1471
1472   my $form     = $main::form;
1473   my %myconfig = %main::myconfig;
1474   my $locale   = $main::locale;
1475
1476   $main::auth->assert('config');
1477
1478   AM->taxes(\%myconfig, \%$form);
1479
1480   map { $_->{rate} = $form->format_amount(\%myconfig, $_->{rate}, 2) } @{ $form->{TAX} };
1481
1482   $form->{callback} = build_std_url('action=list_tax');
1483
1484   $form->{title} = $locale->text('Tax-O-Matic');
1485
1486   $form->header();
1487
1488   my $parameters_ref = {
1489   };
1490
1491   # Ausgabe des Templates
1492   print($form->parse_html_template('am/list_tax', $parameters_ref));
1493
1494   $main::lxdebug->leave_sub();
1495 }
1496
1497 sub _get_taxaccount_selection{
1498   $main::lxdebug->enter_sub();
1499
1500   my $form     = $main::form;
1501   my %myconfig = %main::myconfig;
1502
1503   $main::auth->assert('config');
1504
1505   AM->get_tax_accounts(\%myconfig, \%$form);
1506
1507   map { $_->{selected} = $form->{chart_id} == $_->{id} } @{ $form->{ACCOUNTS} };
1508
1509   $main::lxdebug->leave_sub();
1510 }
1511
1512 sub save_tax {
1513   $main::lxdebug->enter_sub();
1514
1515   my $form     = $main::form;
1516   my %myconfig = %main::myconfig;
1517   my $locale   = $main::locale;
1518
1519   $main::auth->assert('config');
1520
1521   $form->error($locale->text('Taxkey  missing!')) unless length($form->{taxkey}) != 0;
1522   $form->error($locale->text('Taxdescription  missing!')) unless length($form->{taxdescription}) != 0;
1523   $form->error($locale->text('Taxrate missing!')) unless length($form->{rate}) != 0;
1524
1525   $form->{rate} = $form->parse_amount(\%myconfig, $form->{rate});
1526
1527   if ($form->{taxkey} == 0 and $form->{rate} > 0) {
1528     $form->error($locale->text('Taxkey 0 is reserved for rate 0'));
1529   }
1530
1531   if ( $form->{rate} < 0 || $form->{rate} >= 100 ) {
1532     $form->error($locale->text('Tax Percent is a number between 0 and 100'));
1533   }
1534
1535   if ( $form->{rate} <= 0.99 && $form->{rate} > 0 ) {
1536     $form->error($locale->text('Tax Percent is a number between 0 and 100'));
1537   }
1538
1539   my @translation_keys  =  grep { $_ =~ '^translation_\d+' } keys %$form;
1540   $form->{translations} = { map { $_ =~ '^translation_(\d+)'; $1 => $form->{$_} } @translation_keys };
1541
1542   AM->save_tax(\%myconfig, \%$form);
1543   $form->redirect($locale->text('Tax saved!'));
1544
1545   $main::lxdebug->leave_sub();
1546 }
1547
1548 sub delete_tax {
1549   $main::lxdebug->enter_sub();
1550
1551   my $form     = $main::form;
1552   my %myconfig = %main::myconfig;
1553   my $locale   = $main::locale;
1554
1555   $main::auth->assert('config');
1556
1557   AM->delete_tax(\%myconfig, \%$form);
1558   $form->redirect($locale->text('Tax deleted!'));
1559
1560   $main::lxdebug->leave_sub();
1561 }
1562
1563 sub add_price_factor {
1564   $main::lxdebug->enter_sub();
1565
1566   my $form     = $main::form;
1567   my $locale   = $main::locale;
1568
1569   $main::auth->assert('config');
1570
1571   $form->{title}      = $locale->text('Add Price Factor');
1572   $form->{callback} ||= build_std_url('action=add_price_factor');
1573
1574   $form->header();
1575   print $form->parse_html_template('am/edit_price_factor');
1576
1577   $main::lxdebug->leave_sub();
1578 }
1579
1580 sub edit_price_factor {
1581   $main::lxdebug->enter_sub();
1582
1583   my $form     = $main::form;
1584   my %myconfig = %main::myconfig;
1585   my $locale   = $main::locale;
1586
1587   $main::auth->assert('config');
1588
1589   $form->{title}      = $locale->text('Edit Price Factor');
1590   $form->{callback} ||= build_std_url('action=add_price_factor');
1591
1592   AM->get_price_factor(\%myconfig, $form);
1593
1594   $form->{factor} = $form->format_amount(\%myconfig, $form->{factor} * 1);
1595
1596   $form->header();
1597   print $form->parse_html_template('am/edit_price_factor');
1598
1599   $main::lxdebug->leave_sub();
1600 }
1601
1602 sub list_price_factors {
1603   $main::lxdebug->enter_sub();
1604
1605   my $form     = $main::form;
1606   my %myconfig = %main::myconfig;
1607   my $locale   = $main::locale;
1608
1609   $main::auth->assert('config');
1610
1611   AM->get_all_price_factors(\%myconfig, \%$form);
1612
1613   foreach my $current (@{ $form->{PRICE_FACTORS} }) {
1614     $current->{factor} = $form->format_amount(\%myconfig, $current->{factor} * 1);
1615   }
1616
1617   $form->{callback} = build_std_url('action=list_price_factors');
1618   $form->{title}    = $locale->text('Price Factors');
1619   $form->{url_base} = build_std_url('callback');
1620
1621   $form->header();
1622   print $form->parse_html_template('am/list_price_factors');
1623
1624   $main::lxdebug->leave_sub();
1625 }
1626
1627 sub save_price_factor {
1628   $main::lxdebug->enter_sub();
1629
1630   my $form     = $main::form;
1631   my %myconfig = %main::myconfig;
1632   my $locale   = $main::locale;
1633
1634   $main::auth->assert('config');
1635
1636   $form->isblank("description", $locale->text('Description missing!'));
1637   $form->isblank("factor", $locale->text('Factor missing!'));
1638
1639   $form->{factor} = $form->parse_amount(\%myconfig, $form->{factor});
1640
1641   AM->save_price_factor(\%myconfig, $form);
1642
1643   $form->{callback} .= '&MESSAGE=' . $form->escape($locale->text('Price factor saved!')) if ($form->{callback});
1644
1645   $form->redirect($locale->text('Price factor saved!'));
1646
1647   $main::lxdebug->leave_sub();
1648 }
1649
1650 sub delete_price_factor {
1651   $main::lxdebug->enter_sub();
1652
1653   my $form     = $main::form;
1654   my %myconfig = %main::myconfig;
1655   my $locale   = $main::locale;
1656
1657   $main::auth->assert('config');
1658
1659   AM->delete_price_factor(\%myconfig, \%$form);
1660
1661   $form->{callback} .= '&MESSAGE=' . $form->escape($locale->text('Price factor deleted!')) if ($form->{callback});
1662
1663   $form->redirect($locale->text('Price factor deleted!'));
1664
1665   $main::lxdebug->leave_sub();
1666 }
1667
1668 sub add_warehouse {
1669   $main::lxdebug->enter_sub();
1670
1671   my $form     = $main::form;
1672   my $locale   = $main::locale;
1673
1674   $main::auth->assert('config');
1675
1676   $form->{title}      = $locale->text('Add Warehouse');
1677   $form->{callback} ||= build_std_url('action=add_warehouse');
1678
1679   $form->header();
1680   print $form->parse_html_template('am/edit_warehouse');
1681
1682   $main::lxdebug->leave_sub();
1683 }
1684
1685 sub edit_warehouse {
1686   $main::lxdebug->enter_sub();
1687
1688   my $form     = $main::form;
1689   my %myconfig = %main::myconfig;
1690   my $locale   = $main::locale;
1691
1692   $main::auth->assert('config');
1693
1694   AM->get_warehouse(\%myconfig, $form);
1695
1696   $form->get_lists('employees' => 'EMPLOYEES');
1697
1698   $form->{title}      = $locale->text('Edit Warehouse');
1699   $form->{callback} ||= build_std_url('action=list_warehouses');
1700
1701   $form->header();
1702   print $form->parse_html_template('am/edit_warehouse');
1703
1704   $main::lxdebug->leave_sub();
1705 }
1706
1707 sub list_warehouses {
1708   $main::lxdebug->enter_sub();
1709
1710   my $form     = $main::form;
1711   my %myconfig = %main::myconfig;
1712   my $locale   = $main::locale;
1713
1714   $main::auth->assert('config');
1715
1716   AM->get_all_warehouses(\%myconfig, $form);
1717
1718   $form->{callback} = build_std_url('action=list_warehouses');
1719   $form->{title}    = $locale->text('Warehouses');
1720   $form->{url_base} = build_std_url('callback');
1721
1722   $form->header();
1723   print $form->parse_html_template('am/list_warehouses');
1724
1725   $main::lxdebug->leave_sub();
1726 }
1727
1728 sub save_warehouse {
1729   $main::lxdebug->enter_sub();
1730
1731   my $form     = $main::form;
1732   my %myconfig = %main::myconfig;
1733   my $locale   = $main::locale;
1734
1735   $main::auth->assert('config');
1736
1737   $form->isblank("description", $locale->text('Description missing!'));
1738
1739   $form->{number_of_new_bins} = $form->parse_amount(\%myconfig, $form->{number_of_new_bins});
1740
1741   AM->save_warehouse(\%myconfig, $form);
1742
1743   $form->{callback} .= '&saved_message=' . E($locale->text('Warehouse saved.')) if ($form->{callback});
1744
1745   $form->redirect($locale->text('Warehouse saved.'));
1746
1747   $main::lxdebug->leave_sub();
1748 }
1749
1750 sub delete_warehouse {
1751   $main::lxdebug->enter_sub();
1752
1753   my $form     = $main::form;
1754   my %myconfig = %main::myconfig;
1755   my $locale   = $main::locale;
1756
1757   $main::auth->assert('config');
1758
1759   if (!$form->{confirmed}) {
1760     $form->{title} = $locale->text('Confirmation');
1761
1762     $form->header();
1763     print $form->parse_html_template('am/confirm_delete_warehouse');
1764     ::end_of_request();
1765   }
1766
1767   if (AM->delete_warehouse(\%myconfig, $form)) {
1768     $form->{callback} .= '&saved_message=' . E($locale->text('Warehouse deleted.')) if ($form->{callback});
1769     $form->redirect($locale->text('Warehouse deleted.'));
1770
1771   } else {
1772     $form->error($locale->text('The warehouse could not be deleted because it has already been used.'));
1773   }
1774
1775   $main::lxdebug->leave_sub();
1776 }
1777
1778 sub save_bin {
1779   $main::lxdebug->enter_sub();
1780
1781   my $form     = $main::form;
1782   my %myconfig = %main::myconfig;
1783   my $locale   = $main::locale;
1784
1785   $main::auth->assert('config');
1786
1787   AM->save_bins(\%myconfig, $form);
1788
1789   $form->{callback} .= '&saved_message=' . E($locale->text('Bins saved.')) if ($form->{callback});
1790
1791   $form->redirect($locale->text('Bins saved.'));
1792
1793   $main::lxdebug->leave_sub();
1794 }