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