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