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