]> wagnertech.de Git - mfinanz.git/blob - bin/mozilla/gl.pl
restart apache2 in postinst
[mfinanz.git] / bin / mozilla / gl.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 # Genereal Ledger
32 #
33 #======================================================================
34
35 use utf8;
36 use strict;
37
38 use POSIX qw(strftime);
39 use List::Util qw(first sum);
40
41 use SL::DB::ApGl;
42 use SL::DB::RecordTemplate;
43 use SL::DB::ReconciliationLink;
44 use SL::DB::BankTransactionAccTrans;
45 use SL::DB::Tax;
46 use SL::DB::ValidityToken;
47 use SL::DB::GLTransaction;
48 use SL::FU;
49 use SL::GL;
50 use SL::Helper::Flash qw(flash flash_later);
51 use SL::IS;
52 use SL::ReportGenerator;
53 use SL::DBUtils qw(selectrow_query selectall_hashref_query);
54 use SL::Webdav;
55 use SL::Locale::String qw(t8);
56 use SL::Helper::GlAttachments qw(count_gl_attachments);
57 use SL::Presenter::Tag;
58 use SL::Presenter::Chart;
59 require "bin/mozilla/common.pl";
60 require "bin/mozilla/reportgenerator.pl";
61
62 # this is for our long dates
63 # $locale->text('January')
64 # $locale->text('February')
65 # $locale->text('March')
66 # $locale->text('April')
67 # $locale->text('May ')
68 # $locale->text('June')
69 # $locale->text('July')
70 # $locale->text('August')
71 # $locale->text('September')
72 # $locale->text('October')
73 # $locale->text('November')
74 # $locale->text('December')
75
76 # this is for our short month
77 # $locale->text('Jan')
78 # $locale->text('Feb')
79 # $locale->text('Mar')
80 # $locale->text('Apr')
81 # $locale->text('May')
82 # $locale->text('Jun')
83 # $locale->text('Jul')
84 # $locale->text('Aug')
85 # $locale->text('Sep')
86 # $locale->text('Oct')
87 # $locale->text('Nov')
88 # $locale->text('Dec')
89
90 sub load_record_template {
91   $::auth->assert('gl_transactions');
92
93   # Load existing template and verify that its one for this module.
94   my $template = SL::DB::RecordTemplate
95     ->new(id => $::form->{id})
96     ->load(
97       with_object => [ qw(customer payment currency record_items record_items.chart) ],
98     );
99
100   die "invalid template type" unless $template->template_type eq 'gl_transaction';
101
102   $template->substitute_variables;
103   my $payment_suggestion =  $::form->{form_defaults}->{amount_1};
104
105   # Clean the current $::form before rebuilding it from the template.
106   my $form_defaults = delete $::form->{form_defaults};
107   delete @{ $::form }{ grep { !m{^(?:script|login)$}i } keys %{ $::form } };
108
109   my $dummy_form = {};
110   GL->transaction(\%::myconfig, $dummy_form);
111
112   # Fill $::form from the template.
113   my $today                   = DateTime->today_local;
114   $::form->{title}            = "Add";
115   $::form->{transdate}        = $today->to_kivitendo;
116   $::form->{duedate}          = $today->to_kivitendo;
117   $::form->{rowcount}         = @{ $template->items };
118   $::form->{paidaccounts}     = 1;
119   $::form->{$_}               = $template->$_     for qw(department_id taxincluded ob_transaction cb_transaction reference description show_details transaction_description);
120   $::form->{$_}               = $dummy_form->{$_} for qw(closedto revtrans previous_id previous_gldate);
121
122   my $row = 0;
123   foreach my $item (@{ $template->items }) {
124     $row++;
125
126     my $active_taxkey = $item->chart->get_active_taxkey;
127     my $taxes         = SL::DB::Manager::Tax->get_all(
128       where   => [ chart_categories => { like => '%' . $item->chart->category . '%' }],
129       sort_by => 'taxkey, rate',
130     );
131
132     my $tax   = first { $item->tax_id          == $_->id } @{ $taxes };
133     $tax    //= first { $active_taxkey->tax_id == $_->id } @{ $taxes };
134     $tax    //= $taxes->[0];
135
136     if (!$tax) {
137       $row--;
138       next;
139     }
140
141     $::form->{"accno_id_${row}"}          = $item->chart_id;
142     $::form->{"previous_accno_id_${row}"} = $item->chart_id;
143     $::form->{"debit_${row}"}             = $::form->format_amount(\%::myconfig, ($payment_suggestion ? $payment_suggestion : $item->amount1), 2) if $item->amount1 * 1;
144     $::form->{"credit_${row}"}            = $::form->format_amount(\%::myconfig, ($payment_suggestion ? $payment_suggestion : $item->amount2), 2) if $item->amount2 * 1;
145     $::form->{"taxchart_${row}"}          = $item->tax_id . '--' . $tax->rate;
146     $::form->{"${_}_${row}"}              = $item->$_ for qw(source memo project_id);
147   }
148
149   $::form->{$_} = $form_defaults->{$_} for keys %{ $form_defaults // {} };
150
151   flash('info', $::locale->text("The record template '#1' has been loaded.", $template->template_name));
152
153   $::form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_GL_TRANSACTION_POST())->token;
154
155   update(
156     keep_rows_without_amount => 1,
157     dont_add_new_row         => 1,
158   );
159 }
160
161 sub save_record_template {
162   $::auth->assert('gl_transactions');
163
164   my $template = $::form->{record_template_id} ? SL::DB::RecordTemplate->new(id => $::form->{record_template_id})->load : SL::DB::RecordTemplate->new;
165   my $js       = SL::ClientJS->new(controller => SL::Controller::Base->new);
166   my $new_name = $template->template_name_to_use($::form->{record_template_new_template_name});
167   $js->dialog->close('#record_template_dialog');
168
169
170   # bank transactions need amounts for assignment
171   my $can_save = 0;
172   $can_save    = 1 if ($::form->{credit_1} > 0 && $::form->{debit_2} > 0 && $::form->{credit_2} == 0 && $::form->{debit_1} == 0);
173   $can_save    = 1 if ($::form->{credit_2} > 0 && $::form->{debit_1} > 0 && $::form->{credit_1} == 0 && $::form->{debit_2} == 0);
174   return $js->flash('error', t8('Can only save template if amounts,i.e. 1 for debit and credit are set.'))->render unless $can_save;
175
176   my @items = grep {
177     $_->{chart_id} && (($_->{tax_id} // '') ne '')
178   } map {
179     +{ chart_id   => $::form->{"accno_id_${_}"},
180        amount1    => $::form->parse_amount(\%::myconfig, $::form->{"debit_${_}"}),
181        amount2    => $::form->parse_amount(\%::myconfig, $::form->{"credit_${_}"}),
182        tax_id     => (split m{--}, $::form->{"taxchart_${_}"})[0],
183        project_id => $::form->{"project_id_${_}"} || undef,
184        source     => $::form->{"source_${_}"},
185        memo       => $::form->{"memo_${_}"},
186      }
187   } (1..($::form->{rowcount} || 1));
188
189   $template->assign_attributes(
190     template_type  => 'gl_transaction',
191     template_name  => $new_name,
192
193     currency_id             => $::instance_conf->get_currency_id,
194     department_id           => $::form->{department_id}    || undef,
195     project_id              => $::form->{globalproject_id} || undef,
196     taxincluded             => $::form->{taxincluded}     ? 1 : 0,
197     ob_transaction          => $::form->{ob_transaction}  ? 1 : 0,
198     cb_transaction          => $::form->{cb_transaction}  ? 1 : 0,
199     reference               => $::form->{reference},
200     description             => $::form->{description},
201     show_details            => $::form->{show_details},
202     transaction_description => $::form->{transaction_description},
203
204     items          => \@items,
205   );
206
207   eval {
208     $template->save;
209     1;
210   } or do {
211     return $js
212       ->flash('error', $::locale->text("Saving the record template '#1' failed.", $new_name))
213       ->render;
214   };
215
216   return $js
217     ->flash('info', $::locale->text("The record template '#1' has been saved.", $new_name))
218     ->render;
219 }
220
221 sub add {
222   $main::lxdebug->enter_sub();
223
224   $main::auth->assert('gl_transactions');
225
226   my $form     = $main::form;
227   my %myconfig = %main::myconfig;
228
229   $form->{title} = "Add";
230
231   $form->{callback} = "gl.pl?action=add" unless $form->{callback};
232
233   # we use this only to set a default date
234   # yep. aber er holt hier auch schon ALL_CHARTS. Aufwand / Nutzen? jb
235   GL->transaction(\%myconfig, \%$form);
236
237   $form->{rowcount}  = 2;
238
239   $form->{debit}  = 0;
240   $form->{credit} = 0;
241   $form->{tax}    = 0;
242
243   $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
244
245   $form->{show_details} = $myconfig{show_form_details} unless defined $form->{show_details};
246
247   if (!$form->{form_validity_token}) {
248     $form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_GL_TRANSACTION_POST())->token;
249   }
250
251   &display_form(1);
252   $main::lxdebug->leave_sub();
253
254 }
255
256 sub add_from_email_journal {
257   die "No 'email_journal_id' was given." unless ($::form->{email_journal_id});
258   &add;
259 }
260
261 sub load_record_template_from_email_journal {
262   die "No 'email_journal_id' was given." unless ($::form->{email_journal_id});
263   &load_record_template;
264 }
265
266 sub edit_with_email_journal_workflow {
267   my ($self) = @_;
268   die "No 'email_journal_id' was given." unless ($::form->{email_journal_id});
269   $::form->{workflow_email_journal_id}    = delete $::form->{email_journal_id};
270   $::form->{workflow_email_attachment_id} = delete $::form->{email_attachment_id};
271   $::form->{workflow_email_callback}      = delete $::form->{callback};
272
273   &edit;
274 }
275
276 sub prepare_transaction {
277   $main::lxdebug->enter_sub();
278
279   $main::auth->assert('gl_transactions');
280
281   my $form     = $main::form;
282   my %myconfig = %main::myconfig;
283
284   GL->transaction(\%myconfig, \%$form);
285
286   $form->{amount} = $form->format_amount(\%myconfig, $form->{amount}, 2);
287
288   $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
289
290   my $i        = 1;
291   my $tax      = 0;
292   my $taxaccno = "";
293   foreach my $ref (@{ $form->{GL} }) {
294     my $j = $i - 1;
295     if ($tax && ($ref->{accno} eq $taxaccno)) {
296       $form->{"tax_$j"}      = abs($ref->{amount});
297       $form->{"taxchart_$j"} = $ref->{id} . "--" . $ref->{taxrate};
298       if ($form->{taxincluded}) {
299         if ($ref->{amount} < 0) {
300           $form->{"debit_$j"} += $form->{"tax_$j"};
301         } else {
302           $form->{"credit_$j"} += $form->{"tax_$j"};
303         }
304       }
305       $form->{"project_id_$j"} = $ref->{project_id};
306
307     } else {
308       $form->{"accno_id_$i"} = $ref->{chart_id};
309       for (qw(fx_transaction source memo)) { $form->{"${_}_$i"} = $ref->{$_} }
310       if ($ref->{amount} < 0) {
311         $form->{totaldebit} -= $ref->{amount};
312         $form->{"debit_$i"} = $ref->{amount} * -1;
313       } else {
314         $form->{totalcredit} += $ref->{amount};
315         $form->{"credit_$i"} = $ref->{amount};
316       }
317       $form->{"taxchart_$i"} = $ref->{id}."--0.00000";
318       $form->{"project_id_$i"} = $ref->{project_id};
319       $i++;
320     }
321     if ($ref->{taxaccno} && !$tax) {
322       $taxaccno = $ref->{taxaccno};
323       $tax      = 1;
324     } else {
325       $taxaccno = "";
326       $tax      = 0;
327     }
328   }
329
330   $form->{rowcount} = $i;
331   $form->{locked}   =
332     ($form->datetonum($form->{transdate}, \%myconfig) <=
333      $form->datetonum($form->{closedto}, \%myconfig));
334
335   $main::lxdebug->leave_sub();
336 }
337
338 sub edit {
339   $main::lxdebug->enter_sub();
340
341   $main::auth->assert('gl_transactions');
342
343   my $form     = $main::form;
344   my %myconfig = %main::myconfig;
345
346   prepare_transaction();
347
348   $form->{title} = "Edit";
349
350   $form->{show_details} = $myconfig{show_form_details} unless defined $form->{show_details};
351
352   if ($form->{id} && $::instance_conf->get_webdav) {
353     my $webdav = SL::Webdav->new(
354       type     => 'general_ledger',
355       number   => $form->{id},
356     );
357     my @all_objects = $webdav->get_all_objects;
358     @{ $form->{WEBDAV} } = map { { name => $_->filename,
359                                    type => t8('File'),
360                                    link => File::Spec->catfile($_->full_filedescriptor),
361                                } } @all_objects;
362   }
363   form_header();
364   display_rows();
365   form_footer();
366
367   $main::lxdebug->leave_sub();
368 }
369
370
371 sub search {
372   $::lxdebug->enter_sub;
373   $::auth->assert('general_ledger | gl_transactions');
374
375   $::form->get_lists(
376     projects  => { key => "ALL_PROJECTS", all => 1 },
377   );
378   $::form->{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]);
379   $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
380
381   setup_gl_search_action_bar();
382
383   $::form->{title} = t8('Journal');
384   $::form->header;
385   print $::form->parse_html_template('gl/search', {
386     employee_label => sub { "$_[0]{id}--$_[0]{name}" },
387   });
388
389   $::lxdebug->leave_sub;
390 }
391
392 sub create_subtotal_row {
393   $main::lxdebug->enter_sub();
394
395   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
396
397   my $form     = $main::form;
398   my %myconfig = %main::myconfig;
399
400   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
401
402   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
403
404   map { $totals->{$_} = 0 } @{ $subtotal_columns };
405
406   $main::lxdebug->leave_sub();
407
408   return $row;
409 }
410
411 sub generate_report {
412   $main::lxdebug->enter_sub();
413
414   $main::auth->assert('general_ledger | gl_transactions');
415
416   my $form     = $main::form;
417   my %myconfig = %main::myconfig;
418   my $locale   = $main::locale;
419
420   # generate_report wird beim ersten Aufruf per Weiter-Knopf und POST mit der hidden Variablen sort mit Wert "datesort" (früher "transdate" als Defaultsortiervariable) Ã¼bertragen
421
422   # <form method=post action=gl.pl>
423   # <input type=hidden name=sort value=datesort>    # form->{sort} setzen
424   # <input type=hidden name=nextsub value=generate_report>
425
426   # anhand von neuer Variable datesort wird jetzt $form->{sort} auf transdate oder gldate gesetzt
427   # damit ist die Hidden Variable "sort" wahrscheinlich sogar Ã¼berflüssig
428
429   # Ã¤ndert man die Sortierreihenfolge per Klick auf eine der Ãœberschriften wird die Variable "sort" per GET Ã¼bergeben, z.B. id,transdate, gldate, ...
430   # gl.pl?action=generate_report&employee=18383--Jan%20B%c3%bcren&datesort=transdate&category=X&l_transdate=Y&l_gldate=Y&l_id=Y&l_reference=Y&l_description=Y&l_source=Y&l_debit=Y&l_credit=Y&sort=gldate&sortdir=0
431
432   if ( $form->{sort} eq 'datesort' ) {   # sollte bei einem Post (Aufruf aus Suchmaske) immer wahr sein
433       # je nachdem ob in Suchmaske "transdate" oder "gldate" ausgesucht wurde erstes Suchergebnis entsprechend sortieren
434       $form->{sort} = $form->{datesort};
435   };
436
437   # was passiert hier?
438   report_generator_set_default_sort("$form->{datesort}", 1);
439 #  report_generator_set_default_sort('transdate', 1);
440
441   GL->all_transactions(\%myconfig, \%$form);
442
443   my %acctype = ('A' => $locale->text('Asset'),
444                  'C' => $locale->text('Contra'),
445                  'L' => $locale->text('Liability'),
446                  'Q' => $locale->text('Equity'),
447                  'I' => $locale->text('Revenue'),
448                  'E' => $locale->text('Expense'),);
449
450   $form->{title} = $locale->text('Journal');
451   if ($form->{category} ne 'X') {
452     $form->{title} .= " : " . $locale->text($acctype{ $form->{category} });
453   }
454
455   $form->{landscape} = 1;
456
457   my $ml = ($form->{ml} =~ /(A|E|Q)/) ? -1 : 1;
458
459   my @columns = qw(
460     transdate     gldate              id                         reference
461     description   notes               transaction_description    source
462     doccnt        debit               debit_accno
463     credit        credit_accno        debit_tax                  debit_tax_accno
464     credit_tax    credit_tax_accno    balance                    projectnumbers
465     department    employee
466   );
467
468   # add employee here, so that variable is still known and passed in url when choosing a different sort order in resulting table
469   my @hidden_variables = qw(accno source reference description notes project_id datefrom dateto employee_id datesort category l_subtotal department_id transaction_description);
470   push @hidden_variables, map { "l_${_}" } @columns;
471
472   my $employee = $form->{employee_id} ? SL::DB::Employee->new(id => $form->{employee_id})->load->name : '';
473
474   my (@options, @date_options);
475   push @options,      $locale->text('Account')                 . " : $form->{accno} $form->{account_description}" if ($form->{accno});
476   push @options,      $locale->text('Source')                  . " : $form->{source}"                             if ($form->{source});
477   push @options,      $locale->text('Reference')               . " : $form->{reference}"                          if ($form->{reference});
478   push @options,      $locale->text('Description')             . " : $form->{description}"                        if ($form->{description});
479   push @options,      $locale->text('Notes')                   . " : $form->{notes}"                              if ($form->{notes});
480   push @options,      $locale->text('Transaction description') . " : $form->{transaction_description}"            if $form->{transaction_description};
481   push @options,      $locale->text('Employee')                . " : $employee"                                   if $employee;
482   my $datesorttext = $form->{datesort} eq 'transdate' ? $locale->text('Transdate') :  $locale->text('Gldate');
483   push @date_options,      "$datesorttext"                              if ($form->{datesort} and ($form->{datefrom} or $form->{dateto}));
484   push @date_options, $locale->text('From'), $locale->date(\%myconfig, $form->{datefrom}, 1)          if ($form->{datefrom});
485   push @date_options, $locale->text('Bis'),  $locale->date(\%myconfig, $form->{dateto},   1)          if ($form->{dateto});
486   push @options,      join(' ', @date_options)                                                        if (scalar @date_options);
487
488   if ($form->{department_id}) {
489     my $department = SL::DB::Manager::Department->find_by( id => $form->{department_id} );
490     push @options, $locale->text('Department') . " : " . $department->description;
491   }
492
493   my $callback = build_std_url('action=generate_report', grep { $form->{$_} } @hidden_variables);
494
495   $form->{l_credit_accno}     = 'Y';
496   $form->{l_debit_accno}      = 'Y';
497   $form->{l_credit_tax}       = 'Y';
498   $form->{l_debit_tax}        = 'Y';
499 #  $form->{l_gldate}           = 'Y';  # Spalte mit gldate immer anzeigen
500   $form->{l_credit_tax_accno} = 'Y';
501   $form->{l_datesort} = 'Y';
502   $form->{l_debit_tax_accno}  = 'Y';
503   $form->{l_balance}          = $form->{accno} ? 'Y' : '';
504   $form->{l_doccnt}           = $form->{l_source} ? 'Y' : '';
505
506   my %column_defs = (
507     'id'                      => { 'text' => $locale->text('ID'), },
508     'transdate'               => { 'text' => $locale->text('Transdate'), },
509     'gldate'                  => { 'text' => $locale->text('Gldate'), },
510     'reference'               => { 'text' => $locale->text('Reference'), },
511     'source'                  => { 'text' => $locale->text('Source'), },
512     'doccnt'                  => { 'text' => $locale->text('Document Count'), },
513     'description'             => { 'text' => $locale->text('Description'), },
514     'notes'                   => { 'text' => $locale->text('Notes'), },
515     'debit'                   => { 'text' => $locale->text('Debit'), },
516     'debit_accno'             => { 'text' => $locale->text('Debit Account'), },
517     'credit'                  => { 'text' => $locale->text('Credit'), },
518     'credit_accno'            => { 'text' => $locale->text('Credit Account'), },
519     'debit_tax'               => { 'text' => $locale->text('Debit Tax'), },
520     'debit_tax_accno'         => { 'text' => $locale->text('Debit Tax Account'), },
521     'credit_tax'              => { 'text' => $locale->text('Credit Tax'), },
522     'credit_tax_accno'        => { 'text' => $locale->text('Credit Tax Account'), },
523     'balance'                 => { 'text' => $locale->text('Balance'), },
524     'projectnumbers'          => { 'text' => $locale->text('Project Numbers'), },
525     'department'              => { 'text' => $locale->text('Department'), },
526     'employee'                => { 'text' => $locale->text('Employee'), },
527     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
528   );
529
530   foreach my $name (qw(id transdate gldate reference description debit_accno credit_accno debit_tax_accno credit_tax_accno department transaction_description)) {
531     my $sortname                = $name =~ m/accno/ ? 'accno' : $name;
532     my $sortdir                 = $sortname eq $form->{sort} ? 1 - $form->{sortdir} : $form->{sortdir};
533     $column_defs{$name}->{link} = $callback . "&sort=$sortname&sortdir=$sortdir";
534   }
535
536   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
537   map { $column_defs{$_}->{visible} = 0 } qw(debit_accno credit_accno debit_tax_accno credit_tax_accno) if $form->{accno};
538
539   my %column_alignment;
540   map { $column_alignment{$_}     = 'right'  } qw(balance id debit credit debit_tax credit_tax balance);
541   map { $column_alignment{$_}     = 'center' } qw(transdate gldate reference debit_accno credit_accno debit_tax_accno credit_tax_accno);
542   map { $column_alignment{$_}     = 'left' } qw(description source notes);
543   map { $column_defs{$_}->{align} = $column_alignment{$_} } keys %column_alignment;
544
545   my $report = SL::ReportGenerator->new(\%myconfig, $form);
546
547   $report->set_columns(%column_defs);
548   $report->set_column_order(@columns);
549
550   $form->{l_attachments} = 'Y';
551   $report->set_export_options('generate_report', @hidden_variables, qw(sort sortdir l_attachments));
552
553   $report->set_sort_indicator($form->{sort} eq 'accno' ? 'debit_accno' : $form->{sort}, $form->{sortdir});
554
555   $report->set_options('top_info_text'        => join("\n", @options),
556                        'output_format'        => 'HTML',
557                        'title'                => $form->{title},
558                        'attachment_basename'  => $locale->text('general_ledger_list') . strftime('_%Y%m%d', localtime time),
559     );
560   $report->set_options_from_form();
561   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
562
563   # add sort to callback
564   $form->{callback} = "$callback&sort=" . E($form->{sort}) . "&sortdir=" . E($form->{sortdir});
565
566
567   my @totals_columns = qw(debit credit debit_tax credit_tax);
568   my %subtotals      = map { $_ => 0 } @totals_columns;
569   my %totals         = map { $_ => 0 } @totals_columns;
570   my $idx            = 0;
571
572   foreach my $ref (@{ $form->{GL} }) {
573
574     my %rows;
575
576     foreach my $key (qw(debit credit debit_tax credit_tax)) {
577       $rows{$key} = [];
578       foreach my $idx (sort keys(%{ $ref->{$key} })) {
579         my $value         = $ref->{$key}->{$idx};
580         $subtotals{$key} += $value;
581         $totals{$key}    += $value;
582         if ($key =~ /debit.*/) {
583           $ml = -1;
584         } else {
585           $ml = 1;
586         }
587         $form->{balance}  = $form->{balance} + $value * $ml;
588         push @{ $rows{$key} }, $form->format_amount(\%myconfig, $value, 2);
589       }
590     }
591
592     foreach my $key (qw(debit_accno credit_accno debit_tax_accno credit_tax_accno ac_transdate source)) {
593       my $col = $key eq 'ac_transdate' ? 'transdate' : $key;
594       $rows{$col} = [ map { $ref->{$key}->{$_} } sort keys(%{ $ref->{$key} }) ];
595     }
596
597     my $row = { };
598     map { $row->{$_} = { 'data' => '', 'align' => $column_alignment{$_} } } @columns;
599
600     if ( $form->{l_doccnt} ) {
601       $row->{doccnt}->{data} = SL::Helper::GlAttachments->count_gl_pdf_attachments($ref->{id},$ref->{type});
602     }
603
604     my $sh = "";
605     if ($form->{balance} < 0) {
606       $sh = " S";
607       $ml = -1;
608     } elsif ($form->{balance} > 0) {
609       $sh = " H";
610       $ml = 1;
611     }
612     my $data = $form->format_amount(\%myconfig, ($form->{balance} * $ml), 2);
613     $data .= $sh;
614
615     $row->{balance}->{data}        = $data;
616     $row->{projectnumbers}->{data} = join ", ", sort { lc($a) cmp lc($b) } keys %{ $ref->{projectnumbers} };
617
618     map { $row->{$_}->{data} = $ref->{$_} } qw(id reference description notes gldate employee department transaction_description);
619
620     map { $row->{$_}->{data} = \@{ $rows{$_} }; } qw(transdate debit credit debit_accno credit_accno debit_tax_accno credit_tax_accno source);
621
622     foreach my $col (qw(debit_accno credit_accno debit_tax_accno credit_tax_accno)) {
623       $row->{$col}->{link} = [ map { "${callback}&accno=" . E($_) } @{ $rows{$col} } ];
624     }
625
626     map { $row->{$_}->{data} = \@{ $rows{$_} } if ($ref->{"${_}_accno"} ne "") } qw(debit_tax credit_tax);
627
628     $row->{reference}->{link} = build_std_url("script=$ref->{module}.pl", 'action=edit', 'id=' . E($ref->{id}), 'callback');
629
630     my $row_set = [ $row ];
631
632     if ( ($form->{l_subtotal} eq 'Y' && !$form->{report_generator_csv_options_for_import} )
633         && (($idx == (scalar @{ $form->{GL} } - 1))
634             || ($ref->{ $form->{sort} } ne $form->{GL}->[$idx + 1]->{ $form->{sort} }))) {
635       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, [ qw(debit credit) ], 'listsubtotal');
636     }
637
638     $report->add_data($row_set);
639
640     $idx++;
641   }
642
643   # = 0 for balanced ledger
644   my $balanced_ledger = $totals{debit} + $totals{debit_tax} - $totals{credit} - $totals{credit_tax};
645
646   my $row = create_subtotal_row(\%totals, \@columns, \%column_alignment, [ qw(debit credit debit_tax credit_tax) ], 'listtotal');
647
648   my $sh = "";
649   if ($form->{balance} < 0) {
650     $sh = " S";
651     $ml = -1;
652   } elsif ($form->{balance} > 0) {
653     $sh = " H";
654     $ml = 1;
655   }
656   my $data = $form->format_amount(\%myconfig, ($form->{balance} * $ml), 2);
657   $data .= $sh;
658
659   $row->{balance}->{data}        = $data;
660
661   if ( !$form->{report_generator_csv_options_for_import} ) {
662     $report->add_separator();
663     $report->add_data($row);
664   }
665
666   my $raw_bottom_info_text;
667
668   if (!$form->{accno} && (abs($balanced_ledger) >  0.001)) {
669     $raw_bottom_info_text .=
670         '<p><span class="unbalanced_ledger">'
671       . $locale->text('Unbalanced Ledger')
672       . ': '
673       . $form->format_amount(\%myconfig, $balanced_ledger, 3)
674       . '</span></p> ';
675   }
676
677   $raw_bottom_info_text .= $form->parse_html_template('gl/generate_report_bottom');
678
679   $report->set_options('raw_bottom_info_text' => $raw_bottom_info_text);
680
681   setup_gl_transactions_action_bar();
682
683   $report->generate_with_headers();
684
685   $main::lxdebug->leave_sub();
686 }
687
688 sub show_draft {
689   $::form->{transdate} = DateTime->today_local->to_kivitendo if !$::form->{transdate};
690   $::form->{gldate}    = $::form->{transdate} if !$::form->{gldate};
691   $::form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_GL_TRANSACTION_POST())->token;
692   update();
693 }
694
695 sub update {
696   my %params = @_;
697
698   $main::lxdebug->enter_sub();
699
700   $main::auth->assert('gl_transactions');
701
702   my $form     = $main::form;
703   my %myconfig = %main::myconfig;
704
705   $form->{oldtransdate} = $form->{transdate};
706
707   my @a           = ();
708   my $count       = 0;
709   my $debittax    = 0;
710   my $credittax   = 0;
711   my $debitcount  = 0;
712   my $creditcount = 0;
713   my ($debitcredit, $amount);
714
715   my $dbh = SL::DB->client->dbh;
716   my ($notax_id) = selectrow_query($form, $dbh, "SELECT id FROM tax WHERE taxkey = 0 LIMIT 1", );
717   my $zerotaxes  = selectall_hashref_query($form, $dbh, "SELECT id FROM tax WHERE rate = 0", );
718
719   my @flds =
720     qw(accno_id debit credit projectnumber fx_transaction source memo tax taxchart);
721
722   for my $i (1 .. $form->{rowcount}) {
723     $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) for qw(debit credit tax);
724
725     next if !$form->{"debit_$i"} && !$form->{"credit_$i"} && !$params{keep_rows_without_amount};
726
727     push @a, {};
728     $debitcredit = ($form->{"debit_$i"} == 0) ? "0" : "1";
729     if ($debitcredit) {
730       $debitcount++;
731     } else {
732       $creditcount++;
733     }
734
735     if (($debitcount >= 2) && ($creditcount == 2)) {
736       $form->{"credit_$i"} = 0;
737       $form->{"tax_$i"}    = 0;
738       $creditcount--;
739       $form->{creditlock} = 1;
740     }
741     if (($creditcount >= 2) && ($debitcount == 2)) {
742       $form->{"debit_$i"} = 0;
743       $form->{"tax_$i"}   = 0;
744       $debitcount--;
745       $form->{debitlock} = 1;
746     }
747     if (($creditcount == 1) && ($debitcount == 2)) {
748       $form->{creditlock} = 1;
749     }
750     if (($creditcount == 2) && ($debitcount == 1)) {
751       $form->{debitlock} = 1;
752     }
753     if ($debitcredit && $credittax) {
754       $form->{"taxchart_$i"} = "$notax_id--0.00000";
755     }
756     if (!$debitcredit && $debittax) {
757       $form->{"taxchart_$i"} = "$notax_id--0.00000";
758     }
759     $amount =
760       ($form->{"debit_$i"} == 0)
761       ? $form->{"credit_$i"}
762       : $form->{"debit_$i"};
763     my $j = $#a;
764     if (($debitcredit && $credittax) || (!$debitcredit && $debittax)) {
765       $form->{"taxchart_$i"} = "$notax_id--0.00000";
766       $form->{"tax_$i"}      = 0;
767     }
768     my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
769     my $iswithouttax = grep { $_->{id} == $taxkey } @{ $zerotaxes };
770     if (!$iswithouttax) {
771       if ($debitcredit) {
772         $debittax = 1;
773       } else {
774         $credittax = 1;
775       }
776     };
777     my ($tmpnetamount,$tmpdiff);
778     ($tmpnetamount,$form->{"tax_$i"},$tmpdiff) = $form->calculate_tax($amount,$rate,$form->{taxincluded} *= 1,2);
779
780     for (@flds) { $a[$j]->{$_} = $form->{"${_}_$i"} }
781     $count++;
782   }
783
784   for my $i (1 .. $count) {
785     my $j = $i - 1;
786     for (@flds) { $form->{"${_}_$i"} = $a[$j]->{$_} }
787   }
788
789   for my $i ($count + 1 .. $form->{rowcount}) {
790     for (@flds) { delete $form->{"${_}_$i"} }
791   }
792
793   $form->{rowcount} = $count + ($params{dont_add_new_row} ? 0 : 1);
794
795   display_form();
796   $main::lxdebug->leave_sub();
797
798 }
799
800 sub display_form {
801   my ($init) = @_;
802   $main::lxdebug->enter_sub();
803
804   $main::auth->assert('gl_transactions');
805
806   my $form     = $main::form;
807   my %myconfig = %main::myconfig;
808
809   &form_header($init);
810
811   #   for $i (1 .. $form->{rowcount}) {
812   #     $form->{totaldebit} += $form->parse_amount(\%myconfig, $form->{"debit_$i"});
813   #     $form->{totalcredit} += $form->parse_amount(\%myconfig, $form->{"credit_$i"});
814   #
815   #     &form_row($i);
816   #   }
817   &display_rows($init);
818   &form_footer;
819   $main::lxdebug->leave_sub();
820
821 }
822
823 sub display_rows {
824   my ($init) = @_;
825   $main::lxdebug->enter_sub();
826
827   $main::auth->assert('gl_transactions');
828
829   my $form     = $main::form;
830   my %myconfig = %main::myconfig;
831   my $cgi      = $::request->{cgi};
832
833   my %balances = GL->get_chart_balances(map { $_->{id} } @{ $form->{ALL_CHARTS} });
834
835   $form->{debit_1}     = 0 if !$form->{"debit_1"};
836   $form->{totaldebit}  = 0;
837   $form->{totalcredit} = 0;
838
839   my %charts_by_id  = map { ($_->{id} => $_) } @{ $::form->{ALL_CHARTS} };
840   my $default_chart = $::form->{ALL_CHARTS}[0];
841   my $transdate     = $::form->{transdate} ? DateTime->from_kivitendo($::form->{transdate}) : DateTime->today_local;
842   my $deliverydate  = $::form->{deliverydate} ? DateTime->from_kivitendo($::form->{deliverydate}) : undef;
843
844   my ($source, $memo, $source_hidden, $memo_hidden);
845   for my $i (1 .. $form->{rowcount}) {
846     if ($form->{show_details}) {
847       $source = qq|
848       <td><input name="source_$i" value="$form->{"source_$i"}" size="16"></td>|;
849       $memo = qq|
850       <td><input name="memo_$i" value="$form->{"memo_$i"}" size="16"></td>|;
851     } else {
852       $source_hidden = qq|
853       <input type="hidden" name="source_$i" value="$form->{"source_$i"}" size="16">|;
854       $memo_hidden = qq|
855       <input type="hidden" name="memo_$i" value="$form->{"memo_$i"}" size="16">|;
856     }
857
858     my %taxchart_labels = ();
859     my @taxchart_values = ();
860
861     my $accno_id = $::form->{"accno_id_$i"};
862     my $chart    = $charts_by_id{$accno_id} // $default_chart;
863     $accno_id    = $chart->{id};
864     my ($first_taxchart, $default_taxchart, $taxchart_to_use);
865
866     my $used_tax_id;
867     if ( $form->{"taxchart_$i"} ) {
868       ($used_tax_id) = split(/--/, $form->{"taxchart_$i"});
869     }
870
871     my $taxdate = $deliverydate ? $deliverydate : $transdate;
872     foreach my $item ( GL->get_active_taxes_for_chart($accno_id, $taxdate, $used_tax_id) ) {
873       my $key             = $item->id . "--" . $item->rate;
874       $first_taxchart   //= $item;
875       $default_taxchart   = $item if $item->{is_default};
876       $taxchart_to_use    = $item if $key eq $form->{"taxchart_$i"};
877
878       push(@taxchart_values, $key);
879       $taxchart_labels{$key} = $item->taxkey . " - " . $item->taxdescription . " " . $item->rate * 100 . ' %';
880     }
881
882     $taxchart_to_use    //= $default_taxchart // $first_taxchart;
883     my $selected_taxchart = $taxchart_to_use->id . '--' . $taxchart_to_use->rate;
884
885     my $accno = qq|<td>| .
886       SL::Presenter::Chart::picker("accno_id_$i", $accno_id, style => "width: 300px") .
887       SL::Presenter::Tag::hidden_tag("previous_accno_id_$i", $accno_id)
888       . qq|</td>|;
889     my $tax_ddbox = qq|<td>| .
890       NTI($cgi->popup_menu('-name' => "taxchart_$i",
891             '-id' => "taxchart_$i",
892             '-style' => 'width:200px',
893             '-values' => \@taxchart_values,
894             '-labels' => \%taxchart_labels,
895             '-default' => $selected_taxchart))
896       . qq|</td>|;
897
898     my ($fx_transaction, $checked);
899     if ($init) {
900       if ($form->{transfer}) {
901         $fx_transaction = qq|
902         <td><input name="fx_transaction_$i" class=checkbox type=checkbox value=1></td>
903     |;
904       }
905
906     } else {
907       if ($form->{"debit_$i"} != 0) {
908         $form->{totaldebit} += $form->{"debit_$i"};
909         if (!$form->{taxincluded}) {
910           $form->{totaldebit} += $form->{"tax_$i"};
911         }
912       } else {
913         $form->{totalcredit} += $form->{"credit_$i"};
914         if (!$form->{taxincluded}) {
915           $form->{totalcredit} += $form->{"tax_$i"};
916         }
917       }
918
919       for (qw(debit credit tax)) {
920         $form->{"${_}_$i"} =
921           ($form->{"${_}_$i"})
922           ? $form->format_amount(\%myconfig, $form->{"${_}_$i"}, 2)
923           : "";
924       }
925
926       if ($i < $form->{rowcount}) {
927         if ($form->{transfer}) {
928           $checked = ($form->{"fx_transaction_$i"}) ? "1" : "";
929           my $x = ($checked) ? "x" : "";
930           $fx_transaction = qq|
931       <td><input type=hidden name="fx_transaction_$i" value="$checked">$x</td>
932     |;
933         }
934         $form->hide_form("accno_$i");
935
936       } else {
937         if ($form->{transfer}) {
938           $fx_transaction = qq|
939       <td><input name="fx_transaction_$i" class=checkbox type=checkbox value=1></td>
940     |;
941         }
942       }
943     }
944     my $debitreadonly  = "";
945     my $creditreadonly = "";
946     if ($i == $form->{rowcount}) {
947       if ($form->{debitlock}) {
948         $debitreadonly = "readonly";
949       } elsif ($form->{creditlock}) {
950         $creditreadonly = "readonly";
951       }
952     }
953
954     my $projectnumber = SL::Presenter::Project::picker("project_id_$i", $form->{"project_id_$i"});
955     my $projectnumber_hidden = SL::Presenter::Tag::hidden_tag("project_id_$i", $form->{"project_id_$i"});
956
957     my $copy2credit = $i == 1 ? 'onkeyup="copy_debit_to_credit()"' : '';
958     my $balance     = $form->format_amount(\%::myconfig, $balances{$accno_id} // 0, 2, 'DRCR');
959
960     # if we have a bt_chart_id we disallow changing the amount of the bank account
961     if ($form->{bt_chart_id}) {
962       $debitreadonly = $creditreadonly = "readonly" if ($form->{"accno_id_$i"} eq $form->{bt_chart_id});
963       $copy2credit   = '' if $i == 1;   # and disallow copy2credit
964     }
965
966     print qq|<tr valign=top>
967     $accno
968     <td id="chart_balance_$i" align="right">${balance}</td>
969     $fx_transaction
970     <td><input name="debit_$i" size="8" value="$form->{"debit_$i"}" accesskey=$i $copy2credit $debitreadonly></td>
971     <td><input name="credit_$i" size=8 value="$form->{"credit_$i"}" $creditreadonly></td>
972     <td><input type="hidden" name="tax_$i" value="$form->{"tax_$i"}">$form->{"tax_$i"}</td>
973     $tax_ddbox|;
974
975     if ($form->{show_details}) {
976       print qq|
977     $source
978     $memo
979     <td>$projectnumber</td>
980 |;
981     } else {
982     print qq|
983     $source_hidden
984     $memo_hidden
985     $projectnumber_hidden
986     |;
987     }
988     print qq|
989   </tr>
990 |;
991   }
992
993   $form->hide_form(qw(rowcount selectaccno));
994
995   $main::lxdebug->leave_sub();
996
997 }
998
999 sub _get_radieren {
1000   return ($::instance_conf->get_gl_changeable == 2) ? ($::form->current_date(\%::myconfig) eq $::form->{gldate}) : ($::instance_conf->get_gl_changeable == 1);
1001 }
1002
1003 sub setup_gl_action_bar {
1004   my %params = @_;
1005   my $form   = $::form;
1006   my $change_never            = $::instance_conf->get_gl_changeable == 0;
1007   my $change_on_same_day_only = $::instance_conf->get_gl_changeable == 2 && ($form->current_date(\%::myconfig) ne $form->{gldate});
1008   my ($is_linked_bank_transaction, $is_linked_ap_transaction, $is_reconciled_bank_transaction);
1009
1010   if ($form->{id} && SL::DB::Manager::BankTransactionAccTrans->find_by(gl_id => $form->{id})) {
1011     $is_linked_bank_transaction = 1;
1012   }
1013   if ($form->{id} && SL::DB::Manager::ApGl->find_by(gl_id => $form->{id})) {
1014     $is_linked_ap_transaction = 1;
1015   }
1016   # dont edit reconcilated bookings!
1017   if ($form->{id}) {
1018     my @acc_trans = map { $_->acc_trans_id } @{ SL::DB::Manager::AccTransaction->get_all( where => [ trans_id => $form->{id} ] ) };
1019     if (scalar @acc_trans && scalar @{ SL::DB::Manager::ReconciliationLink->get_all(where => [ acc_trans_id  => [ @acc_trans ] ]) }) {
1020       $is_reconciled_bank_transaction = 1;
1021     }
1022   }
1023   my $create_post_action = sub {
1024     # $_[0]: description
1025     # $_[1]: after_action
1026     action => [
1027       $_[0],
1028       submit   => [ '#form', { action => 'post', after_action => $_[1] } ],
1029       disabled => $form->{locked}                           ? t8('The billing period has already been locked.')
1030                 : $form->{storno}                           ? t8('A canceled general ledger transaction cannot be posted.')
1031                 : ($form->{id} && $change_never)            ? t8('Changing general ledger transaction has been disabled in the configuration.')
1032                 : ($form->{id} && $change_on_same_day_only) ? t8('General ledger transactions can only be changed on the day they are posted.')
1033                 : $is_linked_bank_transaction               ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
1034                 : $is_linked_ap_transaction                 ? t8('This transaction is linked with a AP transaction. Please undo and redo the AP transaction booking if needed.')
1035                 : $is_reconciled_bank_transaction           ? t8('This transaction is reconciled with a bank transaction. Please undo the reconciliation if needed.')
1036                 : undef,
1037     ],
1038   };
1039
1040   my %post_entry;
1041   if ($::instance_conf->get_gl_add_doc && $::instance_conf->get_doc_storage) {
1042     %post_entry = (combobox => [ $create_post_action->(t8('Post'), 'doc-tab'),
1043                                  $create_post_action->(t8('Post and new booking')) ]);
1044   } elsif ($::instance_conf->get_doc_storage) {
1045     %post_entry = (combobox => [ $create_post_action->(t8('Post')),
1046                                  $create_post_action->(t8('Post and upload document'), 'doc-tab') ]);
1047   } else {
1048     %post_entry = $create_post_action->(t8('Post'));
1049   }
1050   push @{$post_entry{combobox}}, $create_post_action->(t8('Post and Close'), 'callback');
1051
1052   for my $bar ($::request->layout->get('actionbar')) {
1053     $bar->add(
1054       action => [
1055         t8('Update'),
1056         submit    => [ '#form', { action => 'update' } ],
1057         id        => 'update_button',
1058         accesskey => 'enter',
1059       ],
1060       %post_entry,
1061       combobox => [
1062         action => [ t8('Storno'),
1063           submit   => [ '#form', { action => 'storno' } ],
1064           confirm  => t8('Do you really want to cancel this general ledger transaction?'),
1065           disabled => !$form->{id}                ? t8('This general ledger transaction has not been posted yet.')
1066                     : $form->{storno}             ? t8('A canceled general ledger transaction cannot be canceled again.')
1067                     : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
1068                     : $is_linked_ap_transaction   ? t8('This transaction is linked with a AP transaction. Please undo and redo the AP transaction booking if needed.')
1069                     : $is_reconciled_bank_transaction ? t8('This transaction is reconciled with a bank transaction. Please undo the reconciliation if needed.')
1070                     : undef,
1071         ],
1072         action => [ t8('Delete'),
1073           submit   => [ '#form', { action => 'delete' } ],
1074           confirm  => t8('Do you really want to delete this object?'),
1075           disabled => !$form->{id}             ? t8('This invoice has not been posted yet.')
1076                     : $form->{locked}          ? t8('The billing period has already been locked.')
1077                     : $change_never            ? t8('Changing invoices has been disabled in the configuration.')
1078                     : $change_on_same_day_only ? t8('Invoices can only be changed on the day they are posted.')
1079                     : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
1080                     : $is_linked_ap_transaction   ? t8('This transaction is linked with a AP transaction. Please undo and redo the AP transaction booking if needed.')
1081                     : $is_reconciled_bank_transaction ? t8('This transaction is reconciled with a bank transaction. Please undo the reconciliation if needed.')
1082                     : $form->{storno}             ? t8('A canceled general ledger transaction cannot be deleted.')
1083                     : undef,
1084         ],
1085       ], # end of combobox "Storno"
1086
1087       combobox => [
1088         action => [ t8('Workflow') ],
1089         action => [
1090           t8('Use As New'),
1091           submit   => [ '#form', { action => "use_as_new" } ],
1092           checks   => [ 'kivi.validate_form' ],
1093           disabled => !$form->{id} ? t8('This general ledger transaction has not been posted yet.')
1094                     : undef,
1095         ],
1096       ], # end of combobox "Workflow"
1097
1098       combobox => [
1099         action => [ t8('more') ],
1100         action => [
1101           t8('History'),
1102           call     => [ 'set_history_window', $form->{id} * 1, 'glid' ],
1103           disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
1104         ],
1105         action => [
1106           t8('Follow-Up'),
1107           call     => [ 'follow_up_window' ],
1108           disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
1109         ],
1110         action => [
1111           t8('Record templates'),
1112           call => [ 'kivi.RecordTemplate.popup', 'gl_transaction' ],
1113         ],
1114         action => [
1115           t8('Drafts'),
1116           call     => [ 'kivi.Draft.popup', 'gl', 'unknown', $form->{draft_id}, $form->{draft_description} ],
1117           disabled => $form->{id}     ? t8('This invoice has already been posted.')
1118                     : $form->{locked} ? t8('The billing period has already been locked.')
1119                     : undef,
1120         ],
1121       ], # end of combobox "more"
1122     );
1123   }
1124 }
1125
1126 sub setup_gl_search_action_bar {
1127   my %params = @_;
1128
1129   for my $bar ($::request->layout->get('actionbar')) {
1130     $bar->add(
1131       action => [
1132         t8('Search'),
1133         submit    => [ '#form', { action => 'continue', nextsub => 'generate_report' } ],
1134         accesskey => 'enter',
1135       ],
1136     );
1137   }
1138 }
1139
1140 sub setup_gl_transactions_action_bar {
1141   my %params = @_;
1142
1143   for my $bar ($::request->layout->get('actionbar')) {
1144     $bar->add(
1145       combobox => [
1146         action => [ $::locale->text('Create new') ],
1147         action => [
1148           $::locale->text('GL Transaction'),
1149           submit => [ '#create_new_form', { action => 'gl_transaction' } ],
1150         ],
1151         action => [
1152           $::locale->text('AR Transaction'),
1153           submit => [ '#create_new_form', { action => 'ar_transaction' } ],
1154         ],
1155         action => [
1156           $::locale->text('AP Transaction'),
1157           submit => [ '#create_new_form', { action => 'ap_transaction' } ],
1158         ],
1159         action => [
1160           $::locale->text('Sales Invoice'),
1161           submit => [ '#create_new_form', { action => 'sales_invoice'  } ],
1162         ],
1163         action => [
1164           $::locale->text('Vendor Invoice'),
1165           submit => [ '#create_new_form', { action => 'vendor_invoice' } ],
1166         ],
1167       ], # end of combobox "Create new"
1168     );
1169   }
1170 }
1171
1172 sub form_header {
1173   $::lxdebug->enter_sub;
1174   $::auth->assert('gl_transactions');
1175
1176   my ($init) = @_;
1177
1178   $::request->layout->add_javascripts("autocomplete_chart.js", "autocomplete_project.js", "kivi.File.js", "kivi.GL.js", "kivi.RecordTemplate.js", "kivi.Validator.js", "show_history.js");
1179
1180   my @old_project_ids     = grep { $_ } map{ $::form->{"project_id_$_"} } 1..$::form->{rowcount};
1181   my @conditions          = @old_project_ids ? (id => \@old_project_ids) : ();
1182   $::form->{ALL_PROJECTS} = SL::DB::Manager::Project->get_all_sorted(query => [ or => [ active => 1, @conditions ]]);
1183
1184   $::form->get_lists(
1185     "charts"    => { "key" => "ALL_CHARTS", "transdate" => $::form->{transdate} },
1186   );
1187
1188   # we cannot book on charttype header
1189   @{ $::form->{ALL_CHARTS} } = grep { $_->{charttype} ne 'H' }  @{ $::form->{ALL_CHARTS} };
1190   $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
1191
1192   my $title      = $::form->{title};
1193   $::form->{title} = $::locale->text("$title General Ledger Transaction");
1194   # $locale->text('Add General Ledger Transaction')
1195   # $locale->text('Edit General Ledger Transaction')
1196
1197   map { $::form->{$_} =~ s/\"/&quot;/g }
1198     qw(chart taxchart);
1199
1200   if ($init) {
1201     $::request->{layout}->focus("#reference");
1202     $::form->{taxincluded} = "1";
1203   } else {
1204     $::request->{layout}->focus("#accno_id_$::form->{rowcount}_name");
1205   }
1206
1207   $::form->{previous_id}     ||= "--";
1208   $::form->{previous_gldate} ||= "--";
1209
1210   setup_gl_action_bar();
1211
1212   $::form->header;
1213   print $::form->parse_html_template('gl/form_header', {
1214     hide_title => $title,
1215     readonly   => $::form->{id} && ($::form->{locked} || !_get_radieren()),
1216   });
1217
1218   $::lxdebug->leave_sub;
1219
1220 }
1221
1222 sub form_footer {
1223   $::lxdebug->enter_sub;
1224   $::auth->assert('gl_transactions');
1225
1226   my ($follow_ups, $follow_ups_due);
1227
1228   if ($::form->{id}) {
1229     $follow_ups     = FU->follow_ups('trans_id' => $::form->{id}, 'not_done' => 1);
1230     $follow_ups_due = sum map { $_->{due} * 1 } @{ $follow_ups || [] };
1231   }
1232
1233   print $::form->parse_html_template('gl/form_footer', {
1234     radieren       => _get_radieren(),
1235     follow_ups     => $follow_ups,
1236     follow_ups_due => $follow_ups_due,
1237   });
1238
1239   $::lxdebug->leave_sub;
1240 }
1241
1242 sub delete {
1243   $main::lxdebug->enter_sub();
1244
1245   my $form     = $main::form;
1246   my %myconfig = %main::myconfig;
1247   my $locale   = $main::locale;
1248
1249   if (GL->delete_transaction(\%myconfig, \%$form)){
1250     # saving the history
1251       if(!exists $form->{addition} && $form->{id} ne "") {
1252         $form->{snumbers} = qq|gltransaction_| . $form->{id};
1253         $form->{addition} = "DELETED";
1254         $form->{what_done} = "gl_transaction";
1255         $form->save_history;
1256       }
1257     # /saving the history
1258     $form->redirect($locale->text('Transaction deleted!'))
1259   }
1260   $form->error($locale->text('Cannot delete transaction!'));
1261   $main::lxdebug->leave_sub();
1262
1263 }
1264
1265 sub post_transaction {
1266   $main::lxdebug->enter_sub();
1267
1268   my $form     = $main::form;
1269   my %myconfig = %main::myconfig;
1270   my $locale   = $main::locale;
1271
1272   # check if there is something in reference and date
1273   $form->isblank("reference",               $locale->text('Reference missing!'));
1274   $form->isblank("transdate",               $locale->text('Transaction Date missing!'));
1275   $form->isblank("description",             $locale->text('Description missing!'));
1276   $form->isblank("transaction_description", $locale->text('A transaction description is required.')) if $::instance_conf->get_require_transaction_description_ps;
1277
1278   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
1279   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
1280
1281   my @a           = ();
1282   my $count       = 0;
1283   my $debittax    = 0;
1284   my $credittax   = 0;
1285   my $debitcount  = 0;
1286   my $creditcount = 0;
1287   my $debitcredit;
1288   my %split_safety = ();
1289
1290   my $dbh = SL::DB->client->dbh;
1291   my ($notax_id) = selectrow_query($form, $dbh, "SELECT id FROM tax WHERE taxkey = 0 LIMIT 1", );
1292   my $zerotaxes  = selectall_hashref_query($form, $dbh, "SELECT id FROM tax WHERE rate = 0", );
1293
1294   my @flds = qw(accno_id debit credit projectnumber fx_transaction source memo tax taxchart);
1295
1296   for my $i (1 .. $form->{rowcount}) {
1297     next if $form->{"debit_$i"} eq "" && $form->{"credit_$i"} eq "";
1298
1299     for (qw(debit credit tax)) {
1300       $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"});
1301     }
1302
1303     push @a, {};
1304     $debitcredit = ($form->{"debit_$i"} == 0) ? "0" : "1";
1305
1306     $split_safety{   $form->{"debit_$i"}  <=> 0 }++;
1307     $split_safety{ - $form->{"credit_$i"} <=> 0 }++;
1308
1309     if ($debitcredit) {
1310       $debitcount++;
1311     } else {
1312       $creditcount++;
1313     }
1314
1315     if (($debitcount >= 2) && ($creditcount == 2)) {
1316       $form->{"credit_$i"} = 0;
1317       $form->{"tax_$i"}    = 0;
1318       $creditcount--;
1319       $form->{creditlock} = 1;
1320     }
1321     if (($creditcount >= 2) && ($debitcount == 2)) {
1322       $form->{"debit_$i"} = 0;
1323       $form->{"tax_$i"}   = 0;
1324       $debitcount--;
1325       $form->{debitlock} = 1;
1326     }
1327     if (($creditcount == 1) && ($debitcount == 2)) {
1328       $form->{creditlock} = 1;
1329     }
1330     if (($creditcount == 2) && ($debitcount == 1)) {
1331       $form->{debitlock} = 1;
1332     }
1333     if ($debitcredit && $credittax) {
1334       $form->{"taxchart_$i"} = "$notax_id--0.00000";
1335     }
1336     if (!$debitcredit && $debittax) {
1337       $form->{"taxchart_$i"} = "$notax_id--0.00000";
1338     }
1339     my $amount = ($form->{"debit_$i"} == 0)
1340             ? $form->{"credit_$i"}
1341             : $form->{"debit_$i"};
1342     my $j = $#a;
1343     if (($debitcredit && $credittax) || (!$debitcredit && $debittax)) {
1344       $form->{"taxchart_$i"} = "$notax_id--0.00000";
1345       $form->{"tax_$i"}      = 0;
1346     }
1347     my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
1348     my $iswithouttax = grep { $_->{id} == $taxkey } @{ $zerotaxes };
1349     if (!$iswithouttax) {
1350       if ($debitcredit) {
1351         $debittax = 1;
1352       } else {
1353         $credittax = 1;
1354       }
1355
1356       my ($tmpnetamount,$tmpdiff);
1357       ($tmpnetamount,$form->{"tax_$i"},$tmpdiff) = $form->calculate_tax($amount,$rate,$form->{taxincluded} *= 1,2);
1358       if ($debitcredit) {
1359         $form->{"debit_$i"} = $tmpnetamount;
1360       } else {
1361         $form->{"credit_$i"} = $tmpnetamount;
1362       }
1363
1364     } else {
1365       $form->{"tax_$i"} = 0;
1366     }
1367
1368     for (@flds) { $a[$j]->{$_} = $form->{"${_}_$i"} }
1369     $count++;
1370   }
1371
1372   if ($split_safety{-1} > 1 && $split_safety{1} > 1) {
1373     $::form->error($::locale->text("Split entry detected. The values you have entered will result in an entry with more than one position on both debit and credit. " .
1374                                    "Due to known problems involving accounting software kivitendo does not allow these."));
1375   }
1376
1377   for my $i (1 .. $count) {
1378     my $j = $i - 1;
1379     for (@flds) { $form->{"${_}_$i"} = $a[$j]->{$_} }
1380   }
1381
1382   for my $i ($count + 1 .. $form->{rowcount}) {
1383     for (@flds) { delete $form->{"${_}_$i"} }
1384   }
1385
1386   my ($debit, $credit, $taxtotal);
1387   for my $i (1 .. $form->{rowcount}) {
1388     my $dr  = $form->{"debit_$i"};
1389     my $cr  = $form->{"credit_$i"};
1390     my $tax = $form->{"tax_$i"};
1391     if ($dr && $cr) {
1392       $form->error($locale->text('Cannot post transaction with a debit and credit entry for the same account!'));
1393     }
1394     $debit    += $dr + $tax if $dr;
1395     $credit   += $cr + $tax if $cr;
1396     $taxtotal += $tax if $form->{taxincluded}
1397   }
1398
1399   $form->{taxincluded} = 0 if !$taxtotal;
1400
1401   # this is just for the wise guys
1402
1403   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
1404     if ($form->date_max_future($form->{"transdate"}, \%myconfig));
1405   $form->error($locale->text('Cannot post transaction for a closed period!'))
1406     if ($form->date_closed($form->{"transdate"}, \%myconfig));
1407   if ($form->round_amount($debit, 2) != $form->round_amount($credit, 2)) {
1408     $form->error($locale->text('Out of balance transaction!'));
1409   }
1410
1411   if ($form->round_amount($debit, 2) + $form->round_amount($credit, 2) == 0) {
1412     $form->error($locale->text('Empty transaction!'));
1413   }
1414
1415
1416   # start transaction (post + history + (optional) banktrans)
1417   SL::DB->client->with_transaction(sub {
1418
1419     if ((my $errno = GL->post_transaction(\%myconfig, \%$form)) <= -1) {
1420       $errno *= -1;
1421       my @err;
1422       $err[1] = $locale->text('Cannot have a value in both Debit and Credit!');
1423       $err[2] = $locale->text('Debit and credit out of balance!');
1424       $err[3] = $locale->text('Cannot post a transaction without a value!');
1425
1426       die $err[$errno];
1427     }
1428     # saving the history
1429     if(!exists $form->{addition} && $form->{id} ne "") {
1430       $form->{snumbers} = qq|gltransaction_| . $form->{id};
1431       $form->{addition} = "POSTED";
1432       $form->{what_done} = "gl transaction";
1433       $form->save_history;
1434     }
1435
1436     # Case BankTransaction: update RecordLink and BankTransaction
1437     if ($form->{callback} =~ /BankTransaction/ && $form->{bt_id}) {
1438       # set invoice_amount - we only rely on bt_id in form, do all other stuff ui independent
1439       # die if we have a unlogic or NYI case and abort the whole transaction
1440       my ($bt, $chart_id, $payment);
1441       require SL::DB::Manager::BankTransaction;
1442
1443       $bt = SL::DB::Manager::BankTransaction->find_by(id => $::form->{bt_id});
1444       die "No bank transaction found" unless $bt;
1445
1446       $chart_id = SL::DB::Manager::BankAccount->find_by(id => $bt->local_bank_account_id)->chart_id;
1447       die "no chart id" unless $chart_id;
1448
1449       $payment = SL::DB::Manager::AccTransaction->get_all(where => [ trans_id => $::form->{id},
1450                                                                      chart_link => { like => '%_paid%' },
1451                                                                      chart_id => $chart_id                  ]);
1452       die "guru meditation error: Can only assign amount to one bank account booking" if scalar @{ $payment } > 1;
1453
1454       # credit/debit * -1 matches the sign for bt.amount and bt.invoice_amount
1455
1456       die "Can only assign the full (partial) bank amount to a single general ledger booking: " . $bt->not_assigned_amount . " " .  ($payment->[0]->amount * -1)
1457         unless (abs($bt->not_assigned_amount - ($payment->[0]->amount * -1)) < 0.001);
1458
1459       $bt->update_attributes(invoice_amount => $bt->invoice_amount + ($payment->[0]->amount * -1));
1460
1461       # create record_link
1462       my %props = (
1463         from_table => 'bank_transactions',
1464         from_id    => $::form->{bt_id},
1465         to_table   => 'gl',
1466         to_id      => $::form->{id},
1467       );
1468       SL::DB::RecordLink->new(%props)->save;
1469       # and tighten holy acc_trans_id for this bank_transaction
1470       my  %props_acc = (
1471         acc_trans_id        => $payment->[0]->acc_trans_id,
1472         bank_transaction_id => $bt->id,
1473         gl_id               => $payment->[0]->trans_id,
1474       );
1475       my $bta = SL::DB::BankTransactionAccTrans->new(%props_acc);
1476       $bta->save;
1477
1478     }
1479     1;
1480   }) or do { die SL::DB->client->error };
1481
1482   $main::lxdebug->leave_sub();
1483 }
1484
1485 sub post {
1486   $main::lxdebug->enter_sub();
1487
1488   $main::auth->assert('gl_transactions');
1489
1490   my $form     = $main::form;
1491   my $locale   = $main::locale;
1492
1493   if ($::myconfig{mandatory_departments} && !$form->{department_id}) {
1494     $form->error($locale->text('You have to specify a department.'));
1495   }
1496
1497   $form->{title}  = $locale->text("$form->{title} General Ledger Transaction");
1498   $form->{storno} = 0;
1499
1500   post_transaction();
1501
1502   if ($::instance_conf->get_webdav) {
1503     SL::Webdav->new(type     => 'general_ledger',
1504                     number   => $form->{id},
1505                    )->webdav_path;
1506   }
1507
1508   if ($form->{email_journal_id} && $form->{id} ne "") {
1509     my $ar_transaction = SL::DB::GLTransaction->new(id => $form->{id})->load;
1510     my $email_journal = SL::DB::EmailJournal->new(
1511       id => delete $form->{email_journal_id}
1512     )->load;
1513     $email_journal->link_to_record_with_attachment($ar_transaction, delete $::form->{email_attachment_id});
1514   }
1515
1516   my $msg = $::locale->text("General ledger transaction '#1' posted (ID: #2)", $form->{reference}, $form->{id});
1517   if ($form->{callback} =~ /BankTransaction/ && $form->{bt_id}) {
1518     SL::Helper::Flash::flash_later('info', $msg) if $msg;
1519     print $::form->redirect_header($form->{callback});
1520   } elsif ('doc-tab' eq $form->{after_action}) {
1521     # Redirect with callback containing a fragment does not work (by now)
1522     # because the callback info is stored in the session an parsing the
1523     # callback parameters does not support fragments (see SL::Form::redirect).
1524     # So use flash_later for the message and redirect_headers for redirecting.
1525     my $add_doc_url = build_std_url("script=gl.pl", 'action=edit', 'id=' . E($form->{id}), 'fragment=ui-tabs-docs');
1526     SL::Helper::Flash::flash_later('info', $msg);
1527     print $form->redirect_header($add_doc_url);
1528     $::dispatcher->end_request;
1529   } elsif ('callback' eq $form->{after_action}) {
1530     my $callback = $form->{callback}
1531       || "controller.pl?action=LoginScreen/user_login";
1532     SL::Helper::Flash::flash_later('info', $msg);
1533     print $form->redirect_header($callback);
1534     $::dispatcher->end_request;
1535   } else {
1536     $form->{callback} = build_std_url("action=add", "show_details");
1537     $form->redirect($msg);
1538   }
1539
1540   $main::lxdebug->leave_sub();
1541 }
1542
1543 sub storno {
1544   $main::lxdebug->enter_sub();
1545
1546   $main::auth->assert('gl_transactions');
1547
1548   my $form     = $main::form;
1549   my %myconfig = %main::myconfig;
1550   my $locale   = $main::locale;
1551
1552   # don't cancel cancelled transactions
1553   if (IS->has_storno(\%myconfig, $form, 'gl')) {
1554     $form->{title} = $locale->text("Cancel Accounts Receivables Transaction");
1555     $form->error($locale->text("Transaction has already been cancelled!"));
1556   }
1557
1558   GL->storno($form, \%myconfig, $form->{id});
1559
1560   # saving the history
1561   if(!exists $form->{addition} && $form->{id} ne "") {
1562     $form->{snumbers} = qq|gltransaction_| . $form->{id};
1563     $form->{addition} = "STORNO";
1564     $form->{what_done} = "gl_transaction";
1565     $form->save_history;
1566   }
1567   # /saving the history
1568
1569   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
1570
1571   $main::lxdebug->leave_sub();
1572 }
1573
1574 sub use_as_new {
1575   $::auth->assert('gl_transactions');
1576
1577   $::form->{email_journal_id}    = delete $::form->{workflow_email_journal_id};
1578   $::form->{email_attachment_id} = delete $::form->{workflow_email_attachment_id};
1579   $::form->{callback}            = delete $::form->{workflow_email_callback};
1580
1581   delete $::form->{$_} for qw(id gldate tax_point deliverydate storno);
1582
1583   $::form->{title}     = "Add";
1584   $::form->{transdate} = DateTime->today_local->to_kivitendo;
1585
1586   $::form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_GL_TRANSACTION_POST())->token;
1587
1588   update();
1589 }
1590
1591 sub continue {
1592   call_sub($main::form->{nextsub});
1593 }
1594
1595 sub get_tax_dropdown {
1596   my $transdate    = $::form->{transdate}    ? DateTime->from_kivitendo($::form->{transdate}) : DateTime->today_local;
1597   my $deliverydate = $::form->{deliverydate} ? DateTime->from_kivitendo($::form->{deliverydate}) : undef;
1598   my @tax_accounts = GL->get_active_taxes_for_chart($::form->{accno_id}, $deliverydate // $transdate);
1599   my $html         = $::form->parse_html_template("gl/update_tax_accounts", { TAX_ACCOUNTS => \@tax_accounts });
1600
1601   print $::form->ajax_response_header, $html;
1602 }
1603
1604 sub get_chart_balance {
1605   my %balances = GL->get_chart_balances($::form->{accno_id});
1606   my $balance  = $::form->format_amount(\%::myconfig, $balances{ $::form->{accno_id} }, 2, 'DRCR');
1607
1608   print $::form->ajax_response_header, $balance;
1609 }
1610
1611 1;