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