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