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