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