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