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