432eb7b9d248cab92eb2edc8233e472e19e38f7c
[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
664   $myconfig{show_form_details} = 1 unless (defined($myconfig{show_form_details}));
665   $form->{CAN_CHANGE_PASSWORD} = $main::auth->can_change_password();
666   $form->{todo_cfg}            = { TODO->get_user_config('login' => $::myconfig{login}) };
667
668   $::request->{layout}->use_javascript("jquery.multiselect2side.js");
669   $form->{title}               = $locale->text('Edit Preferences for #1', $::myconfig{login});
670
671   setup_am_config_action_bar();
672   $form->header();
673
674   $form->{full_signature} = $form->create_email_signature();
675
676   print $form->parse_html_template('am/config');
677
678   $main::lxdebug->leave_sub();
679 }
680
681 sub save_preferences {
682   $main::lxdebug->enter_sub();
683
684   my $form     = $main::form;
685   my %myconfig = %main::myconfig;
686   my $locale   = $main::locale;
687
688   $form->{stylesheet} = $form->{usestylesheet};
689
690   TODO->save_user_config('login' => $::myconfig{login}, %{ $form->{todo_cfg} || { } });
691
692   if ($form->{quick_search_modules}) {
693     my $user_prefs = SL::Helper::UserPreferences->new( namespace => 'TopQuickSearch',);
694     my $quick_search_modules = join ',', @{$form->{quick_search_modules}};
695     $user_prefs->store('quick_search_modules', $quick_search_modules);
696   }
697   if (AM->save_preferences($form)) {
698     if ($::auth->can_change_password()
699         && defined $form->{new_password}
700         && ($form->{new_password} ne '********')) {
701       my $verifier = SL::Auth::PasswordPolicy->new;
702       my $result   = $verifier->verify($form->{new_password});
703
704       if ($result != SL::Auth::PasswordPolicy->OK()) {
705         $form->error($::locale->text('The settings were saved, but the password was not changed.') . ' ' . join(' ', $verifier->errors($result)));
706       }
707
708       $::auth->change_password($::myconfig{login}, $form->{new_password});
709     }
710
711     $form->redirect($locale->text('Preferences saved!'));
712   }
713
714   $form->error($locale->text('Cannot save preferences!'));
715
716   $main::lxdebug->leave_sub();
717 }
718
719 sub audit_control {
720   $::lxdebug->enter_sub;
721   $::auth->assert('config');
722
723   $::form->{title} = $::locale->text('Audit Control');
724
725   AM->closedto(\%::myconfig, $::form);
726
727   setup_am_audit_control_action_bar();
728
729   $::form->header;
730   print $::form->parse_html_template('am/audit_control');
731
732   $::lxdebug->leave_sub;
733 }
734
735 sub doclose {
736   $main::lxdebug->enter_sub();
737
738   my $form     = $main::form;
739   my %myconfig = %main::myconfig;
740   my $locale   = $main::locale;
741
742   $main::auth->assert('config');
743
744   AM->closebooks(\%myconfig, \%$form);
745
746   if ($form->{closedto}) {
747     $form->redirect(
748                     $locale->text('Books closed up to') . " "
749                       . $locale->date(\%myconfig, $form->{closedto}, 1));
750   } else {
751     $form->redirect($locale->text('Books are open'));
752   }
753
754   $main::lxdebug->leave_sub();
755 }
756
757 sub add_unit {
758   $::auth->assert('config');
759
760   # my $units = AM->retrieve_units(\%::myconfig, $::form, "resolved_");
761   # # AM->units_in_use(\%::myconfig, $::form, $units);
762
763   # $units->{$_}->{BASE_UNIT_DDBOX} = AM->unit_select_data($units, $units->{$_}->{base_unit}, 1) for keys %{$units};
764
765   my @languages = @{ SL::DB::Manager::Language->get_all_sorted };
766
767   my $units = AM->retrieve_units(\%::myconfig, $::form);
768   my $ddbox = AM->unit_select_data($units, undef, 1);
769
770   setup_am_add_unit_action_bar();
771
772   $::form->{title} = $::locale->text("Add unit");
773   $::form->header();
774   print($::form->parse_html_template("am/add_unit", {
775     NEW_BASE_UNIT_DDBOX => $ddbox,
776     LANGUAGES           => \@languages,
777   }));
778 }
779
780 sub edit_units {
781   $main::lxdebug->enter_sub();
782
783   my $form     = $main::form;
784   my %myconfig = %main::myconfig;
785   my $locale   = $main::locale;
786
787   $main::auth->assert('config');
788
789   my $units = AM->retrieve_units(\%myconfig, $form, "resolved_");
790   AM->units_in_use(\%myconfig, $form, $units);
791   map({ $units->{$_}->{"BASE_UNIT_DDBOX"} = AM->unit_select_data($units, $units->{$_}->{"base_unit"}, 1); } keys(%{$units}));
792
793   my @languages = @{ SL::DB::Manager::Language->get_all_sorted };
794
795   my @unit_list = sort({ $a->{"sortkey"} <=> $b->{"sortkey"} } values(%{$units}));
796
797   my $i = 1;
798   foreach (@unit_list) {
799     $_->{"factor"} = $form->format_amount(\%myconfig, $_->{"factor"} * 1) if ($_->{"factor"});
800     $_->{"UNITLANGUAGES"} = [];
801     foreach my $lang (@languages) {
802       push(@{ $_->{"UNITLANGUAGES"} },
803            { "idx"              => $i,
804              "unit"             => $_->{"name"},
805              "language_id"      => $lang->id,
806              "localized"        => $_->{"LANGUAGES"}->{$lang->template_code}->{"localized"},
807              "localized_plural" => $_->{"LANGUAGES"}->{$lang->template_code}->{"localized_plural"},
808            });
809     }
810     $i++;
811   }
812
813   $units = AM->retrieve_units(\%myconfig, $form);
814   my $ddbox = AM->unit_select_data($units, undef, 1);
815
816   setup_am_edit_units_action_bar();
817
818   $form->{"title"} = $locale->text("Edit units");
819   $form->header();
820   print($form->parse_html_template("am/edit_units",
821                                    { "UNITS"               => \@unit_list,
822                                      "NEW_BASE_UNIT_DDBOX" => $ddbox,
823                                      "LANGUAGES"           => \@languages,
824                                    }));
825
826   $main::lxdebug->leave_sub();
827 }
828
829 sub create_unit {
830   $main::lxdebug->enter_sub();
831
832   my $form     = $main::form;
833   my %myconfig = %main::myconfig;
834   my $locale   = $main::locale;
835
836   $main::auth->assert('config');
837
838   $form->isblank("new_name", $locale->text("The name is missing."));
839   my $units = AM->retrieve_units(\%myconfig, $form);
840   my $all_units = AM->retrieve_units(\%myconfig, $form);
841   $form->show_generic_error($locale->text("A unit with this name does already exist.")) if ($all_units->{$form->{"new_name"}});
842
843   my ($base_unit, $factor);
844   if ($form->{"new_base_unit"}) {
845     $form->show_generic_error($locale->text("The base unit does not exist.")) unless (defined($units->{$form->{"new_base_unit"}}));
846
847     $form->isblank("new_factor", $locale->text("The factor is missing."));
848     $factor = $form->parse_amount(\%myconfig, $form->{"new_factor"});
849     $form->show_generic_error($locale->text("The factor is missing.")) unless ($factor);
850     $base_unit = $form->{"new_base_unit"};
851   }
852
853   my @languages;
854   foreach my $lang (@{ SL::DB::Manager::Language->get_all_sorted }) {
855     next unless ($form->{"new_localized_$lang->{id}"} || $form->{"new_localized_plural_$lang->{id}"});
856     push(@languages, { "id"               => $lang->id,
857                        "localized"        => $form->{"new_localized_" . $lang->id},
858                        "localized_plural" => $form->{"new_localized_plural_" . $lang->id},
859          });
860   }
861
862   AM->add_unit(\%myconfig, $form, $form->{"new_name"}, $base_unit, $factor, \@languages);
863
864   flash_later('info', $locale->text("The unit has been added."));
865
866   print $form->redirect_header('am.pl?action=edit_units');
867
868   $main::lxdebug->leave_sub();
869 }
870
871 sub set_unit_languages {
872   $main::lxdebug->enter_sub();
873
874   my $form     = $main::form;
875
876   $main::auth->assert('config');
877
878   my ($unit, $languages, $idx) = @_;
879
880   $unit->{"LANGUAGES"} = [];
881
882   foreach my $lang (@{$languages}) {
883     push(@{ $unit->{"LANGUAGES"} },
884          { "id"               => $lang->id,
885            "localized"        => $form->{"localized_${idx}_" . $lang->id},
886            "localized_plural" => $form->{"localized_plural_${idx}_" . $lang->id},
887          });
888   }
889
890   $main::lxdebug->leave_sub();
891 }
892
893 sub save_unit {
894   $main::lxdebug->enter_sub();
895
896   my $form     = $main::form;
897   my %myconfig = %main::myconfig;
898   my $locale   = $main::locale;
899
900   $main::auth->assert('config');
901
902   my $old_units = AM->retrieve_units(\%myconfig, $form, "resolved_");
903   AM->units_in_use(\%myconfig, $form, $old_units);
904
905   my @languages = @{ SL::DB::Manager::Language->get_all_sorted };
906
907   my $new_units = {};
908   my @delete_units = ();
909   foreach my $i (1..($form->{"rowcount"} * 1)) {
910     my $old_unit = $old_units->{$form->{"old_name_$i"}};
911     if (!$old_unit) {
912       $form->show_generic_error(sprintf($locale->text("The unit in row %d has been deleted in the meantime."), $i));
913     }
914
915     if ($form->{"unchangeable_$i"}) {
916       $new_units->{$form->{"old_name_$i"}} = $old_units->{$form->{"old_name_$i"}};
917       $new_units->{$form->{"old_name_$i"}}->{"unchanged_unit"} = 1;
918       set_unit_languages($new_units->{$form->{"old_name_$i"}}, \@languages, $i);
919       next;
920     }
921
922     if ($old_unit->{"in_use"}) {
923       $form->show_generic_error(sprintf($locale->text("The unit in row %d has been used in the meantime and cannot be changed anymore."), $i));
924     }
925
926     if ($form->{"delete_$i"}) {
927       push(@delete_units, $old_unit->{"name"});
928       next;
929     }
930
931     $form->isblank("name_$i", sprintf($locale->text("The name is missing in row %d."), $i));
932
933     $form->show_generic_error(sprintf($locale->text("The name in row %d has already been used before."), $i)) if ($new_units->{$form->{"name_$i"}});
934     my %h = map({ $_ => $form->{"${_}_$i"} } qw(name base_unit factor old_name));
935     $new_units->{$form->{"name_$i"}} = \%h;
936     $new_units->{$form->{"name_$i"}}->{"row"} = $i;
937     set_unit_languages($new_units->{$form->{"old_name_$i"}}, \@languages, $i);
938   }
939
940   foreach my $unit (values(%{$new_units})) {
941     next unless ($unit->{"old_name"});
942     if ($unit->{"base_unit"}) {
943       $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"}))
944         unless (defined($new_units->{$unit->{"base_unit"}}));
945       $unit->{"factor"} = $form->parse_amount(\%myconfig, $unit->{"factor"});
946       $form->show_generic_error(sprintf($locale->text("The factor is missing in row %d."), $unit->{"row"})) unless ($unit->{"factor"} >= 1.0);
947     } else {
948       $unit->{"base_unit"} = undef;
949       $unit->{"factor"} = undef;
950     }
951   }
952
953   foreach my $unit (values(%{$new_units})) {
954     next if ($unit->{"unchanged_unit"});
955
956     map({ $_->{"seen"} = 0; } values(%{$new_units}));
957     my $new_unit = $unit;
958     while ($new_unit->{"base_unit"}) {
959       $new_unit->{"seen"} = 1;
960       $new_unit = $new_units->{$new_unit->{"base_unit"}};
961       if ($new_unit->{"seen"}) {
962         $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, " .
963                                                         "B's base unit is C and C's base unit is A) in row %d."), $unit->{"row"}));
964       }
965     }
966   }
967
968   AM->save_units(\%myconfig, $form, $new_units, \@delete_units);
969
970   flash_later('info', $locale->text("The units have been saved."));
971
972   print $form->redirect_header('am.pl?action=edit_units');
973
974   $main::lxdebug->leave_sub();
975 }
976
977 sub show_history_search {
978   $main::lxdebug->enter_sub();
979
980   my $form     = $main::form;
981   my $locale   = $main::locale;
982
983   $main::auth->assert('config');
984
985   setup_am_show_history_search_action_bar();
986
987   $form->{title} = $locale->text("History Search");
988   $form->header();
989
990   print $form->parse_html_template("common/search_history");
991
992   $main::lxdebug->leave_sub();
993 }
994
995 sub show_am_history {
996   $main::lxdebug->enter_sub();
997
998   my $form     = $main::form;
999   my %myconfig = %main::myconfig;
1000   my $locale   = $main::locale;
1001
1002   $main::auth->assert('config');
1003
1004   my $callback     = build_std_url(qw(action einschraenkungen fromdate todate mitarbeiter searchid what2search));
1005   $form->{order} ||= 'h.itime--1';
1006
1007   # my %search = ( "Artikelnummer"          => "parts",
1008   #                "Kundennummer"           => "customer",
1009   #                "Lieferantennummer"      => "vendor",
1010   #                "Projektnummer"          => "project",
1011   #                "Auftragsnummer"         => "oe",
1012   #                "Angebotsnummer"         => "oe",
1013   #                "Eingangsrechnungnummer" => "ap",
1014   #                "Ausgangsrechnungnummer" => "ar",
1015   #                "Mahnungsnummer"         => "dunning",
1016   #                "Buchungsnummer"         => "gl",
1017   # );
1018
1019   my %searchNo = ( "Artikelnummer"          => "partnumber",
1020                    "Kundennummer"           => "customernumber",
1021                    "Lieferantennummer"      => "vendornumber",
1022                    "Projektnummer"          => "projectnumber",
1023                    "Auftragsnummer"         => "ordnumber",
1024                    "Angebotsnummer"         => "quonumber",
1025                    "Eingangsrechnungnummer" => "invnumber",
1026                    "Ausgangsrechnungnummer" => "invnumber",
1027                    "Mahnungsnummer"         => "dunning_id",
1028                    "Buchungsnummer"         => "gltransaction"
1029     );
1030
1031   my $dbh = $form->dbconnect(\%myconfig);
1032
1033   my $restriction;
1034   $restriction     = qq| AND (| . join(' OR ', map { " addition = " . $dbh->quote($_) } split(m/\,/, $form->{einschraenkungen})) . qq|)| if $form->{einschraenkungen};
1035   $restriction    .= qq| AND h.itime::date >= | . conv_dateq($form->{fromdate})                                                          if $form->{fromdate};
1036   $restriction    .= qq| AND h.itime::date <= | . conv_dateq($form->{todate})                                                            if $form->{todate};
1037   if ($form->{mitarbeiter} =~ m/^\d+$/) {
1038     $restriction  .= qq| AND employee_id = |    . $form->{mitarbeiter};
1039   } elsif ($form->{mitarbeiter}) {
1040     $restriction  .= qq| AND employee_id = (SELECT id FROM employee WHERE name ILIKE | . $dbh->quote('%' . $form->{mitarbeiter} . '%') . qq|)|;
1041   }
1042
1043   my $snumbers_where = '';
1044   my $snumbers_value;
1045   if ($form->{'searchid'}) {
1046     $snumbers_where = ' WHERE snumbers = ?';
1047     $snumbers_value = $searchNo{$form->{'what2search'}} . '_' . $form->{'searchid'};
1048   } else {
1049     $snumbers_where = ' WHERE snumbers ~ ?';
1050     $snumbers_value = '^' . $searchNo{$form->{'what2search'}};
1051   }
1052   my $query = qq|SELECT trans_id AS id FROM history_erp $snumbers_where|;
1053
1054   my @ids    = grep { $_ * 1 } selectall_array_query($form, $dbh, $query, $snumbers_value);
1055   my $daten .= shift @ids;
1056   if (scalar(@ids) > 0 ) {
1057     $daten  .= ' OR trans_id IN (' . join(',', @ids) . ')';
1058   }
1059   my ($sort, $sortby) = split(/\-\-/, $form->{order});
1060   $sort =~ s/.*\.(.*)$/$1/;
1061
1062   setup_am_show_am_history_action_bar();
1063
1064   $form->{title} = $locale->text("History Search");
1065   $form->header();
1066
1067   print $form->parse_html_template("common/show_history",
1068                                    { "DATEN"          => $form->get_history($dbh, $daten, $restriction, $form->{order}),
1069                                      "SUCCESS"        => ($form->get_history($dbh, $daten, $restriction, $form->{order}) ne "0"),
1070                                      "NONEWWINDOW"    => 1,
1071                                      uc($sort)        => 1,
1072                                      uc($sort) . "BY" => $sortby,
1073                                      'callback'       => $callback,
1074                                    });
1075   $dbh->disconnect();
1076
1077   $main::lxdebug->leave_sub();
1078 }
1079
1080 sub add_tax {
1081   $main::lxdebug->enter_sub();
1082
1083   my $form     = $main::form;
1084   my $locale   = $main::locale;
1085
1086   $main::auth->assert('config');
1087
1088   $form->{title} =  $locale->text('Add');
1089
1090   $form->{callback} ||= "am.pl?action=add_tax";
1091
1092   _get_taxaccount_selection();
1093
1094   $form->{asset}      = 1;
1095   $form->{liability}  = 1;
1096   $form->{equity}     = 1;
1097   $form->{revenue}    = 1;
1098   $form->{expense}    = 1;
1099   $form->{costs}      = 1;
1100
1101   setup_am_edit_tax_action_bar();
1102   $form->header();
1103
1104   my $parameters_ref = {
1105     LANGUAGES => SL::DB::Manager::Language->get_all_sorted,
1106   };
1107
1108   # Ausgabe des Templates
1109   print($form->parse_html_template('am/edit_tax', $parameters_ref));
1110
1111   $main::lxdebug->leave_sub();
1112 }
1113
1114 sub edit_tax {
1115   $main::lxdebug->enter_sub();
1116
1117   my $form     = $main::form;
1118   my %myconfig = %main::myconfig;
1119   my $locale   = $main::locale;
1120
1121   $main::auth->assert('config');
1122
1123   $form->{title} =  $locale->text('Edit');
1124
1125   AM->get_tax(\%myconfig, \%$form);
1126
1127   _get_taxaccount_selection();
1128
1129   $form->{asset}      = $form->{chart_categories} =~ 'A' ? 1 : 0;
1130   $form->{liability}  = $form->{chart_categories} =~ 'L' ? 1 : 0;
1131   $form->{equity}     = $form->{chart_categories} =~ 'Q' ? 1 : 0;
1132   $form->{revenue}    = $form->{chart_categories} =~ 'I' ? 1 : 0;
1133   $form->{expense}    = $form->{chart_categories} =~ 'E' ? 1 : 0;
1134   $form->{costs}      = $form->{chart_categories} =~ 'C' ? 1 : 0;
1135
1136   $form->{rate} = $form->format_amount(\%myconfig, $form->{rate}, 2);
1137
1138   setup_am_edit_tax_action_bar();
1139   $form->header();
1140
1141   my $parameters_ref = {
1142     LANGUAGES => SL::DB::Manager::Language->get_all_sorted,
1143     TAX       => SL::DB::Manager::Tax->find_by(id => $form->{id}),
1144   };
1145
1146   # Ausgabe des Templates
1147   print($form->parse_html_template('am/edit_tax', $parameters_ref));
1148
1149   $main::lxdebug->leave_sub();
1150 }
1151
1152 sub list_tax {
1153   $main::lxdebug->enter_sub();
1154
1155   my $form     = $main::form;
1156   my %myconfig = %main::myconfig;
1157   my $locale   = $main::locale;
1158
1159   $main::auth->assert('config');
1160
1161   AM->taxes(\%myconfig, \%$form);
1162
1163   map { $_->{rate} = $form->format_amount(\%myconfig, $_->{rate}, 2) } @{ $form->{TAX} };
1164
1165   $form->{callback} = build_std_url('action=list_tax');
1166
1167   $form->{title} = $locale->text('Tax-O-Matic');
1168
1169   setup_am_list_tax_action_bar();
1170   $form->header();
1171
1172   # Ausgabe des Templates
1173   print($form->parse_html_template('am/list_tax'));
1174
1175   $main::lxdebug->leave_sub();
1176 }
1177
1178 sub _get_taxaccount_selection{
1179   $main::lxdebug->enter_sub();
1180
1181   my $form     = $main::form;
1182   my %myconfig = %main::myconfig;
1183
1184   $main::auth->assert('config');
1185
1186   AM->get_tax_accounts(\%myconfig, \%$form);
1187
1188   map { $_->{selected} = $form->{chart_id} == $_->{id} } @{ $form->{ACCOUNTS} };
1189
1190   $main::lxdebug->leave_sub();
1191 }
1192
1193 sub save_tax {
1194   $main::lxdebug->enter_sub();
1195
1196   my $form     = $main::form;
1197   my %myconfig = %main::myconfig;
1198   my $locale   = $main::locale;
1199
1200   $main::auth->assert('config');
1201
1202   $form->error($locale->text('Taxkey  missing!')) unless length($form->{taxkey}) != 0;
1203   $form->error($locale->text('Taxdescription  missing!')) unless length($form->{taxdescription}) != 0;
1204   $form->error($locale->text('Taxrate missing!')) unless length($form->{rate}) != 0;
1205
1206   $form->{rate} = $form->parse_amount(\%myconfig, $form->{rate});
1207
1208   if ($form->{taxkey} == 0 and $form->{rate} > 0) {
1209     $form->error($locale->text('Taxkey 0 is reserved for rate 0'));
1210   }
1211
1212   if ( $form->{rate} < 0 || $form->{rate} >= 100 ) {
1213     $form->error($locale->text('Tax Percent is a number between 0 and 100'));
1214   }
1215
1216   if ( $form->{rate} <= 0.99 && $form->{rate} > 0 ) {
1217     $form->error($locale->text('Tax Percent is a number between 0 and 100'));
1218   }
1219
1220   my @translation_keys  =  grep { $_ =~ '^translation_\d+' } keys %$form;
1221   $form->{translations} = { map { $_ =~ '^translation_(\d+)'; $1 => $form->{$_} } @translation_keys };
1222
1223   AM->save_tax(\%myconfig, \%$form);
1224   $form->redirect($locale->text('Tax saved!'));
1225
1226   $main::lxdebug->leave_sub();
1227 }
1228
1229 sub delete_tax {
1230   $main::lxdebug->enter_sub();
1231
1232   my $form     = $main::form;
1233   my %myconfig = %main::myconfig;
1234   my $locale   = $main::locale;
1235
1236   $main::auth->assert('config');
1237
1238   AM->delete_tax(\%myconfig, \%$form);
1239   $form->redirect($locale->text('Tax deleted!'));
1240
1241   $main::lxdebug->leave_sub();
1242 }
1243
1244 sub add_warehouse {
1245   $main::lxdebug->enter_sub();
1246
1247   my $form     = $main::form;
1248   my $locale   = $main::locale;
1249
1250   $main::auth->assert('config');
1251
1252   $form->{title}      = $locale->text('Add Warehouse');
1253   $form->{callback} ||= build_std_url('action=add_warehouse');
1254
1255   setup_am_edit_warehouse_action_bar();
1256
1257   $form->header();
1258   print $form->parse_html_template('am/edit_warehouse');
1259
1260   $main::lxdebug->leave_sub();
1261 }
1262
1263 sub edit_warehouse {
1264   $main::lxdebug->enter_sub();
1265
1266   my $form     = $main::form;
1267   my %myconfig = %main::myconfig;
1268   my $locale   = $main::locale;
1269
1270   $main::auth->assert('config');
1271
1272   AM->get_warehouse(\%myconfig, $form);
1273
1274   $form->get_lists('employees' => 'EMPLOYEES');
1275
1276   $form->{title}      = $locale->text('Edit Warehouse');
1277   $form->{callback} ||= build_std_url('action=list_warehouses');
1278
1279   setup_am_edit_warehouse_action_bar(id => $::form->{id}, in_use => any { $_->{in_use} } @{ $::form->{BINS} });
1280
1281   $form->header();
1282   print $form->parse_html_template('am/edit_warehouse');
1283
1284   $main::lxdebug->leave_sub();
1285 }
1286
1287 sub edit_bins {
1288   $::auth->assert('config');
1289
1290   AM->get_warehouse(\%::myconfig, $::form);
1291
1292   $::form->{title}      = $::locale->text('Edit Bins for Warehouse \'#1\'', $::form->{description});
1293   $::form->{callback} ||= build_std_url('action=list_warehouses');
1294
1295   setup_am_edit_bins_action_bar(id => $::form->{id});
1296
1297   $::form->header;
1298   print $::form->parse_html_template('am/edit_bins');
1299 }
1300
1301 sub list_warehouses {
1302   $main::lxdebug->enter_sub();
1303
1304   my $form     = $main::form;
1305   my %myconfig = %main::myconfig;
1306   my $locale   = $main::locale;
1307
1308   $main::auth->assert('config');
1309
1310   AM->get_all_warehouses(\%myconfig, $form);
1311
1312   $form->{callback} = build_std_url('action=list_warehouses');
1313   $form->{title}    = $locale->text('Warehouses');
1314   $form->{url_base} = build_std_url('callback');
1315
1316   setup_am_list_warehouses_action_bar();
1317
1318   $form->header();
1319   print $form->parse_html_template('am/list_warehouses');
1320
1321   $main::lxdebug->leave_sub();
1322 }
1323
1324 sub save_warehouse {
1325   $main::lxdebug->enter_sub();
1326
1327   my $form     = $main::form;
1328   my %myconfig = %main::myconfig;
1329   my $locale   = $main::locale;
1330
1331   $main::auth->assert('config');
1332
1333   $form->isblank("description", $locale->text('Description missing!'));
1334
1335   $form->{number_of_new_bins} = $form->parse_amount(\%myconfig, $form->{number_of_new_bins});
1336
1337   AM->save_warehouse(\%myconfig, $form);
1338
1339   $form->{callback} .= '&saved_message=' . E($locale->text('Warehouse saved.')) if ($form->{callback});
1340
1341   $form->redirect($locale->text('Warehouse saved.'));
1342
1343   $main::lxdebug->leave_sub();
1344 }
1345
1346 sub delete_warehouse {
1347   $main::lxdebug->enter_sub();
1348
1349   my $form     = $main::form;
1350   my %myconfig = %main::myconfig;
1351   my $locale   = $main::locale;
1352
1353   $main::auth->assert('config');
1354
1355   if (AM->delete_warehouse(\%myconfig, $form)) {
1356     $form->{callback} .= '&saved_message=' . E($locale->text('Warehouse deleted.')) if ($form->{callback});
1357     $form->redirect($locale->text('Warehouse deleted.'));
1358
1359   } else {
1360     $form->error($locale->text('The warehouse could not be deleted because it has already been used.'));
1361   }
1362
1363   $main::lxdebug->leave_sub();
1364 }
1365
1366 sub save_bin {
1367   $main::lxdebug->enter_sub();
1368
1369   my $form     = $main::form;
1370   my %myconfig = %main::myconfig;
1371   my $locale   = $main::locale;
1372
1373   $main::auth->assert('config');
1374
1375   AM->save_bins(\%myconfig, $form);
1376
1377   $form->{callback} .= '&saved_message=' . E($locale->text('Bins saved.')) if ($form->{callback});
1378
1379   $form->redirect($locale->text('Bins saved.'));
1380
1381   $main::lxdebug->leave_sub();
1382 }
1383
1384 sub setup_am_config_action_bar {
1385   my %params = @_;
1386
1387   for my $bar ($::request->layout->get('actionbar')) {
1388     $bar->add(
1389       action => [
1390         t8('Save'),
1391         submit    => [ '#form', { action => "save_preferences" } ],
1392         accesskey => 'enter',
1393       ],
1394     );
1395   }
1396 }
1397
1398 sub setup_am_edit_account_action_bar {
1399   my %params = @_;
1400
1401   for my $bar ($::request->layout->get('actionbar')) {
1402     $bar->add(
1403       combobox => [
1404         action => [
1405           t8('Save'),
1406           submit    => [ '#form', { action => "save_account" } ],
1407           accesskey => 'enter',
1408         ],
1409
1410         action => [
1411           t8('Save as new'),
1412           submit   => [ '#form', { action => "save_as_new_account" } ],
1413           disabled => !$::form->{id} ? t8('The object has not been saved yet.') : undef,
1414         ],
1415       ],
1416
1417       action => [
1418         t8('Delete'),
1419         submit   => [ '#form', { action => "delete_account" } ],
1420         disabled => !$::form->{id}                         ? t8('The object has not been saved yet.')
1421                   :  $::form->{id} && !$::form->{orphaned} ? t8('The object is in use and cannot be deleted.')
1422                   :                                          undef,
1423         confirm  => t8('Do you really want to delete this object?'),
1424       ],
1425     );
1426   }
1427 }
1428
1429 sub setup_am_list_tax_action_bar {
1430   my %params = @_;
1431
1432   for my $bar ($::request->layout->get('actionbar')) {
1433     $bar->add(
1434       link => [
1435         t8('Add'),
1436         link => 'am.pl?action=add_tax',
1437       ],
1438     );
1439   }
1440 }
1441
1442 sub setup_am_edit_tax_action_bar {
1443   my %params = @_;
1444
1445   for my $bar ($::request->layout->get('actionbar')) {
1446     $bar->add(
1447       action => [
1448         t8('Save'),
1449         submit    => [ '#form', { action => "save_tax" } ],
1450         accesskey => 'enter',
1451       ],
1452
1453       action => [
1454         t8('Delete'),
1455         submit   => [ '#form', { action => "delete_tax" } ],
1456         disabled => !$::form->{id}                                      ? t8('The object has not been saved yet.')
1457                   : !$::form->{orphaned} || $::form->{tax_already_used} ? t8('The object is in use and cannot be deleted.')
1458                   :                                                       undef,
1459         confirm  => t8('Do you really want to delete this object?'),
1460       ],
1461     );
1462   }
1463 }
1464
1465 sub setup_am_add_unit_action_bar {
1466   my %params = @_;
1467
1468   for my $bar ($::request->layout->get('actionbar')) {
1469     $bar->add(
1470       action => [
1471         t8('Save'),
1472         submit    => [ '#form', { action => "create_unit" } ],
1473         accesskey => 'enter',
1474       ],
1475
1476       'separator',
1477
1478       link => [
1479         t8('Back'),
1480         link => 'am.pl?action=edit_units',
1481       ],
1482     );
1483   }
1484 }
1485
1486 sub setup_am_edit_units_action_bar {
1487   my %params = @_;
1488
1489   for my $bar ($::request->layout->get('actionbar')) {
1490     $bar->add(
1491       action => [
1492         t8('Save'),
1493         submit    => [ '#form', { action => "save_unit" } ],
1494         accesskey => 'enter',
1495       ],
1496
1497       'separator',
1498
1499       link => [
1500         t8('Add'),
1501         link => 'am.pl?action=add_unit',
1502       ],
1503     );
1504   }
1505 }
1506
1507 sub setup_am_list_warehouses_action_bar {
1508   my %params = @_;
1509
1510   for my $bar ($::request->layout->get('actionbar')) {
1511     $bar->add(
1512       link => [
1513         t8('Add'),
1514         link      => 'am.pl?action=add&type=warehouse&callback=' . E($::form->{callback}),
1515         accesskey => 'enter',
1516       ],
1517     );
1518   }
1519 }
1520
1521 sub setup_am_edit_warehouse_action_bar {
1522   my %params = @_;
1523
1524   for my $bar ($::request->layout->get('actionbar')) {
1525     $bar->add(
1526       action => [
1527         t8('Save'),
1528         submit    => [ '#form', { action => 'save_warehouse' } ],
1529         accesskey => 'enter',
1530       ],
1531
1532       action => [
1533         t8('Delete'),
1534         submit   => [ '#form', { action => 'delete_warehouse' } ],
1535         disabled => !$params{id}    ? t8('The object has not been saved yet.')
1536                   : $params{in_use} ? t8('The object is in use and cannot be deleted.')
1537                   :                   undef,
1538         confirm  => t8('Do you really want to delete this object?'),
1539       ],
1540
1541       'separator',
1542
1543       link => [
1544         t8('Bins'),
1545         link    => 'am.pl?action=edit_bins&id=' . E($params{id}),
1546         only_if => $params{id},
1547       ],
1548
1549       link => [
1550         t8('Abort'),
1551         link => $::form->{callback} || 'am.pl?action=list_warehouses',
1552       ],
1553     );
1554   }
1555 }
1556
1557 sub setup_am_edit_bins_action_bar {
1558   my %params = @_;
1559
1560   for my $bar ($::request->layout->get('actionbar')) {
1561     $bar->add(
1562       action => [
1563         t8('Save'),
1564         submit    => [ '#form', { action => 'save_bin' } ],
1565         accesskey => 'enter',
1566       ],
1567
1568       'separator',
1569
1570       link => [
1571         t8('Abort'),
1572         link => 'am.pl?action=edit_warehouse&id=' . E($params{id}),
1573       ],
1574     );
1575   }
1576 }
1577
1578 sub setup_am_audit_control_action_bar {
1579   my %params = @_;
1580
1581   for my $bar ($::request->layout->get('actionbar')) {
1582     $bar->add(
1583       action => [
1584         t8('Save'),
1585         submit    => [ '#form', { action => 'doclose' } ],
1586         accesskey => 'enter',
1587       ],
1588     );
1589   }
1590 }
1591
1592 sub setup_am_show_history_search_action_bar {
1593   my %params = @_;
1594
1595   for my $bar ($::request->layout->get('actionbar')) {
1596     $bar->add(
1597       action => [
1598         t8('Show'),
1599         submit    => [ '#form' ],
1600         accesskey => 'enter',
1601       ],
1602     );
1603   }
1604 }
1605
1606 sub setup_am_show_am_history_action_bar {
1607   my %params = @_;
1608
1609   for my $bar ($::request->layout->get('actionbar')) {
1610     $bar->add(
1611       action => [
1612         t8('Back'),
1613         call => [ 'kivi.history_back' ],
1614       ],
1615     );
1616   }
1617 }