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