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