1 #=====================================================================
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (c) 1998-2002
11 # Author: Dieter Simader
12 # Email: dsimader@sql-ledger.org
13 # Web: http://www.sql-ledger.org
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.
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,
29 #======================================================================
33 #======================================================================
38 use POSIX qw(strftime);
39 use List::Util qw(first sum);
42 use SL::DB::RecordTemplate;
43 use SL::DB::ReconciliationLink;
44 use SL::DB::BankTransactionAccTrans;
48 use SL::Helper::Flash qw(flash flash_later);
50 use SL::ReportGenerator;
51 use SL::DBUtils qw(selectrow_query selectall_hashref_query);
53 use SL::Locale::String qw(t8);
54 use SL::Helper::GlAttachments qw(count_gl_attachments);
55 use SL::Presenter::Tag;
56 use SL::Presenter::Chart;
57 require "bin/mozilla/common.pl";
58 require "bin/mozilla/reportgenerator.pl";
60 # this is for our long dates
61 # $locale->text('January')
62 # $locale->text('February')
63 # $locale->text('March')
64 # $locale->text('April')
65 # $locale->text('May ')
66 # $locale->text('June')
67 # $locale->text('July')
68 # $locale->text('August')
69 # $locale->text('September')
70 # $locale->text('October')
71 # $locale->text('November')
72 # $locale->text('December')
74 # this is for our short month
75 # $locale->text('Jan')
76 # $locale->text('Feb')
77 # $locale->text('Mar')
78 # $locale->text('Apr')
79 # $locale->text('May')
80 # $locale->text('Jun')
81 # $locale->text('Jul')
82 # $locale->text('Aug')
83 # $locale->text('Sep')
84 # $locale->text('Oct')
85 # $locale->text('Nov')
86 # $locale->text('Dec')
88 sub load_record_template {
89 $::auth->assert('gl_transactions');
91 # Load existing template and verify that its one for this module.
92 my $template = SL::DB::RecordTemplate
93 ->new(id => $::form->{id})
95 with_object => [ qw(customer payment currency record_items record_items.chart) ],
98 die "invalid template type" unless $template->template_type eq 'gl_transaction';
100 $template->substitute_variables;
101 my $payment_suggestion = $::form->{form_defaults}->{amount_1};
103 # Clean the current $::form before rebuilding it from the template.
104 my $form_defaults = delete $::form->{form_defaults};
105 delete @{ $::form }{ grep { !m{^(?:script|login)$}i } keys %{ $::form } };
108 GL->transaction(\%::myconfig, $dummy_form);
110 # Fill $::form from the template.
111 my $today = DateTime->today_local;
112 $::form->{title} = "Add";
113 $::form->{transdate} = $today->to_kivitendo;
114 $::form->{duedate} = $today->to_kivitendo;
115 $::form->{rowcount} = @{ $template->items };
116 $::form->{paidaccounts} = 1;
117 $::form->{$_} = $template->$_ for qw(department_id taxincluded ob_transaction cb_transaction reference description show_details transaction_description);
118 $::form->{$_} = $dummy_form->{$_} for qw(closedto revtrans previous_id previous_gldate);
121 foreach my $item (@{ $template->items }) {
124 my $active_taxkey = $item->chart->get_active_taxkey;
125 my $taxes = SL::DB::Manager::Tax->get_all(
126 where => [ chart_categories => { like => '%' . $item->chart->category . '%' }],
127 sort_by => 'taxkey, rate',
130 my $tax = first { $item->tax_id == $_->id } @{ $taxes };
131 $tax //= first { $active_taxkey->tax_id == $_->id } @{ $taxes };
132 $tax //= $taxes->[0];
139 $::form->{"accno_id_${row}"} = $item->chart_id;
140 $::form->{"previous_accno_id_${row}"} = $item->chart_id;
141 $::form->{"debit_${row}"} = $::form->format_amount(\%::myconfig, ($payment_suggestion ? $payment_suggestion : $item->amount1), 2) if $item->amount1 * 1;
142 $::form->{"credit_${row}"} = $::form->format_amount(\%::myconfig, ($payment_suggestion ? $payment_suggestion : $item->amount2), 2) if $item->amount2 * 1;
143 $::form->{"taxchart_${row}"} = $item->tax_id . '--' . $tax->rate;
144 $::form->{"${_}_${row}"} = $item->$_ for qw(source memo project_id);
147 $::form->{$_} = $form_defaults->{$_} for keys %{ $form_defaults // {} };
149 flash('info', $::locale->text("The record template '#1' has been loaded.", $template->template_name));
152 keep_rows_without_amount => 1,
153 dont_add_new_row => 1,
157 sub save_record_template {
158 $::auth->assert('gl_transactions');
160 my $template = $::form->{record_template_id} ? SL::DB::RecordTemplate->new(id => $::form->{record_template_id})->load : SL::DB::RecordTemplate->new;
161 my $js = SL::ClientJS->new(controller => SL::Controller::Base->new);
162 my $new_name = $template->template_name_to_use($::form->{record_template_new_template_name});
163 $js->dialog->close('#record_template_dialog');
166 # bank transactions need amounts for assignment
168 $can_save = 1 if ($::form->{credit_1} > 0 && $::form->{debit_2} > 0 && $::form->{credit_2} == 0 && $::form->{debit_1} == 0);
169 $can_save = 1 if ($::form->{credit_2} > 0 && $::form->{debit_1} > 0 && $::form->{credit_1} == 0 && $::form->{debit_2} == 0);
170 return $js->flash('error', t8('Can only save template if amounts,i.e. 1 for debit and credit are set.'))->render unless $can_save;
173 $_->{chart_id} && (($_->{tax_id} // '') ne '')
175 +{ chart_id => $::form->{"accno_id_${_}"},
176 amount1 => $::form->parse_amount(\%::myconfig, $::form->{"debit_${_}"}),
177 amount2 => $::form->parse_amount(\%::myconfig, $::form->{"credit_${_}"}),
178 tax_id => (split m{--}, $::form->{"taxchart_${_}"})[0],
179 project_id => $::form->{"project_id_${_}"} || undef,
180 source => $::form->{"source_${_}"},
181 memo => $::form->{"memo_${_}"},
183 } (1..($::form->{rowcount} || 1));
185 $template->assign_attributes(
186 template_type => 'gl_transaction',
187 template_name => $new_name,
189 currency_id => $::instance_conf->get_currency_id,
190 department_id => $::form->{department_id} || undef,
191 project_id => $::form->{globalproject_id} || undef,
192 taxincluded => $::form->{taxincluded} ? 1 : 0,
193 ob_transaction => $::form->{ob_transaction} ? 1 : 0,
194 cb_transaction => $::form->{cb_transaction} ? 1 : 0,
195 reference => $::form->{reference},
196 description => $::form->{description},
197 show_details => $::form->{show_details},
198 transaction_description => $::form->{transaction_description},
208 ->flash('error', $::locale->text("Saving the record template '#1' failed.", $new_name))
213 ->flash('info', $::locale->text("The record template '#1' has been saved.", $new_name))
218 $main::lxdebug->enter_sub();
220 $main::auth->assert('gl_transactions');
222 my $form = $main::form;
223 my %myconfig = %main::myconfig;
225 $form->{title} = "Add";
227 $form->{callback} = "gl.pl?action=add" unless $form->{callback};
229 # we use this only to set a default date
230 # yep. aber er holt hier auch schon ALL_CHARTS. Aufwand / Nutzen? jb
231 GL->transaction(\%myconfig, \%$form);
233 $form->{rowcount} = 2;
239 $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
241 $form->{show_details} = $myconfig{show_form_details} unless defined $form->{show_details};
244 $main::lxdebug->leave_sub();
248 sub prepare_transaction {
249 $main::lxdebug->enter_sub();
251 $main::auth->assert('gl_transactions');
253 my $form = $main::form;
254 my %myconfig = %main::myconfig;
256 GL->transaction(\%myconfig, \%$form);
258 $form->{amount} = $form->format_amount(\%myconfig, $form->{amount}, 2);
260 $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
265 foreach my $ref (@{ $form->{GL} }) {
267 if ($tax && ($ref->{accno} eq $taxaccno)) {
268 $form->{"tax_$j"} = abs($ref->{amount});
269 $form->{"taxchart_$j"} = $ref->{id} . "--" . $ref->{taxrate};
270 if ($form->{taxincluded}) {
271 if ($ref->{amount} < 0) {
272 $form->{"debit_$j"} += $form->{"tax_$j"};
274 $form->{"credit_$j"} += $form->{"tax_$j"};
277 $form->{"project_id_$j"} = $ref->{project_id};
280 $form->{"accno_id_$i"} = $ref->{chart_id};
281 for (qw(fx_transaction source memo)) { $form->{"${_}_$i"} = $ref->{$_} }
282 if ($ref->{amount} < 0) {
283 $form->{totaldebit} -= $ref->{amount};
284 $form->{"debit_$i"} = $ref->{amount} * -1;
286 $form->{totalcredit} += $ref->{amount};
287 $form->{"credit_$i"} = $ref->{amount};
289 $form->{"taxchart_$i"} = $ref->{id}."--0.00000";
290 $form->{"project_id_$i"} = $ref->{project_id};
293 if ($ref->{taxaccno} && !$tax) {
294 $taxaccno = $ref->{taxaccno};
302 $form->{rowcount} = $i;
304 ($form->datetonum($form->{transdate}, \%myconfig) <=
305 $form->datetonum($form->{closedto}, \%myconfig));
307 $main::lxdebug->leave_sub();
311 $main::lxdebug->enter_sub();
313 $main::auth->assert('gl_transactions');
315 my $form = $main::form;
316 my %myconfig = %main::myconfig;
318 prepare_transaction();
320 $form->{title} = "Edit";
322 $form->{show_details} = $myconfig{show_form_details} unless defined $form->{show_details};
324 if ($form->{id} && $::instance_conf->get_webdav) {
325 my $webdav = SL::Webdav->new(
326 type => 'general_ledger',
327 number => $form->{id},
329 my @all_objects = $webdav->get_all_objects;
330 @{ $form->{WEBDAV} } = map { { name => $_->filename,
332 link => File::Spec->catfile($_->full_filedescriptor),
339 $main::lxdebug->leave_sub();
344 $::lxdebug->enter_sub;
345 $::auth->assert('general_ledger | gl_transactions');
348 projects => { key => "ALL_PROJECTS", all => 1 },
350 $::form->{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]);
351 $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
353 setup_gl_search_action_bar();
356 print $::form->parse_html_template('gl/search', {
357 employee_label => sub { "$_[0]{id}--$_[0]{name}" },
360 $::lxdebug->leave_sub;
363 sub create_subtotal_row {
364 $main::lxdebug->enter_sub();
366 my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
368 my $form = $main::form;
369 my %myconfig = %main::myconfig;
371 my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
373 map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
375 map { $totals->{$_} = 0 } @{ $subtotal_columns };
377 $main::lxdebug->leave_sub();
382 sub generate_report {
383 $main::lxdebug->enter_sub();
385 $main::auth->assert('general_ledger | gl_transactions');
387 my $form = $main::form;
388 my %myconfig = %main::myconfig;
389 my $locale = $main::locale;
391 # 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
393 # <form method=post action=gl.pl>
394 # <input type=hidden name=sort value=datesort> # form->{sort} setzen
395 # <input type=hidden name=nextsub value=generate_report>
397 # anhand von neuer Variable datesort wird jetzt $form->{sort} auf transdate oder gldate gesetzt
398 # damit ist die Hidden Variable "sort" wahrscheinlich sogar überflüssig
400 # ändert man die Sortierreihenfolge per Klick auf eine der Überschriften wird die Variable "sort" per GET übergeben, z.B. id,transdate, gldate, ...
401 # 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
403 if ( $form->{sort} eq 'datesort' ) { # sollte bei einem Post (Aufruf aus Suchmaske) immer wahr sein
404 # je nachdem ob in Suchmaske "transdate" oder "gldate" ausgesucht wurde erstes Suchergebnis entsprechend sortieren
405 $form->{sort} = $form->{datesort};
409 report_generator_set_default_sort("$form->{datesort}", 1);
410 # report_generator_set_default_sort('transdate', 1);
412 GL->all_transactions(\%myconfig, \%$form);
414 my %acctype = ('A' => $locale->text('Asset'),
415 'C' => $locale->text('Contra'),
416 'L' => $locale->text('Liability'),
417 'Q' => $locale->text('Equity'),
418 'I' => $locale->text('Revenue'),
419 'E' => $locale->text('Expense'),);
421 $form->{title} = $locale->text('Journal');
422 if ($form->{category} ne 'X') {
423 $form->{title} .= " : " . $locale->text($acctype{ $form->{category} });
426 $form->{landscape} = 1;
428 my $ml = ($form->{ml} =~ /(A|E|Q)/) ? -1 : 1;
431 transdate gldate id reference
432 description notes transaction_description source
433 doccnt debit debit_accno
434 credit credit_accno debit_tax debit_tax_accno
435 credit_tax credit_tax_accno balance projectnumbers
439 # add employee here, so that variable is still known and passed in url when choosing a different sort order in resulting table
440 my @hidden_variables = qw(accno source reference description notes project_id datefrom dateto employee_id datesort category l_subtotal department_id transaction_description);
441 push @hidden_variables, map { "l_${_}" } @columns;
443 my $employee = $form->{employee_id} ? SL::DB::Employee->new(id => $form->{employee_id})->load->name : '';
445 my (@options, @date_options);
446 push @options, $locale->text('Account') . " : $form->{accno} $form->{account_description}" if ($form->{accno});
447 push @options, $locale->text('Source') . " : $form->{source}" if ($form->{source});
448 push @options, $locale->text('Reference') . " : $form->{reference}" if ($form->{reference});
449 push @options, $locale->text('Description') . " : $form->{description}" if ($form->{description});
450 push @options, $locale->text('Notes') . " : $form->{notes}" if ($form->{notes});
451 push @options, $locale->text('Transaction description') . " : $form->{transaction_description}" if $form->{transaction_description};
452 push @options, $locale->text('Employee') . " : $employee" if $employee;
453 my $datesorttext = $form->{datesort} eq 'transdate' ? $locale->text('Transdate') : $locale->text('Gldate');
454 push @date_options, "$datesorttext" if ($form->{datesort} and ($form->{datefrom} or $form->{dateto}));
455 push @date_options, $locale->text('From'), $locale->date(\%myconfig, $form->{datefrom}, 1) if ($form->{datefrom});
456 push @date_options, $locale->text('Bis'), $locale->date(\%myconfig, $form->{dateto}, 1) if ($form->{dateto});
457 push @options, join(' ', @date_options) if (scalar @date_options);
459 if ($form->{department_id}) {
460 my $department = SL::DB::Manager::Department->find_by( id => $form->{department_id} );
461 push @options, $locale->text('Department') . " : " . $department->description;
464 my $callback = build_std_url('action=generate_report', grep { $form->{$_} } @hidden_variables);
466 $form->{l_credit_accno} = 'Y';
467 $form->{l_debit_accno} = 'Y';
468 $form->{l_credit_tax} = 'Y';
469 $form->{l_debit_tax} = 'Y';
470 # $form->{l_gldate} = 'Y'; # Spalte mit gldate immer anzeigen
471 $form->{l_credit_tax_accno} = 'Y';
472 $form->{l_datesort} = 'Y';
473 $form->{l_debit_tax_accno} = 'Y';
474 $form->{l_balance} = $form->{accno} ? 'Y' : '';
475 $form->{l_doccnt} = $form->{l_source} ? 'Y' : '';
478 'id' => { 'text' => $locale->text('ID'), },
479 'transdate' => { 'text' => $locale->text('Transdate'), },
480 'gldate' => { 'text' => $locale->text('Gldate'), },
481 'reference' => { 'text' => $locale->text('Reference'), },
482 'source' => { 'text' => $locale->text('Source'), },
483 'doccnt' => { 'text' => $locale->text('Document Count'), },
484 'description' => { 'text' => $locale->text('Description'), },
485 'notes' => { 'text' => $locale->text('Notes'), },
486 'debit' => { 'text' => $locale->text('Debit'), },
487 'debit_accno' => { 'text' => $locale->text('Debit Account'), },
488 'credit' => { 'text' => $locale->text('Credit'), },
489 'credit_accno' => { 'text' => $locale->text('Credit Account'), },
490 'debit_tax' => { 'text' => $locale->text('Debit Tax'), },
491 'debit_tax_accno' => { 'text' => $locale->text('Debit Tax Account'), },
492 'credit_tax' => { 'text' => $locale->text('Credit Tax'), },
493 'credit_tax_accno' => { 'text' => $locale->text('Credit Tax Account'), },
494 'balance' => { 'text' => $locale->text('Balance'), },
495 'projectnumbers' => { 'text' => $locale->text('Project Numbers'), },
496 'department' => { 'text' => $locale->text('Department'), },
497 'employee' => { 'text' => $locale->text('Employee'), },
498 'transaction_description' => { 'text' => $locale->text('Transaction description'), },
501 foreach my $name (qw(id transdate gldate reference description debit_accno credit_accno debit_tax_accno credit_tax_accno department transaction_description)) {
502 my $sortname = $name =~ m/accno/ ? 'accno' : $name;
503 my $sortdir = $sortname eq $form->{sort} ? 1 - $form->{sortdir} : $form->{sortdir};
504 $column_defs{$name}->{link} = $callback . "&sort=$sortname&sortdir=$sortdir";
507 map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
508 map { $column_defs{$_}->{visible} = 0 } qw(debit_accno credit_accno debit_tax_accno credit_tax_accno) if $form->{accno};
510 my %column_alignment;
511 map { $column_alignment{$_} = 'right' } qw(balance id debit credit debit_tax credit_tax balance);
512 map { $column_alignment{$_} = 'center' } qw(transdate gldate reference debit_accno credit_accno debit_tax_accno credit_tax_accno);
513 map { $column_alignment{$_} = 'left' } qw(description source notes);
514 map { $column_defs{$_}->{align} = $column_alignment{$_} } keys %column_alignment;
516 my $report = SL::ReportGenerator->new(\%myconfig, $form);
518 $report->set_columns(%column_defs);
519 $report->set_column_order(@columns);
521 $form->{l_attachments} = 'Y';
522 $report->set_export_options('generate_report', @hidden_variables, qw(sort sortdir l_attachments));
524 $report->set_sort_indicator($form->{sort} eq 'accno' ? 'debit_accno' : $form->{sort}, $form->{sortdir});
526 $report->set_options('top_info_text' => join("\n", @options),
527 'output_format' => 'HTML',
528 'title' => $form->{title},
529 'attachment_basename' => $locale->text('general_ledger_list') . strftime('_%Y%m%d', localtime time),
531 $report->set_options_from_form();
532 $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
534 # add sort to callback
535 $form->{callback} = "$callback&sort=" . E($form->{sort}) . "&sortdir=" . E($form->{sortdir});
538 my @totals_columns = qw(debit credit debit_tax credit_tax);
539 my %subtotals = map { $_ => 0 } @totals_columns;
540 my %totals = map { $_ => 0 } @totals_columns;
543 foreach my $ref (@{ $form->{GL} }) {
547 foreach my $key (qw(debit credit debit_tax credit_tax)) {
549 foreach my $idx (sort keys(%{ $ref->{$key} })) {
550 my $value = $ref->{$key}->{$idx};
551 $subtotals{$key} += $value;
552 $totals{$key} += $value;
553 if ($key =~ /debit.*/) {
558 $form->{balance} = $form->{balance} + $value * $ml;
559 push @{ $rows{$key} }, $form->format_amount(\%myconfig, $value, 2);
563 foreach my $key (qw(debit_accno credit_accno debit_tax_accno credit_tax_accno ac_transdate source)) {
564 my $col = $key eq 'ac_transdate' ? 'transdate' : $key;
565 $rows{$col} = [ map { $ref->{$key}->{$_} } sort keys(%{ $ref->{$key} }) ];
569 map { $row->{$_} = { 'data' => '', 'align' => $column_alignment{$_} } } @columns;
571 if ( $form->{l_doccnt} ) {
572 $row->{doccnt}->{data} = SL::Helper::GlAttachments->count_gl_pdf_attachments($ref->{id},$ref->{type});
576 if ($form->{balance} < 0) {
579 } elsif ($form->{balance} > 0) {
583 my $data = $form->format_amount(\%myconfig, ($form->{balance} * $ml), 2);
586 $row->{balance}->{data} = $data;
587 $row->{projectnumbers}->{data} = join ", ", sort { lc($a) cmp lc($b) } keys %{ $ref->{projectnumbers} };
589 map { $row->{$_}->{data} = $ref->{$_} } qw(id reference description notes gldate employee department transaction_description);
591 map { $row->{$_}->{data} = \@{ $rows{$_} }; } qw(transdate debit credit debit_accno credit_accno debit_tax_accno credit_tax_accno source);
593 foreach my $col (qw(debit_accno credit_accno debit_tax_accno credit_tax_accno)) {
594 $row->{$col}->{link} = [ map { "${callback}&accno=" . E($_) } @{ $rows{$col} } ];
597 map { $row->{$_}->{data} = \@{ $rows{$_} } if ($ref->{"${_}_accno"} ne "") } qw(debit_tax credit_tax);
599 $row->{reference}->{link} = build_std_url("script=$ref->{module}.pl", 'action=edit', 'id=' . E($ref->{id}), 'callback');
601 my $row_set = [ $row ];
603 if ( ($form->{l_subtotal} eq 'Y' && !$form->{report_generator_csv_options_for_import} )
604 && (($idx == (scalar @{ $form->{GL} } - 1))
605 || ($ref->{ $form->{sort} } ne $form->{GL}->[$idx + 1]->{ $form->{sort} }))) {
606 push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, [ qw(debit credit) ], 'listsubtotal');
609 $report->add_data($row_set);
614 # = 0 for balanced ledger
615 my $balanced_ledger = $totals{debit} + $totals{debit_tax} - $totals{credit} - $totals{credit_tax};
617 my $row = create_subtotal_row(\%totals, \@columns, \%column_alignment, [ qw(debit credit debit_tax credit_tax) ], 'listtotal');
620 if ($form->{balance} < 0) {
623 } elsif ($form->{balance} > 0) {
627 my $data = $form->format_amount(\%myconfig, ($form->{balance} * $ml), 2);
630 $row->{balance}->{data} = $data;
632 if ( !$form->{report_generator_csv_options_for_import} ) {
633 $report->add_separator();
634 $report->add_data($row);
637 my $raw_bottom_info_text;
639 if (!$form->{accno} && (abs($balanced_ledger) > 0.001)) {
640 $raw_bottom_info_text .=
641 '<p><span class="unbalanced_ledger">'
642 . $locale->text('Unbalanced Ledger')
644 . $form->format_amount(\%myconfig, $balanced_ledger, 3)
648 $raw_bottom_info_text .= $form->parse_html_template('gl/generate_report_bottom');
650 $report->set_options('raw_bottom_info_text' => $raw_bottom_info_text);
652 setup_gl_transactions_action_bar();
654 $report->generate_with_headers();
656 $main::lxdebug->leave_sub();
660 $::form->{transdate} = DateTime->today_local->to_kivitendo if !$::form->{transdate};
661 $::form->{gldate} = $::form->{transdate} if !$::form->{gldate};
668 $main::lxdebug->enter_sub();
670 $main::auth->assert('gl_transactions');
672 my $form = $main::form;
673 my %myconfig = %main::myconfig;
675 $form->{oldtransdate} = $form->{transdate};
683 my ($debitcredit, $amount);
685 my $dbh = SL::DB->client->dbh;
686 my ($notax_id) = selectrow_query($form, $dbh, "SELECT id FROM tax WHERE taxkey = 0 LIMIT 1", );
687 my $zerotaxes = selectall_hashref_query($form, $dbh, "SELECT id FROM tax WHERE rate = 0", );
690 qw(accno_id debit credit projectnumber fx_transaction source memo tax taxchart);
692 for my $i (1 .. $form->{rowcount}) {
693 $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) for qw(debit credit tax);
695 next if !$form->{"debit_$i"} && !$form->{"credit_$i"} && !$params{keep_rows_without_amount};
698 $debitcredit = ($form->{"debit_$i"} == 0) ? "0" : "1";
705 if (($debitcount >= 2) && ($creditcount == 2)) {
706 $form->{"credit_$i"} = 0;
707 $form->{"tax_$i"} = 0;
709 $form->{creditlock} = 1;
711 if (($creditcount >= 2) && ($debitcount == 2)) {
712 $form->{"debit_$i"} = 0;
713 $form->{"tax_$i"} = 0;
715 $form->{debitlock} = 1;
717 if (($creditcount == 1) && ($debitcount == 2)) {
718 $form->{creditlock} = 1;
720 if (($creditcount == 2) && ($debitcount == 1)) {
721 $form->{debitlock} = 1;
723 if ($debitcredit && $credittax) {
724 $form->{"taxchart_$i"} = "$notax_id--0.00000";
726 if (!$debitcredit && $debittax) {
727 $form->{"taxchart_$i"} = "$notax_id--0.00000";
730 ($form->{"debit_$i"} == 0)
731 ? $form->{"credit_$i"}
732 : $form->{"debit_$i"};
734 if (($debitcredit && $credittax) || (!$debitcredit && $debittax)) {
735 $form->{"taxchart_$i"} = "$notax_id--0.00000";
736 $form->{"tax_$i"} = 0;
738 my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
739 my $iswithouttax = grep { $_->{id} == $taxkey } @{ $zerotaxes };
740 if (!$iswithouttax) {
747 my ($tmpnetamount,$tmpdiff);
748 ($tmpnetamount,$form->{"tax_$i"},$tmpdiff) = $form->calculate_tax($amount,$rate,$form->{taxincluded} *= 1,2);
750 for (@flds) { $a[$j]->{$_} = $form->{"${_}_$i"} }
754 for my $i (1 .. $count) {
756 for (@flds) { $form->{"${_}_$i"} = $a[$j]->{$_} }
759 for my $i ($count + 1 .. $form->{rowcount}) {
760 for (@flds) { delete $form->{"${_}_$i"} }
763 $form->{rowcount} = $count + ($params{dont_add_new_row} ? 0 : 1);
766 $main::lxdebug->leave_sub();
772 $main::lxdebug->enter_sub();
774 $main::auth->assert('gl_transactions');
776 my $form = $main::form;
777 my %myconfig = %main::myconfig;
781 # for $i (1 .. $form->{rowcount}) {
782 # $form->{totaldebit} += $form->parse_amount(\%myconfig, $form->{"debit_$i"});
783 # $form->{totalcredit} += $form->parse_amount(\%myconfig, $form->{"credit_$i"});
787 &display_rows($init);
789 $main::lxdebug->leave_sub();
795 $main::lxdebug->enter_sub();
797 $main::auth->assert('gl_transactions');
799 my $form = $main::form;
800 my %myconfig = %main::myconfig;
801 my $cgi = $::request->{cgi};
803 my %balances = GL->get_chart_balances(map { $_->{id} } @{ $form->{ALL_CHARTS} });
805 $form->{debit_1} = 0 if !$form->{"debit_1"};
806 $form->{totaldebit} = 0;
807 $form->{totalcredit} = 0;
809 my %charts_by_id = map { ($_->{id} => $_) } @{ $::form->{ALL_CHARTS} };
810 my $default_chart = $::form->{ALL_CHARTS}[0];
811 my $transdate = $::form->{transdate} ? DateTime->from_kivitendo($::form->{transdate}) : DateTime->today_local;
812 my $deliverydate = $::form->{deliverydate} ? DateTime->from_kivitendo($::form->{deliverydate}) : undef;
814 my ($source, $memo, $source_hidden, $memo_hidden);
815 for my $i (1 .. $form->{rowcount}) {
816 if ($form->{show_details}) {
818 <td><input name="source_$i" value="$form->{"source_$i"}" size="16"></td>|;
820 <td><input name="memo_$i" value="$form->{"memo_$i"}" size="16"></td>|;
823 <input type="hidden" name="source_$i" value="$form->{"source_$i"}" size="16">|;
825 <input type="hidden" name="memo_$i" value="$form->{"memo_$i"}" size="16">|;
828 my %taxchart_labels = ();
829 my @taxchart_values = ();
831 my $accno_id = $::form->{"accno_id_$i"};
832 my $chart = $charts_by_id{$accno_id} // $default_chart;
833 $accno_id = $chart->{id};
834 my ($first_taxchart, $default_taxchart, $taxchart_to_use);
837 if ( $form->{"taxchart_$i"} ) {
838 ($used_tax_id) = split(/--/, $form->{"taxchart_$i"});
841 my $taxdate = $deliverydate ? $deliverydate : $transdate;
842 foreach my $item ( GL->get_active_taxes_for_chart($accno_id, $taxdate, $used_tax_id) ) {
843 my $key = $item->id . "--" . $item->rate;
844 $first_taxchart //= $item;
845 $default_taxchart = $item if $item->{is_default};
846 $taxchart_to_use = $item if $key eq $form->{"taxchart_$i"};
848 push(@taxchart_values, $key);
849 $taxchart_labels{$key} = $item->taxkey . " - " . $item->taxdescription . " " . $item->rate * 100 . ' %';
852 $taxchart_to_use //= $default_taxchart // $first_taxchart;
853 my $selected_taxchart = $taxchart_to_use->id . '--' . $taxchart_to_use->rate;
855 my $accno = qq|<td>| .
856 SL::Presenter::Chart::picker("accno_id_$i", $accno_id, style => "width: 300px") .
857 SL::Presenter::Tag::hidden_tag("previous_accno_id_$i", $accno_id)
859 my $tax_ddbox = qq|<td>| .
860 NTI($cgi->popup_menu('-name' => "taxchart_$i",
861 '-id' => "taxchart_$i",
862 '-style' => 'width:200px',
863 '-values' => \@taxchart_values,
864 '-labels' => \%taxchart_labels,
865 '-default' => $selected_taxchart))
868 my ($fx_transaction, $checked);
870 if ($form->{transfer}) {
871 $fx_transaction = qq|
872 <td><input name="fx_transaction_$i" class=checkbox type=checkbox value=1></td>
877 if ($form->{"debit_$i"} != 0) {
878 $form->{totaldebit} += $form->{"debit_$i"};
879 if (!$form->{taxincluded}) {
880 $form->{totaldebit} += $form->{"tax_$i"};
883 $form->{totalcredit} += $form->{"credit_$i"};
884 if (!$form->{taxincluded}) {
885 $form->{totalcredit} += $form->{"tax_$i"};
889 for (qw(debit credit tax)) {
892 ? $form->format_amount(\%myconfig, $form->{"${_}_$i"}, 2)
896 if ($i < $form->{rowcount}) {
897 if ($form->{transfer}) {
898 $checked = ($form->{"fx_transaction_$i"}) ? "1" : "";
899 my $x = ($checked) ? "x" : "";
900 $fx_transaction = qq|
901 <td><input type=hidden name="fx_transaction_$i" value="$checked">$x</td>
904 $form->hide_form("accno_$i");
907 if ($form->{transfer}) {
908 $fx_transaction = qq|
909 <td><input name="fx_transaction_$i" class=checkbox type=checkbox value=1></td>
914 my $debitreadonly = "";
915 my $creditreadonly = "";
916 if ($i == $form->{rowcount}) {
917 if ($form->{debitlock}) {
918 $debitreadonly = "readonly";
919 } elsif ($form->{creditlock}) {
920 $creditreadonly = "readonly";
924 my $projectnumber = SL::Presenter::Project::picker("project_id_$i", $form->{"project_id_$i"});
925 my $projectnumber_hidden = SL::Presenter::Tag::hidden_tag("project_id_$i", $form->{"project_id_$i"});
927 my $copy2credit = $i == 1 ? 'onkeyup="copy_debit_to_credit()"' : '';
928 my $balance = $form->format_amount(\%::myconfig, $balances{$accno_id} // 0, 2, 'DRCR');
930 # if we have a bt_chart_id we disallow changing the amount of the bank account
931 if ($form->{bt_chart_id}) {
932 $debitreadonly = $creditreadonly = "readonly" if ($form->{"accno_id_$i"} eq $form->{bt_chart_id});
933 $copy2credit = '' if $i == 1; # and disallow copy2credit
936 print qq|<tr valign=top>
938 <td id="chart_balance_$i" align="right">${balance}</td>
940 <td><input name="debit_$i" size="8" value="$form->{"debit_$i"}" accesskey=$i $copy2credit $debitreadonly></td>
941 <td><input name="credit_$i" size=8 value="$form->{"credit_$i"}" $creditreadonly></td>
942 <td><input type="hidden" name="tax_$i" value="$form->{"tax_$i"}">$form->{"tax_$i"}</td>
945 if ($form->{show_details}) {
949 <td>$projectnumber</td>
955 $projectnumber_hidden
963 $form->hide_form(qw(rowcount selectaccno));
965 $main::lxdebug->leave_sub();
970 return ($::instance_conf->get_gl_changeable == 2) ? ($::form->current_date(\%::myconfig) eq $::form->{gldate}) : ($::instance_conf->get_gl_changeable == 1);
973 sub setup_gl_action_bar {
976 my $change_never = $::instance_conf->get_gl_changeable == 0;
977 my $change_on_same_day_only = $::instance_conf->get_gl_changeable == 2 && ($form->current_date(\%::myconfig) ne $form->{gldate});
978 my ($is_linked_bank_transaction, $is_linked_ap_transaction, $is_reconciled_bank_transaction);
980 if ($form->{id} && SL::DB::Manager::BankTransactionAccTrans->find_by(gl_id => $form->{id})) {
981 $is_linked_bank_transaction = 1;
983 if ($form->{id} && SL::DB::Manager::ApGl->find_by(gl_id => $form->{id})) {
984 $is_linked_ap_transaction = 1;
986 # dont edit reconcilated bookings!
988 my @acc_trans = map { $_->acc_trans_id } @{ SL::DB::Manager::AccTransaction->get_all( where => [ trans_id => $form->{id} ] ) };
989 if (scalar @acc_trans && scalar @{ SL::DB::Manager::ReconciliationLink->get_all(where => [ acc_trans_id => [ @acc_trans ] ]) }) {
990 $is_reconciled_bank_transaction = 1;
993 my $create_post_action = sub {
995 # $_[1]: after_action
998 submit => [ '#form', { action => 'post', after_action => $_[1] } ],
999 disabled => $form->{locked} ? t8('The billing period has already been locked.')
1000 : $form->{storno} ? t8('A canceled general ledger transaction cannot be posted.')
1001 : ($form->{id} && $change_never) ? t8('Changing general ledger transaction has been disabled in the configuration.')
1002 : ($form->{id} && $change_on_same_day_only) ? t8('General ledger transactions can only be changed on the day they are posted.')
1003 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
1004 : $is_linked_ap_transaction ? t8('This transaction is linked with a AP transaction. Please undo and redo the AP transaction booking if needed.')
1005 : $is_reconciled_bank_transaction ? t8('This transaction is reconciled with a bank transaction. Please undo the reconciliation if needed.')
1011 if ($::instance_conf->get_gl_add_doc && $::instance_conf->get_doc_storage) {
1012 %post_entry = (combobox => [ $create_post_action->(t8('Post'), 'doc-tab'),
1013 $create_post_action->(t8('Post and new booking')) ]);
1014 } elsif ($::instance_conf->get_doc_storage) {
1015 %post_entry = (combobox => [ $create_post_action->(t8('Post')),
1016 $create_post_action->(t8('Post and upload document'), 'doc-tab') ]);
1018 %post_entry = $create_post_action->(t8('Post'));
1021 for my $bar ($::request->layout->get('actionbar')) {
1025 submit => [ '#form', { action => 'update' } ],
1026 id => 'update_button',
1027 accesskey => 'enter',
1031 action => [ t8('Storno'),
1032 submit => [ '#form', { action => 'storno' } ],
1033 confirm => t8('Do you really want to cancel this general ledger transaction?'),
1034 disabled => !$form->{id} ? t8('This general ledger transaction has not been posted yet.')
1035 : $form->{storno} ? t8('A canceled general ledger transaction cannot be canceled again.')
1036 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
1037 : $is_linked_ap_transaction ? t8('This transaction is linked with a AP transaction. Please undo and redo the AP transaction booking if needed.')
1038 : $is_reconciled_bank_transaction ? t8('This transaction is reconciled with a bank transaction. Please undo the reconciliation if needed.')
1041 action => [ t8('Delete'),
1042 submit => [ '#form', { action => 'delete' } ],
1043 confirm => t8('Do you really want to delete this object?'),
1044 disabled => !$form->{id} ? t8('This invoice has not been posted yet.')
1045 : $form->{locked} ? t8('The billing period has already been locked.')
1046 : $change_never ? t8('Changing invoices has been disabled in the configuration.')
1047 : $change_on_same_day_only ? t8('Invoices can only be changed on the day they are posted.')
1048 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
1049 : $is_linked_ap_transaction ? t8('This transaction is linked with a AP transaction. Please undo and redo the AP transaction booking if needed.')
1050 : $is_reconciled_bank_transaction ? t8('This transaction is reconciled with a bank transaction. Please undo the reconciliation if needed.')
1051 : $form->{storno} ? t8('A canceled general ledger transaction cannot be deleted.')
1054 ], # end of combobox "Storno"
1057 action => [ t8('more') ],
1060 call => [ 'set_history_window', $form->{id} * 1, 'glid' ],
1061 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
1065 call => [ 'follow_up_window' ],
1066 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
1069 t8('Record templates'),
1070 call => [ 'kivi.RecordTemplate.popup', 'gl_transaction' ],
1074 call => [ 'kivi.Draft.popup', 'gl', 'unknown', $form->{draft_id}, $form->{draft_description} ],
1075 disabled => $form->{id} ? t8('This invoice has already been posted.')
1076 : $form->{locked} ? t8('The billing period has already been locked.')
1079 ], # end of combobox "more"
1084 sub setup_gl_search_action_bar {
1087 for my $bar ($::request->layout->get('actionbar')) {
1091 submit => [ '#form', { action => 'continue', nextsub => 'generate_report' } ],
1092 accesskey => 'enter',
1098 sub setup_gl_transactions_action_bar {
1101 for my $bar ($::request->layout->get('actionbar')) {
1104 action => [ $::locale->text('Create new') ],
1106 $::locale->text('GL Transaction'),
1107 submit => [ '#create_new_form', { action => 'gl_transaction' } ],
1110 $::locale->text('AR Transaction'),
1111 submit => [ '#create_new_form', { action => 'ar_transaction' } ],
1114 $::locale->text('AP Transaction'),
1115 submit => [ '#create_new_form', { action => 'ap_transaction' } ],
1118 $::locale->text('Sales Invoice'),
1119 submit => [ '#create_new_form', { action => 'sales_invoice' } ],
1122 $::locale->text('Vendor Invoice'),
1123 submit => [ '#create_new_form', { action => 'vendor_invoice' } ],
1125 ], # end of combobox "Create new"
1131 $::lxdebug->enter_sub;
1132 $::auth->assert('gl_transactions');
1136 $::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");
1138 my @old_project_ids = grep { $_ } map{ $::form->{"project_id_$_"} } 1..$::form->{rowcount};
1139 my @conditions = @old_project_ids ? (id => \@old_project_ids) : ();
1140 $::form->{ALL_PROJECTS} = SL::DB::Manager::Project->get_all_sorted(query => [ or => [ active => 1, @conditions ]]);
1143 "charts" => { "key" => "ALL_CHARTS", "transdate" => $::form->{transdate} },
1146 # we cannot book on charttype header
1147 @{ $::form->{ALL_CHARTS} } = grep { $_->{charttype} ne 'H' } @{ $::form->{ALL_CHARTS} };
1148 $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
1150 my $title = $::form->{title};
1151 $::form->{title} = $::locale->text("$title General Ledger Transaction");
1152 # $locale->text('Add General Ledger Transaction')
1153 # $locale->text('Edit General Ledger Transaction')
1155 map { $::form->{$_} =~ s/\"/"/g }
1159 $::request->{layout}->focus("#reference");
1160 $::form->{taxincluded} = "1";
1162 $::request->{layout}->focus("#accno_id_$::form->{rowcount}_name");
1165 $::form->{previous_id} ||= "--";
1166 $::form->{previous_gldate} ||= "--";
1168 setup_gl_action_bar();
1171 print $::form->parse_html_template('gl/form_header', {
1172 hide_title => $title,
1173 readonly => $::form->{id} && ($::form->{locked} || !_get_radieren()),
1176 $::lxdebug->leave_sub;
1181 $::lxdebug->enter_sub;
1182 $::auth->assert('gl_transactions');
1184 my ($follow_ups, $follow_ups_due);
1186 if ($::form->{id}) {
1187 $follow_ups = FU->follow_ups('trans_id' => $::form->{id}, 'not_done' => 1);
1188 $follow_ups_due = sum map { $_->{due} * 1 } @{ $follow_ups || [] };
1191 print $::form->parse_html_template('gl/form_footer', {
1192 radieren => _get_radieren(),
1193 follow_ups => $follow_ups,
1194 follow_ups_due => $follow_ups_due,
1197 $::lxdebug->leave_sub;
1201 $main::lxdebug->enter_sub();
1203 my $form = $main::form;
1204 my %myconfig = %main::myconfig;
1205 my $locale = $main::locale;
1207 if (GL->delete_transaction(\%myconfig, \%$form)){
1208 # saving the history
1209 if(!exists $form->{addition} && $form->{id} ne "") {
1210 $form->{snumbers} = qq|gltransaction_| . $form->{id};
1211 $form->{addition} = "DELETED";
1212 $form->{what_done} = "gl_transaction";
1213 $form->save_history;
1215 # /saving the history
1216 $form->redirect($locale->text('Transaction deleted!'))
1218 $form->error($locale->text('Cannot delete transaction!'));
1219 $main::lxdebug->leave_sub();
1223 sub post_transaction {
1224 $main::lxdebug->enter_sub();
1226 my $form = $main::form;
1227 my %myconfig = %main::myconfig;
1228 my $locale = $main::locale;
1230 # check if there is something in reference and date
1231 $form->isblank("reference", $locale->text('Reference missing!'));
1232 $form->isblank("transdate", $locale->text('Transaction Date missing!'));
1233 $form->isblank("description", $locale->text('Description missing!'));
1234 $form->isblank("transaction_description", $locale->text('A transaction description is required.')) if $::instance_conf->get_require_transaction_description_ps;
1236 my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
1237 my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
1244 my $creditcount = 0;
1246 my %split_safety = ();
1248 my $dbh = SL::DB->client->dbh;
1249 my ($notax_id) = selectrow_query($form, $dbh, "SELECT id FROM tax WHERE taxkey = 0 LIMIT 1", );
1250 my $zerotaxes = selectall_hashref_query($form, $dbh, "SELECT id FROM tax WHERE rate = 0", );
1252 my @flds = qw(accno_id debit credit projectnumber fx_transaction source memo tax taxchart);
1254 for my $i (1 .. $form->{rowcount}) {
1255 next if $form->{"debit_$i"} eq "" && $form->{"credit_$i"} eq "";
1257 for (qw(debit credit tax)) {
1258 $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"});
1262 $debitcredit = ($form->{"debit_$i"} == 0) ? "0" : "1";
1264 $split_safety{ $form->{"debit_$i"} <=> 0 }++;
1265 $split_safety{ - $form->{"credit_$i"} <=> 0 }++;
1273 if (($debitcount >= 2) && ($creditcount == 2)) {
1274 $form->{"credit_$i"} = 0;
1275 $form->{"tax_$i"} = 0;
1277 $form->{creditlock} = 1;
1279 if (($creditcount >= 2) && ($debitcount == 2)) {
1280 $form->{"debit_$i"} = 0;
1281 $form->{"tax_$i"} = 0;
1283 $form->{debitlock} = 1;
1285 if (($creditcount == 1) && ($debitcount == 2)) {
1286 $form->{creditlock} = 1;
1288 if (($creditcount == 2) && ($debitcount == 1)) {
1289 $form->{debitlock} = 1;
1291 if ($debitcredit && $credittax) {
1292 $form->{"taxchart_$i"} = "$notax_id--0.00000";
1294 if (!$debitcredit && $debittax) {
1295 $form->{"taxchart_$i"} = "$notax_id--0.00000";
1297 my $amount = ($form->{"debit_$i"} == 0)
1298 ? $form->{"credit_$i"}
1299 : $form->{"debit_$i"};
1301 if (($debitcredit && $credittax) || (!$debitcredit && $debittax)) {
1302 $form->{"taxchart_$i"} = "$notax_id--0.00000";
1303 $form->{"tax_$i"} = 0;
1305 my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
1306 my $iswithouttax = grep { $_->{id} == $taxkey } @{ $zerotaxes };
1307 if (!$iswithouttax) {
1314 my ($tmpnetamount,$tmpdiff);
1315 ($tmpnetamount,$form->{"tax_$i"},$tmpdiff) = $form->calculate_tax($amount,$rate,$form->{taxincluded} *= 1,2);
1317 $form->{"debit_$i"} = $tmpnetamount;
1319 $form->{"credit_$i"} = $tmpnetamount;
1323 $form->{"tax_$i"} = 0;
1326 for (@flds) { $a[$j]->{$_} = $form->{"${_}_$i"} }
1330 if ($split_safety{-1} > 1 && $split_safety{1} > 1) {
1331 $::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. " .
1332 "Due to known problems involving accounting software kivitendo does not allow these."));
1335 for my $i (1 .. $count) {
1337 for (@flds) { $form->{"${_}_$i"} = $a[$j]->{$_} }
1340 for my $i ($count + 1 .. $form->{rowcount}) {
1341 for (@flds) { delete $form->{"${_}_$i"} }
1344 my ($debit, $credit, $taxtotal);
1345 for my $i (1 .. $form->{rowcount}) {
1346 my $dr = $form->{"debit_$i"};
1347 my $cr = $form->{"credit_$i"};
1348 my $tax = $form->{"tax_$i"};
1350 $form->error($locale->text('Cannot post transaction with a debit and credit entry for the same account!'));
1352 $debit += $dr + $tax if $dr;
1353 $credit += $cr + $tax if $cr;
1354 $taxtotal += $tax if $form->{taxincluded}
1357 $form->{taxincluded} = 0 if !$taxtotal;
1359 # this is just for the wise guys
1361 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
1362 if ($form->date_max_future($form->{"transdate"}, \%myconfig));
1363 $form->error($locale->text('Cannot post transaction for a closed period!'))
1364 if ($form->date_closed($form->{"transdate"}, \%myconfig));
1365 if ($form->round_amount($debit, 2) != $form->round_amount($credit, 2)) {
1366 $form->error($locale->text('Out of balance transaction!'));
1369 if ($form->round_amount($debit, 2) + $form->round_amount($credit, 2) == 0) {
1370 $form->error($locale->text('Empty transaction!'));
1374 # start transaction (post + history + (optional) banktrans)
1375 SL::DB->client->with_transaction(sub {
1377 if ((my $errno = GL->post_transaction(\%myconfig, \%$form)) <= -1) {
1380 $err[1] = $locale->text('Cannot have a value in both Debit and Credit!');
1381 $err[2] = $locale->text('Debit and credit out of balance!');
1382 $err[3] = $locale->text('Cannot post a transaction without a value!');
1386 # saving the history
1387 if(!exists $form->{addition} && $form->{id} ne "") {
1388 $form->{snumbers} = qq|gltransaction_| . $form->{id};
1389 $form->{addition} = "POSTED";
1390 $form->{what_done} = "gl transaction";
1391 $form->save_history;
1394 # Case BankTransaction: update RecordLink and BankTransaction
1395 if ($form->{callback} =~ /BankTransaction/ && $form->{bt_id}) {
1396 # set invoice_amount - we only rely on bt_id in form, do all other stuff ui independent
1397 # die if we have a unlogic or NYI case and abort the whole transaction
1398 my ($bt, $chart_id, $payment);
1399 require SL::DB::Manager::BankTransaction;
1401 $bt = SL::DB::Manager::BankTransaction->find_by(id => $::form->{bt_id});
1402 die "No bank transaction found" unless $bt;
1404 $chart_id = SL::DB::Manager::BankAccount->find_by(id => $bt->local_bank_account_id)->chart_id;
1405 die "no chart id" unless $chart_id;
1407 $payment = SL::DB::Manager::AccTransaction->get_all(where => [ trans_id => $::form->{id},
1408 chart_link => { like => '%_paid%' },
1409 chart_id => $chart_id ]);
1410 die "guru meditation error: Can only assign amount to one bank account booking" if scalar @{ $payment } > 1;
1412 # credit/debit * -1 matches the sign for bt.amount and bt.invoice_amount
1414 die "Can only assign the full (partial) bank amount to a single general ledger booking: " . $bt->not_assigned_amount . " " . ($payment->[0]->amount * -1)
1415 unless (abs($bt->not_assigned_amount - ($payment->[0]->amount * -1)) < 0.001);
1417 $bt->update_attributes(invoice_amount => $bt->invoice_amount + ($payment->[0]->amount * -1));
1419 # create record_link
1421 from_table => 'bank_transactions',
1422 from_id => $::form->{bt_id},
1424 to_id => $::form->{id},
1426 SL::DB::RecordLink->new(%props)->save;
1427 # and tighten holy acc_trans_id for this bank_transaction
1429 acc_trans_id => $payment->[0]->acc_trans_id,
1430 bank_transaction_id => $bt->id,
1431 gl_id => $payment->[0]->trans_id,
1433 my $bta = SL::DB::BankTransactionAccTrans->new(%props_acc);
1438 }) or do { die SL::DB->client->error };
1440 $main::lxdebug->leave_sub();
1444 $main::lxdebug->enter_sub();
1446 $main::auth->assert('gl_transactions');
1448 my $form = $main::form;
1449 my $locale = $main::locale;
1451 if ($::myconfig{mandatory_departments} && !$form->{department_id}) {
1452 $form->error($locale->text('You have to specify a department.'));
1455 $form->{title} = $locale->text("$form->{title} General Ledger Transaction");
1456 $form->{storno} = 0;
1459 if ($::instance_conf->get_webdav) {
1460 SL::Webdav->new(type => 'general_ledger',
1461 number => $form->{id},
1465 my $msg = $::locale->text("General ledger transaction '#1' posted (ID: #2)", $form->{reference}, $form->{id});
1466 if ($form->{callback} =~ /BankTransaction/ && $form->{bt_id}) {
1467 $form->redirect($msg);
1469 } elsif ('doc-tab' eq $form->{after_action}) {
1470 # Redirect with callback containing a fragment does not work (by now)
1471 # because the callback info is stored in the session an parsing the
1472 # callback parameters does not support fragments (see SL::Form::redirect).
1473 # So use flash_later for the message and redirect_headers for redirecting.
1474 my $add_doc_url = build_std_url("script=gl.pl", 'action=edit', 'id=' . E($form->{id}), 'fragment=ui-tabs-docs');
1475 SL::Helper::Flash::flash_later('info', $msg);
1476 print $form->redirect_header($add_doc_url);
1477 $::dispatcher->end_request;
1480 $form->{callback} = build_std_url("action=add", "show_details");
1481 $form->redirect($msg);
1484 $main::lxdebug->leave_sub();
1488 $main::lxdebug->enter_sub();
1490 $main::auth->assert('gl_transactions');
1492 my $form = $main::form;
1496 $main::lxdebug->leave_sub();
1501 $main::lxdebug->enter_sub();
1503 $main::auth->assert('gl_transactions');
1505 my $form = $main::form;
1506 my %myconfig = %main::myconfig;
1507 my $locale = $main::locale;
1509 # don't cancel cancelled transactions
1510 if (IS->has_storno(\%myconfig, $form, 'gl')) {
1511 $form->{title} = $locale->text("Cancel Accounts Receivables Transaction");
1512 $form->error($locale->text("Transaction has already been cancelled!"));
1515 GL->storno($form, \%myconfig, $form->{id});
1517 # saving the history
1518 if(!exists $form->{addition} && $form->{id} ne "") {
1519 $form->{snumbers} = qq|gltransaction_| . $form->{id};
1520 $form->{addition} = "STORNO";
1521 $form->{what_done} = "gl_transaction";
1522 $form->save_history;
1524 # /saving the history
1526 $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
1528 $main::lxdebug->leave_sub();
1532 call_sub($main::form->{nextsub});
1535 sub get_tax_dropdown {
1536 my $transdate = $::form->{transdate} ? DateTime->from_kivitendo($::form->{transdate}) : DateTime->today_local;
1537 my $deliverydate = $::form->{deliverydate} ? DateTime->from_kivitendo($::form->{deliverydate}) : undef;
1538 my @tax_accounts = GL->get_active_taxes_for_chart($::form->{accno_id}, $deliverydate // $transdate);
1539 my $html = $::form->parse_html_template("gl/update_tax_accounts", { TAX_ACCOUNTS => \@tax_accounts });
1541 print $::form->ajax_response_header, $html;
1544 sub get_chart_balance {
1545 my %balances = GL->get_chart_balances($::form->{accno_id});
1546 my $balance = $::form->format_amount(\%::myconfig, $balances{ $::form->{accno_id} }, 2, 'DRCR');
1548 print $::form->ajax_response_header, $balance;