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