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::BankTransactionAccTrans;
47 use SL::Helper::Flash qw(flash flash_later);
49 use SL::ReportGenerator;
50 use SL::DBUtils qw(selectrow_query selectall_hashref_query);
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";
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')
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')
87 sub load_record_template {
88 $::auth->assert('gl_transactions');
90 # Load existing template and verify that its one for this module.
91 my $template = SL::DB::RecordTemplate
92 ->new(id => $::form->{id})
94 with_object => [ qw(customer payment currency record_items record_items.chart) ],
97 die "invalid template type" unless $template->template_type eq 'gl_transaction';
99 $template->substitute_variables;
100 my $payment_suggestion = $::form->{form_defaults}->{amount_1};
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 } };
107 GL->transaction(\%::myconfig, $dummy_form);
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);
117 $::form->{$_} = $dummy_form->{$_} for qw(closedto revtrans previous_id previous_gldate);
120 foreach my $item (@{ $template->items }) {
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',
129 my $tax = first { $item->tax_id == $_->id } @{ $taxes };
130 $tax //= first { $active_taxkey->tax_id == $_->id } @{ $taxes };
131 $tax //= $taxes->[0];
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);
146 $::form->{$_} = $form_defaults->{$_} for keys %{ $form_defaults // {} };
148 flash('info', $::locale->text("The record template '#1' has been loaded.", $template->template_name));
151 keep_rows_without_amount => 1,
152 dont_add_new_row => 1,
156 sub save_record_template {
157 $::auth->assert('gl_transactions');
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');
165 # bank transactions need amounts for assignment
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;
172 $_->{chart_id} && (($_->{tax_id} // '') ne '')
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_${_}"},
182 } (1..($::form->{rowcount} || 1));
184 $template->assign_attributes(
185 template_type => 'gl_transaction',
186 template_name => $new_name,
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},
206 ->flash('error', $::locale->text("Saving the record template '#1' failed.", $new_name))
211 ->flash('info', $::locale->text("The record template '#1' has been saved.", $new_name))
216 $main::lxdebug->enter_sub();
218 $main::auth->assert('gl_transactions');
220 my $form = $main::form;
221 my %myconfig = %main::myconfig;
223 $form->{title} = "Add";
225 $form->{callback} = "gl.pl?action=add" unless $form->{callback};
227 # we use this only to set a default date
228 # yep. aber er holt hier auch schon ALL_CHARTS. Aufwand / Nutzen? jb
229 GL->transaction(\%myconfig, \%$form);
231 $form->{rowcount} = 2;
237 $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
239 $form->{show_details} = $myconfig{show_form_details} unless defined $form->{show_details};
242 $main::lxdebug->leave_sub();
246 sub prepare_transaction {
247 $main::lxdebug->enter_sub();
249 $main::auth->assert('gl_transactions');
251 my $form = $main::form;
252 my %myconfig = %main::myconfig;
254 GL->transaction(\%myconfig, \%$form);
256 $form->{amount} = $form->format_amount(\%myconfig, $form->{amount}, 2);
258 $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
263 foreach my $ref (@{ $form->{GL} }) {
265 if ($tax && ($ref->{accno} eq $taxaccno)) {
266 $form->{"tax_$j"} = abs($ref->{amount});
267 $form->{"taxchart_$j"} = $ref->{id} . "--" . $ref->{taxrate};
268 if ($form->{taxincluded}) {
269 if ($ref->{amount} < 0) {
270 $form->{"debit_$j"} += $form->{"tax_$j"};
272 $form->{"credit_$j"} += $form->{"tax_$j"};
275 $form->{"project_id_$j"} = $ref->{project_id};
278 $form->{"accno_id_$i"} = $ref->{chart_id};
279 for (qw(fx_transaction source memo)) { $form->{"${_}_$i"} = $ref->{$_} }
280 if ($ref->{amount} < 0) {
281 $form->{totaldebit} -= $ref->{amount};
282 $form->{"debit_$i"} = $ref->{amount} * -1;
284 $form->{totalcredit} += $ref->{amount};
285 $form->{"credit_$i"} = $ref->{amount};
287 $form->{"taxchart_$i"} = $ref->{id}."--0.00000";
288 $form->{"project_id_$i"} = $ref->{project_id};
291 if ($ref->{taxaccno} && !$tax) {
292 $taxaccno = $ref->{taxaccno};
300 $form->{rowcount} = $i;
302 ($form->datetonum($form->{transdate}, \%myconfig) <=
303 $form->datetonum($form->{closedto}, \%myconfig));
305 $main::lxdebug->leave_sub();
309 $main::lxdebug->enter_sub();
311 $main::auth->assert('gl_transactions');
313 my $form = $main::form;
314 my %myconfig = %main::myconfig;
316 prepare_transaction();
318 $form->{title} = "Edit";
320 $form->{show_details} = $myconfig{show_form_details} unless defined $form->{show_details};
322 if ($form->{id} && $::instance_conf->get_webdav) {
323 my $webdav = SL::Webdav->new(
324 type => 'general_ledger',
325 number => $form->{id},
327 my @all_objects = $webdav->get_all_objects;
328 @{ $form->{WEBDAV} } = map { { name => $_->filename,
330 link => File::Spec->catfile($_->full_filedescriptor),
337 $main::lxdebug->leave_sub();
342 $::lxdebug->enter_sub;
343 $::auth->assert('general_ledger | gl_transactions');
346 projects => { key => "ALL_PROJECTS", all => 1 },
348 $::form->{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]);
349 $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
351 setup_gl_search_action_bar();
354 print $::form->parse_html_template('gl/search', {
355 employee_label => sub { "$_[0]{id}--$_[0]{name}" },
358 $::lxdebug->leave_sub;
361 sub create_subtotal_row {
362 $main::lxdebug->enter_sub();
364 my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
366 my $form = $main::form;
367 my %myconfig = %main::myconfig;
369 my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
371 map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
373 map { $totals->{$_} = 0 } @{ $subtotal_columns };
375 $main::lxdebug->leave_sub();
380 sub generate_report {
381 $main::lxdebug->enter_sub();
383 $main::auth->assert('general_ledger | gl_transactions');
385 my $form = $main::form;
386 my %myconfig = %main::myconfig;
387 my $locale = $main::locale;
389 # 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 # <form method=post action=gl.pl>
392 # <input type=hidden name=sort value=datesort> # form->{sort} setzen
393 # <input type=hidden name=nextsub value=generate_report>
395 # anhand von neuer Variable datesort wird jetzt $form->{sort} auf transdate oder gldate gesetzt
396 # damit ist die Hidden Variable "sort" wahrscheinlich sogar überflüssig
398 # ändert man die Sortierreihenfolge per Klick auf eine der Überschriften wird die Variable "sort" per GET übergeben, z.B. id,transdate, gldate, ...
399 # 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 if ( $form->{sort} eq 'datesort' ) { # sollte bei einem Post (Aufruf aus Suchmaske) immer wahr sein
402 # je nachdem ob in Suchmaske "transdate" oder "gldate" ausgesucht wurde erstes Suchergebnis entsprechend sortieren
403 $form->{sort} = $form->{datesort};
407 report_generator_set_default_sort("$form->{datesort}", 1);
408 # report_generator_set_default_sort('transdate', 1);
410 GL->all_transactions(\%myconfig, \%$form);
412 my %acctype = ('A' => $locale->text('Asset'),
413 'C' => $locale->text('Contra'),
414 'L' => $locale->text('Liability'),
415 'Q' => $locale->text('Equity'),
416 'I' => $locale->text('Revenue'),
417 'E' => $locale->text('Expense'),);
419 $form->{title} = $locale->text('Journal');
420 if ($form->{category} ne 'X') {
421 $form->{title} .= " : " . $locale->text($acctype{ $form->{category} });
424 $form->{landscape} = 1;
426 my $ml = ($form->{ml} =~ /(A|E|Q)/) ? -1 : 1;
429 transdate gldate id reference description
430 notes source doccnt debit debit_accno
431 credit credit_accno debit_tax debit_tax_accno
432 credit_tax credit_tax_accno balance projectnumbers
436 # add employee here, so that variable is still known and passed in url when choosing a different sort order in resulting table
437 my @hidden_variables = qw(accno source reference description notes project_id datefrom dateto employee_id datesort category l_subtotal department_id);
438 push @hidden_variables, map { "l_${_}" } @columns;
440 my $employee = $form->{employee_id} ? SL::DB::Employee->new(id => $form->{employee_id})->load->name : '';
442 my (@options, @date_options);
443 push @options, $locale->text('Account') . " : $form->{accno} $form->{account_description}" if ($form->{accno});
444 push @options, $locale->text('Source') . " : $form->{source}" if ($form->{source});
445 push @options, $locale->text('Reference') . " : $form->{reference}" if ($form->{reference});
446 push @options, $locale->text('Description') . " : $form->{description}" if ($form->{description});
447 push @options, $locale->text('Notes') . " : $form->{notes}" if ($form->{notes});
448 push @options, $locale->text('Employee') . " : $employee" if $employee;
449 my $datesorttext = $form->{datesort} eq 'transdate' ? $locale->text('Transdate') : $locale->text('Gldate');
450 push @date_options, "$datesorttext" if ($form->{datesort} and ($form->{datefrom} or $form->{dateto}));
451 push @date_options, $locale->text('From'), $locale->date(\%myconfig, $form->{datefrom}, 1) if ($form->{datefrom});
452 push @date_options, $locale->text('Bis'), $locale->date(\%myconfig, $form->{dateto}, 1) if ($form->{dateto});
453 push @options, join(' ', @date_options) if (scalar @date_options);
455 if ($form->{department_id}) {
456 my $department = SL::DB::Manager::Department->find_by( id => $form->{department_id} );
457 push @options, $locale->text('Department') . " : " . $department->description;
460 my $callback = build_std_url('action=generate_report', grep { $form->{$_} } @hidden_variables);
462 $form->{l_credit_accno} = 'Y';
463 $form->{l_debit_accno} = 'Y';
464 $form->{l_credit_tax} = 'Y';
465 $form->{l_debit_tax} = 'Y';
466 # $form->{l_gldate} = 'Y'; # Spalte mit gldate immer anzeigen
467 $form->{l_credit_tax_accno} = 'Y';
468 $form->{l_datesort} = 'Y';
469 $form->{l_debit_tax_accno} = 'Y';
470 $form->{l_balance} = $form->{accno} ? 'Y' : '';
471 $form->{l_doccnt} = $form->{l_source} ? 'Y' : '';
474 'id' => { 'text' => $locale->text('ID'), },
475 'transdate' => { 'text' => $locale->text('Transdate'), },
476 'gldate' => { 'text' => $locale->text('Gldate'), },
477 'reference' => { 'text' => $locale->text('Reference'), },
478 'source' => { 'text' => $locale->text('Source'), },
479 'doccnt' => { 'text' => $locale->text('Document Count'), },
480 'description' => { 'text' => $locale->text('Description'), },
481 'notes' => { 'text' => $locale->text('Notes'), },
482 'debit' => { 'text' => $locale->text('Debit'), },
483 'debit_accno' => { 'text' => $locale->text('Debit Account'), },
484 'credit' => { 'text' => $locale->text('Credit'), },
485 'credit_accno' => { 'text' => $locale->text('Credit Account'), },
486 'debit_tax' => { 'text' => $locale->text('Debit Tax'), },
487 'debit_tax_accno' => { 'text' => $locale->text('Debit Tax Account'), },
488 'credit_tax' => { 'text' => $locale->text('Credit Tax'), },
489 'credit_tax_accno' => { 'text' => $locale->text('Credit Tax Account'), },
490 'balance' => { 'text' => $locale->text('Balance'), },
491 'projectnumbers' => { 'text' => $locale->text('Project Numbers'), },
492 'department' => { 'text' => $locale->text('Department'), },
493 'employee' => { 'text' => $locale->text('Employee'), },
496 foreach my $name (qw(id transdate gldate reference description debit_accno credit_accno debit_tax_accno credit_tax_accno department)) {
497 my $sortname = $name =~ m/accno/ ? 'accno' : $name;
498 my $sortdir = $sortname eq $form->{sort} ? 1 - $form->{sortdir} : $form->{sortdir};
499 $column_defs{$name}->{link} = $callback . "&sort=$sortname&sortdir=$sortdir";
502 map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
503 map { $column_defs{$_}->{visible} = 0 } qw(debit_accno credit_accno debit_tax_accno credit_tax_accno) if $form->{accno};
505 my %column_alignment;
506 map { $column_alignment{$_} = 'right' } qw(balance id debit credit debit_tax credit_tax balance);
507 map { $column_alignment{$_} = 'center' } qw(transdate gldate reference debit_accno credit_accno debit_tax_accno credit_tax_accno);
508 map { $column_alignment{$_} = 'left' } qw(description source notes);
509 map { $column_defs{$_}->{align} = $column_alignment{$_} } keys %column_alignment;
511 my $report = SL::ReportGenerator->new(\%myconfig, $form);
513 $report->set_columns(%column_defs);
514 $report->set_column_order(@columns);
516 $form->{l_attachments} = 'Y';
517 $report->set_export_options('generate_report', @hidden_variables, qw(sort sortdir l_attachments));
519 $report->set_sort_indicator($form->{sort} eq 'accno' ? 'debit_accno' : $form->{sort}, $form->{sortdir});
521 $report->set_options('top_info_text' => join("\n", @options),
522 'output_format' => 'HTML',
523 'title' => $form->{title},
524 'attachment_basename' => $locale->text('general_ledger_list') . strftime('_%Y%m%d', localtime time),
526 $report->set_options_from_form();
527 $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
529 # add sort to callback
530 $form->{callback} = "$callback&sort=" . E($form->{sort}) . "&sortdir=" . E($form->{sortdir});
533 my @totals_columns = qw(debit credit debit_tax credit_tax);
534 my %subtotals = map { $_ => 0 } @totals_columns;
535 my %totals = map { $_ => 0 } @totals_columns;
538 foreach my $ref (@{ $form->{GL} }) {
542 foreach my $key (qw(debit credit debit_tax credit_tax)) {
544 foreach my $idx (sort keys(%{ $ref->{$key} })) {
545 my $value = $ref->{$key}->{$idx};
546 $subtotals{$key} += $value;
547 $totals{$key} += $value;
548 if ($key =~ /debit.*/) {
553 $form->{balance} = $form->{balance} + $value * $ml;
554 push @{ $rows{$key} }, $form->format_amount(\%myconfig, $value, 2);
558 foreach my $key (qw(debit_accno credit_accno debit_tax_accno credit_tax_accno ac_transdate source)) {
559 my $col = $key eq 'ac_transdate' ? 'transdate' : $key;
560 $rows{$col} = [ map { $ref->{$key}->{$_} } sort keys(%{ $ref->{$key} }) ];
564 map { $row->{$_} = { 'data' => '', 'align' => $column_alignment{$_} } } @columns;
566 if ( $form->{l_doccnt} ) {
567 $row->{doccnt}->{data} = SL::Helper::GlAttachments->count_gl_pdf_attachments($ref->{id},$ref->{type});
571 if ($form->{balance} < 0) {
574 } elsif ($form->{balance} > 0) {
578 my $data = $form->format_amount(\%myconfig, ($form->{balance} * $ml), 2);
581 $row->{balance}->{data} = $data;
582 $row->{projectnumbers}->{data} = join ", ", sort { lc($a) cmp lc($b) } keys %{ $ref->{projectnumbers} };
584 map { $row->{$_}->{data} = $ref->{$_} } qw(id reference description notes gldate employee department);
586 map { $row->{$_}->{data} = \@{ $rows{$_} }; } qw(transdate debit credit debit_accno credit_accno debit_tax_accno credit_tax_accno source);
588 foreach my $col (qw(debit_accno credit_accno debit_tax_accno credit_tax_accno)) {
589 $row->{$col}->{link} = [ map { "${callback}&accno=" . E($_) } @{ $rows{$col} } ];
592 map { $row->{$_}->{data} = \@{ $rows{$_} } if ($ref->{"${_}_accno"} ne "") } qw(debit_tax credit_tax);
594 $row->{reference}->{link} = build_std_url("script=$ref->{module}.pl", 'action=edit', 'id=' . E($ref->{id}), 'callback');
596 my $row_set = [ $row ];
598 if ( ($form->{l_subtotal} eq 'Y' && !$form->{report_generator_csv_options_for_import} )
599 && (($idx == (scalar @{ $form->{GL} } - 1))
600 || ($ref->{ $form->{sort} } ne $form->{GL}->[$idx + 1]->{ $form->{sort} }))) {
601 push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, [ qw(debit credit) ], 'listsubtotal');
604 $report->add_data($row_set);
609 # = 0 for balanced ledger
610 my $balanced_ledger = $totals{debit} + $totals{debit_tax} - $totals{credit} - $totals{credit_tax};
612 my $row = create_subtotal_row(\%totals, \@columns, \%column_alignment, [ qw(debit credit debit_tax credit_tax) ], 'listtotal');
615 if ($form->{balance} < 0) {
618 } elsif ($form->{balance} > 0) {
622 my $data = $form->format_amount(\%myconfig, ($form->{balance} * $ml), 2);
625 $row->{balance}->{data} = $data;
627 if ( !$form->{report_generator_csv_options_for_import} ) {
628 $report->add_separator();
629 $report->add_data($row);
632 my $raw_bottom_info_text;
634 if (!$form->{accno} && (abs($balanced_ledger) > 0.001)) {
635 $raw_bottom_info_text .=
636 '<p><span class="unbalanced_ledger">'
637 . $locale->text('Unbalanced Ledger')
639 . $form->format_amount(\%myconfig, $balanced_ledger, 3)
643 $raw_bottom_info_text .= $form->parse_html_template('gl/generate_report_bottom');
645 $report->set_options('raw_bottom_info_text' => $raw_bottom_info_text);
647 setup_gl_transactions_action_bar();
649 $report->generate_with_headers();
651 $main::lxdebug->leave_sub();
655 $::form->{transdate} = DateTime->today_local->to_kivitendo if !$::form->{transdate};
656 $::form->{gldate} = $::form->{transdate} if !$::form->{gldate};
663 $main::lxdebug->enter_sub();
665 $main::auth->assert('gl_transactions');
667 my $form = $main::form;
668 my %myconfig = %main::myconfig;
670 $form->{oldtransdate} = $form->{transdate};
678 my ($debitcredit, $amount);
680 my $dbh = SL::DB->client->dbh;
681 my ($notax_id) = selectrow_query($form, $dbh, "SELECT id FROM tax WHERE taxkey = 0 LIMIT 1", );
682 my $zerotaxes = selectall_hashref_query($form, $dbh, "SELECT id FROM tax WHERE rate = 0", );
685 qw(accno_id debit credit projectnumber fx_transaction source memo tax taxchart);
687 for my $i (1 .. $form->{rowcount}) {
688 $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) for qw(debit credit tax);
690 next if !$form->{"debit_$i"} && !$form->{"credit_$i"} && !$params{keep_rows_without_amount};
693 $debitcredit = ($form->{"debit_$i"} == 0) ? "0" : "1";
700 if (($debitcount >= 2) && ($creditcount == 2)) {
701 $form->{"credit_$i"} = 0;
702 $form->{"tax_$i"} = 0;
704 $form->{creditlock} = 1;
706 if (($creditcount >= 2) && ($debitcount == 2)) {
707 $form->{"debit_$i"} = 0;
708 $form->{"tax_$i"} = 0;
710 $form->{debitlock} = 1;
712 if (($creditcount == 1) && ($debitcount == 2)) {
713 $form->{creditlock} = 1;
715 if (($creditcount == 2) && ($debitcount == 1)) {
716 $form->{debitlock} = 1;
718 if ($debitcredit && $credittax) {
719 $form->{"taxchart_$i"} = "$notax_id--0.00000";
721 if (!$debitcredit && $debittax) {
722 $form->{"taxchart_$i"} = "$notax_id--0.00000";
725 ($form->{"debit_$i"} == 0)
726 ? $form->{"credit_$i"}
727 : $form->{"debit_$i"};
729 if (($debitcredit && $credittax) || (!$debitcredit && $debittax)) {
730 $form->{"taxchart_$i"} = "$notax_id--0.00000";
731 $form->{"tax_$i"} = 0;
733 my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
734 my $iswithouttax = grep { $_->{id} == $taxkey } @{ $zerotaxes };
735 if (!$iswithouttax) {
742 my ($tmpnetamount,$tmpdiff);
743 ($tmpnetamount,$form->{"tax_$i"},$tmpdiff) = $form->calculate_tax($amount,$rate,$form->{taxincluded} *= 1,2);
745 for (@flds) { $a[$j]->{$_} = $form->{"${_}_$i"} }
749 for my $i (1 .. $count) {
751 for (@flds) { $form->{"${_}_$i"} = $a[$j]->{$_} }
754 for my $i ($count + 1 .. $form->{rowcount}) {
755 for (@flds) { delete $form->{"${_}_$i"} }
758 $form->{rowcount} = $count + ($params{dont_add_new_row} ? 0 : 1);
761 $main::lxdebug->leave_sub();
767 $main::lxdebug->enter_sub();
769 $main::auth->assert('gl_transactions');
771 my $form = $main::form;
772 my %myconfig = %main::myconfig;
776 # for $i (1 .. $form->{rowcount}) {
777 # $form->{totaldebit} += $form->parse_amount(\%myconfig, $form->{"debit_$i"});
778 # $form->{totalcredit} += $form->parse_amount(\%myconfig, $form->{"credit_$i"});
782 &display_rows($init);
784 $main::lxdebug->leave_sub();
790 $main::lxdebug->enter_sub();
792 $main::auth->assert('gl_transactions');
794 my $form = $main::form;
795 my %myconfig = %main::myconfig;
796 my $cgi = $::request->{cgi};
798 my %balances = GL->get_chart_balances(map { $_->{id} } @{ $form->{ALL_CHARTS} });
800 $form->{debit_1} = 0 if !$form->{"debit_1"};
801 $form->{totaldebit} = 0;
802 $form->{totalcredit} = 0;
804 my %charts_by_id = map { ($_->{id} => $_) } @{ $::form->{ALL_CHARTS} };
805 my $default_chart = $::form->{ALL_CHARTS}[0];
806 my $transdate = $::form->{transdate} ? DateTime->from_kivitendo($::form->{transdate}) : DateTime->today_local;
807 my $deliverydate = $::form->{deliverydate} ? DateTime->from_kivitendo($::form->{deliverydate}) : undef;
809 my ($source, $memo, $source_hidden, $memo_hidden);
810 for my $i (1 .. $form->{rowcount}) {
811 if ($form->{show_details}) {
813 <td><input name="source_$i" value="$form->{"source_$i"}" size="16"></td>|;
815 <td><input name="memo_$i" value="$form->{"memo_$i"}" size="16"></td>|;
818 <input type="hidden" name="source_$i" value="$form->{"source_$i"}" size="16">|;
820 <input type="hidden" name="memo_$i" value="$form->{"memo_$i"}" size="16">|;
823 my %taxchart_labels = ();
824 my @taxchart_values = ();
826 my $accno_id = $::form->{"accno_id_$i"};
827 my $chart = $charts_by_id{$accno_id} // $default_chart;
828 $accno_id = $chart->{id};
829 my ($first_taxchart, $default_taxchart, $taxchart_to_use);
832 if ( $form->{"taxchart_$i"} ) {
833 ($used_tax_id) = split(/--/, $form->{"taxchart_$i"});
836 my $taxdate = $deliverydate ? $deliverydate : $transdate;
837 foreach my $item ( GL->get_active_taxes_for_chart($accno_id, $taxdate, $used_tax_id) ) {
838 my $key = $item->id . "--" . $item->rate;
839 $first_taxchart //= $item;
840 $default_taxchart = $item if $item->{is_default};
841 $taxchart_to_use = $item if $key eq $form->{"taxchart_$i"};
843 push(@taxchart_values, $key);
844 $taxchart_labels{$key} = $item->taxkey . " - " . $item->taxdescription . " " . $item->rate * 100 . ' %';
847 $taxchart_to_use //= $default_taxchart // $first_taxchart;
848 my $selected_taxchart = $taxchart_to_use->id . '--' . $taxchart_to_use->rate;
850 my $accno = qq|<td>| .
851 SL::Presenter::Chart::picker("accno_id_$i", $accno_id, style => "width: 300px") .
852 SL::Presenter::Tag::hidden_tag("previous_accno_id_$i", $accno_id)
854 my $tax_ddbox = qq|<td>| .
855 NTI($cgi->popup_menu('-name' => "taxchart_$i",
856 '-id' => "taxchart_$i",
857 '-style' => 'width:200px',
858 '-values' => \@taxchart_values,
859 '-labels' => \%taxchart_labels,
860 '-default' => $selected_taxchart))
863 my ($fx_transaction, $checked);
865 if ($form->{transfer}) {
866 $fx_transaction = qq|
867 <td><input name="fx_transaction_$i" class=checkbox type=checkbox value=1></td>
872 if ($form->{"debit_$i"} != 0) {
873 $form->{totaldebit} += $form->{"debit_$i"};
874 if (!$form->{taxincluded}) {
875 $form->{totaldebit} += $form->{"tax_$i"};
878 $form->{totalcredit} += $form->{"credit_$i"};
879 if (!$form->{taxincluded}) {
880 $form->{totalcredit} += $form->{"tax_$i"};
884 for (qw(debit credit tax)) {
887 ? $form->format_amount(\%myconfig, $form->{"${_}_$i"}, 2)
891 if ($i < $form->{rowcount}) {
892 if ($form->{transfer}) {
893 $checked = ($form->{"fx_transaction_$i"}) ? "1" : "";
894 my $x = ($checked) ? "x" : "";
895 $fx_transaction = qq|
896 <td><input type=hidden name="fx_transaction_$i" value="$checked">$x</td>
899 $form->hide_form("accno_$i");
902 if ($form->{transfer}) {
903 $fx_transaction = qq|
904 <td><input name="fx_transaction_$i" class=checkbox type=checkbox value=1></td>
909 my $debitreadonly = "";
910 my $creditreadonly = "";
911 if ($i == $form->{rowcount}) {
912 if ($form->{debitlock}) {
913 $debitreadonly = "readonly";
914 } elsif ($form->{creditlock}) {
915 $creditreadonly = "readonly";
919 my $projectnumber = SL::Presenter::Project::picker("project_id_$i", $form->{"project_id_$i"});
920 my $projectnumber_hidden = SL::Presenter::Tag::hidden_tag("project_id_$i", $form->{"project_id_$i"});
922 my $copy2credit = $i == 1 ? 'onkeyup="copy_debit_to_credit()"' : '';
923 my $balance = $form->format_amount(\%::myconfig, $balances{$accno_id} // 0, 2, 'DRCR');
925 # if we have a bt_chart_id we disallow changing the amount of the bank account
926 if ($form->{bt_chart_id}) {
927 $debitreadonly = $creditreadonly = "readonly" if ($form->{"accno_id_$i"} eq $form->{bt_chart_id});
928 $copy2credit = '' if $i == 1; # and disallow copy2credit
931 print qq|<tr valign=top>
933 <td id="chart_balance_$i" align="right">${balance}</td>
935 <td><input name="debit_$i" size="8" value="$form->{"debit_$i"}" accesskey=$i $copy2credit $debitreadonly></td>
936 <td><input name="credit_$i" size=8 value="$form->{"credit_$i"}" $creditreadonly></td>
937 <td><input type="hidden" name="tax_$i" value="$form->{"tax_$i"}">$form->{"tax_$i"}</td>
940 if ($form->{show_details}) {
944 <td>$projectnumber</td>
950 $projectnumber_hidden
958 $form->hide_form(qw(rowcount selectaccno));
960 $main::lxdebug->leave_sub();
965 return ($::instance_conf->get_gl_changeable == 2) ? ($::form->current_date(\%::myconfig) eq $::form->{gldate}) : ($::instance_conf->get_gl_changeable == 1);
968 sub setup_gl_action_bar {
971 my $change_never = $::instance_conf->get_gl_changeable == 0;
972 my $change_on_same_day_only = $::instance_conf->get_gl_changeable == 2 && ($form->current_date(\%::myconfig) ne $form->{gldate});
973 my ($is_linked_bank_transaction, $is_linked_ap_transaction);
975 if ($form->{id} && SL::DB::Manager::BankTransactionAccTrans->find_by(gl_id => $form->{id})) {
976 $is_linked_bank_transaction = 1;
978 if ($form->{id} && SL::DB::Manager::ApGl->find_by(gl_id => $form->{id})) {
979 $is_linked_ap_transaction = 1;
983 my $create_post_action = sub {
985 # $_[1]: after_action
988 submit => [ '#form', { action => 'post', after_action => $_[1] } ],
989 disabled => $form->{locked} ? t8('The billing period has already been locked.')
990 : $form->{storno} ? t8('A canceled general ledger transaction cannot be posted.')
991 : ($form->{id} && $change_never) ? t8('Changing general ledger transaction has been disabled in the configuration.')
992 : ($form->{id} && $change_on_same_day_only) ? t8('General ledger transactions can only be changed on the day they are posted.')
993 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
994 : $is_linked_ap_transaction ? t8('This transaction is linked with a AP transaction. Please undo and redo the AP transaction booking if needed.')
1000 if ($::instance_conf->get_gl_add_doc && $::instance_conf->get_doc_storage) {
1001 %post_entry = (combobox => [ $create_post_action->(t8('Post'), 'doc-tab'),
1002 $create_post_action->(t8('Post and new booking')) ]);
1003 } elsif ($::instance_conf->get_doc_storage) {
1004 %post_entry = (combobox => [ $create_post_action->(t8('Post')),
1005 $create_post_action->(t8('Post and upload document'), 'doc-tab') ]);
1007 %post_entry = $create_post_action->(t8('Post'));
1010 for my $bar ($::request->layout->get('actionbar')) {
1014 submit => [ '#form', { action => 'update' } ],
1015 id => 'update_button',
1016 accesskey => 'enter',
1020 action => [ t8('Storno'),
1021 submit => [ '#form', { action => 'storno' } ],
1022 confirm => t8('Do you really want to cancel this general ledger transaction?'),
1023 disabled => !$form->{id} ? t8('This general ledger transaction has not been posted yet.')
1024 : $form->{storno} ? t8('A canceled general ledger transaction cannot be canceled again.')
1025 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
1026 : $is_linked_ap_transaction ? t8('This transaction is linked with a AP transaction. Please undo and redo the AP transaction booking if needed.')
1029 action => [ t8('Delete'),
1030 submit => [ '#form', { action => 'delete' } ],
1031 confirm => t8('Do you really want to delete this object?'),
1032 disabled => !$form->{id} ? t8('This invoice has not been posted yet.')
1033 : $form->{locked} ? t8('The billing period has already been locked.')
1034 : $change_never ? t8('Changing invoices has been disabled in the configuration.')
1035 : $change_on_same_day_only ? t8('Invoices can only be changed on the day they are posted.')
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 : $form->{storno} ? t8('A canceled general ledger transaction cannot be deleted.')
1041 ], # end of combobox "Storno"
1044 action => [ t8('more') ],
1047 call => [ 'set_history_window', $form->{id} * 1, 'glid' ],
1048 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
1052 call => [ 'follow_up_window' ],
1053 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
1056 t8('Record templates'),
1057 call => [ 'kivi.RecordTemplate.popup', 'gl_transaction' ],
1061 call => [ 'kivi.Draft.popup', 'gl', 'unknown', $form->{draft_id}, $form->{draft_description} ],
1062 disabled => $form->{id} ? t8('This invoice has already been posted.')
1063 : $form->{locked} ? t8('The billing period has already been locked.')
1066 ], # end of combobox "more"
1071 sub setup_gl_search_action_bar {
1074 for my $bar ($::request->layout->get('actionbar')) {
1078 submit => [ '#form', { action => 'continue', nextsub => 'generate_report' } ],
1079 accesskey => 'enter',
1085 sub setup_gl_transactions_action_bar {
1088 for my $bar ($::request->layout->get('actionbar')) {
1091 action => [ $::locale->text('Create new') ],
1093 $::locale->text('GL Transaction'),
1094 submit => [ '#create_new_form', { action => 'gl_transaction' } ],
1097 $::locale->text('AR Transaction'),
1098 submit => [ '#create_new_form', { action => 'ar_transaction' } ],
1101 $::locale->text('AP Transaction'),
1102 submit => [ '#create_new_form', { action => 'ap_transaction' } ],
1105 $::locale->text('Sales Invoice'),
1106 submit => [ '#create_new_form', { action => 'sales_invoice' } ],
1109 $::locale->text('Vendor Invoice'),
1110 submit => [ '#create_new_form', { action => 'vendor_invoice' } ],
1112 ], # end of combobox "Create new"
1118 $::lxdebug->enter_sub;
1119 $::auth->assert('gl_transactions');
1123 $::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");
1125 my @old_project_ids = grep { $_ } map{ $::form->{"project_id_$_"} } 1..$::form->{rowcount};
1126 my @conditions = @old_project_ids ? (id => \@old_project_ids) : ();
1127 $::form->{ALL_PROJECTS} = SL::DB::Manager::Project->get_all_sorted(query => [ or => [ active => 1, @conditions ]]);
1130 "charts" => { "key" => "ALL_CHARTS", "transdate" => $::form->{transdate} },
1133 # we cannot book on charttype header
1134 @{ $::form->{ALL_CHARTS} } = grep { $_->{charttype} ne 'H' } @{ $::form->{ALL_CHARTS} };
1135 $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
1137 my $title = $::form->{title};
1138 $::form->{title} = $::locale->text("$title General Ledger Transaction");
1139 # $locale->text('Add General Ledger Transaction')
1140 # $locale->text('Edit General Ledger Transaction')
1142 map { $::form->{$_} =~ s/\"/"/g }
1146 $::request->{layout}->focus("#reference");
1147 $::form->{taxincluded} = "1";
1149 $::request->{layout}->focus("#accno_id_$::form->{rowcount}_name");
1152 $::form->{previous_id} ||= "--";
1153 $::form->{previous_gldate} ||= "--";
1155 setup_gl_action_bar();
1158 print $::form->parse_html_template('gl/form_header', {
1159 hide_title => $title,
1160 readonly => $::form->{id} && ($::form->{locked} || !_get_radieren()),
1163 $::lxdebug->leave_sub;
1168 $::lxdebug->enter_sub;
1169 $::auth->assert('gl_transactions');
1171 my ($follow_ups, $follow_ups_due);
1173 if ($::form->{id}) {
1174 $follow_ups = FU->follow_ups('trans_id' => $::form->{id}, 'not_done' => 1);
1175 $follow_ups_due = sum map { $_->{due} * 1 } @{ $follow_ups || [] };
1178 print $::form->parse_html_template('gl/form_footer', {
1179 radieren => _get_radieren(),
1180 follow_ups => $follow_ups,
1181 follow_ups_due => $follow_ups_due,
1184 $::lxdebug->leave_sub;
1188 $main::lxdebug->enter_sub();
1190 my $form = $main::form;
1191 my %myconfig = %main::myconfig;
1192 my $locale = $main::locale;
1194 if (GL->delete_transaction(\%myconfig, \%$form)){
1195 # saving the history
1196 if(!exists $form->{addition} && $form->{id} ne "") {
1197 $form->{snumbers} = qq|gltransaction_| . $form->{id};
1198 $form->{addition} = "DELETED";
1199 $form->{what_done} = "gl_transaction";
1200 $form->save_history;
1202 # /saving the history
1203 $form->redirect($locale->text('Transaction deleted!'))
1205 $form->error($locale->text('Cannot delete transaction!'));
1206 $main::lxdebug->leave_sub();
1210 sub post_transaction {
1211 $main::lxdebug->enter_sub();
1213 my $form = $main::form;
1214 my %myconfig = %main::myconfig;
1215 my $locale = $main::locale;
1217 # check if there is something in reference and date
1218 $form->isblank("reference", $locale->text('Reference missing!'));
1219 $form->isblank("transdate", $locale->text('Transaction Date missing!'));
1220 $form->isblank("description", $locale->text('Description missing!'));
1222 my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
1223 my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
1230 my $creditcount = 0;
1232 my %split_safety = ();
1234 my $dbh = SL::DB->client->dbh;
1235 my ($notax_id) = selectrow_query($form, $dbh, "SELECT id FROM tax WHERE taxkey = 0 LIMIT 1", );
1236 my $zerotaxes = selectall_hashref_query($form, $dbh, "SELECT id FROM tax WHERE rate = 0", );
1238 my @flds = qw(accno_id debit credit projectnumber fx_transaction source memo tax taxchart);
1240 for my $i (1 .. $form->{rowcount}) {
1241 next if $form->{"debit_$i"} eq "" && $form->{"credit_$i"} eq "";
1243 for (qw(debit credit tax)) {
1244 $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"});
1248 $debitcredit = ($form->{"debit_$i"} == 0) ? "0" : "1";
1250 $split_safety{ $form->{"debit_$i"} <=> 0 }++;
1251 $split_safety{ - $form->{"credit_$i"} <=> 0 }++;
1259 if (($debitcount >= 2) && ($creditcount == 2)) {
1260 $form->{"credit_$i"} = 0;
1261 $form->{"tax_$i"} = 0;
1263 $form->{creditlock} = 1;
1265 if (($creditcount >= 2) && ($debitcount == 2)) {
1266 $form->{"debit_$i"} = 0;
1267 $form->{"tax_$i"} = 0;
1269 $form->{debitlock} = 1;
1271 if (($creditcount == 1) && ($debitcount == 2)) {
1272 $form->{creditlock} = 1;
1274 if (($creditcount == 2) && ($debitcount == 1)) {
1275 $form->{debitlock} = 1;
1277 if ($debitcredit && $credittax) {
1278 $form->{"taxchart_$i"} = "$notax_id--0.00000";
1280 if (!$debitcredit && $debittax) {
1281 $form->{"taxchart_$i"} = "$notax_id--0.00000";
1283 my $amount = ($form->{"debit_$i"} == 0)
1284 ? $form->{"credit_$i"}
1285 : $form->{"debit_$i"};
1287 if (($debitcredit && $credittax) || (!$debitcredit && $debittax)) {
1288 $form->{"taxchart_$i"} = "$notax_id--0.00000";
1289 $form->{"tax_$i"} = 0;
1291 my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
1292 my $iswithouttax = grep { $_->{id} == $taxkey } @{ $zerotaxes };
1293 if (!$iswithouttax) {
1300 my ($tmpnetamount,$tmpdiff);
1301 ($tmpnetamount,$form->{"tax_$i"},$tmpdiff) = $form->calculate_tax($amount,$rate,$form->{taxincluded} *= 1,2);
1303 $form->{"debit_$i"} = $tmpnetamount;
1305 $form->{"credit_$i"} = $tmpnetamount;
1309 $form->{"tax_$i"} = 0;
1312 for (@flds) { $a[$j]->{$_} = $form->{"${_}_$i"} }
1316 if ($split_safety{-1} > 1 && $split_safety{1} > 1) {
1317 $::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. " .
1318 "Due to known problems involving accounting software kivitendo does not allow these."));
1321 for my $i (1 .. $count) {
1323 for (@flds) { $form->{"${_}_$i"} = $a[$j]->{$_} }
1326 for my $i ($count + 1 .. $form->{rowcount}) {
1327 for (@flds) { delete $form->{"${_}_$i"} }
1330 my ($debit, $credit, $taxtotal);
1331 for my $i (1 .. $form->{rowcount}) {
1332 my $dr = $form->{"debit_$i"};
1333 my $cr = $form->{"credit_$i"};
1334 my $tax = $form->{"tax_$i"};
1336 $form->error($locale->text('Cannot post transaction with a debit and credit entry for the same account!'));
1338 $debit += $dr + $tax if $dr;
1339 $credit += $cr + $tax if $cr;
1340 $taxtotal += $tax if $form->{taxincluded}
1343 $form->{taxincluded} = 0 if !$taxtotal;
1345 # this is just for the wise guys
1347 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
1348 if ($form->date_max_future($form->{"transdate"}, \%myconfig));
1349 $form->error($locale->text('Cannot post transaction for a closed period!'))
1350 if ($form->date_closed($form->{"transdate"}, \%myconfig));
1351 if ($form->round_amount($debit, 2) != $form->round_amount($credit, 2)) {
1352 $form->error($locale->text('Out of balance transaction!'));
1355 if ($form->round_amount($debit, 2) + $form->round_amount($credit, 2) == 0) {
1356 $form->error($locale->text('Empty transaction!'));
1360 # start transaction (post + history + (optional) banktrans)
1361 SL::DB->client->with_transaction(sub {
1363 if ((my $errno = GL->post_transaction(\%myconfig, \%$form)) <= -1) {
1366 $err[1] = $locale->text('Cannot have a value in both Debit and Credit!');
1367 $err[2] = $locale->text('Debit and credit out of balance!');
1368 $err[3] = $locale->text('Cannot post a transaction without a value!');
1372 # saving the history
1373 if(!exists $form->{addition} && $form->{id} ne "") {
1374 $form->{snumbers} = qq|gltransaction_| . $form->{id};
1375 $form->{addition} = "POSTED";
1376 $form->{what_done} = "gl transaction";
1377 $form->save_history;
1380 # Case BankTransaction: update RecordLink and BankTransaction
1381 if ($form->{callback} =~ /BankTransaction/ && $form->{bt_id}) {
1382 # set invoice_amount - we only rely on bt_id in form, do all other stuff ui independent
1383 # die if we have a unlogic or NYI case and abort the whole transaction
1384 my ($bt, $chart_id, $payment);
1385 require SL::DB::Manager::BankTransaction;
1387 $bt = SL::DB::Manager::BankTransaction->find_by(id => $::form->{bt_id});
1388 die "No bank transaction found" unless $bt;
1390 $chart_id = SL::DB::Manager::BankAccount->find_by(id => $bt->local_bank_account_id)->chart_id;
1391 die "no chart id" unless $chart_id;
1393 $payment = SL::DB::Manager::AccTransaction->get_all(where => [ trans_id => $::form->{id},
1394 chart_link => { like => '%_paid%' },
1395 chart_id => $chart_id ]);
1396 die "guru meditation error: Can only assign amount to one bank account booking" if scalar @{ $payment } > 1;
1398 # credit/debit * -1 matches the sign for bt.amount and bt.invoice_amount
1400 die "Can only assign the full (partial) bank amount to a single general ledger booking: " . $bt->not_assigned_amount . " " . ($payment->[0]->amount * -1)
1401 unless (abs($bt->not_assigned_amount - ($payment->[0]->amount * -1)) < 0.001);
1403 $bt->update_attributes(invoice_amount => $bt->invoice_amount + ($payment->[0]->amount * -1));
1405 # create record_link
1407 from_table => 'bank_transactions',
1408 from_id => $::form->{bt_id},
1410 to_id => $::form->{id},
1412 SL::DB::RecordLink->new(%props)->save;
1413 # and tighten holy acc_trans_id for this bank_transaction
1415 acc_trans_id => $payment->[0]->acc_trans_id,
1416 bank_transaction_id => $bt->id,
1417 gl_id => $payment->[0]->trans_id,
1419 my $bta = SL::DB::BankTransactionAccTrans->new(%props_acc);
1424 }) or do { die SL::DB->client->error };
1426 $main::lxdebug->leave_sub();
1430 $main::lxdebug->enter_sub();
1432 $main::auth->assert('gl_transactions');
1434 my $form = $main::form;
1435 my $locale = $main::locale;
1437 if ($::myconfig{mandatory_departments} && !$form->{department_id}) {
1438 $form->error($locale->text('You have to specify a department.'));
1441 $form->{title} = $locale->text("$form->{title} General Ledger Transaction");
1442 $form->{storno} = 0;
1445 if ($::instance_conf->get_webdav) {
1446 SL::Webdav->new(type => 'general_ledger',
1447 number => $form->{id},
1451 my $msg = $::locale->text("General ledger transaction '#1' posted (ID: #2)", $form->{reference}, $form->{id});
1452 if ($form->{callback} =~ /BankTransaction/ && $form->{bt_id}) {
1453 $form->redirect($msg);
1455 } elsif ('doc-tab' eq $form->{after_action}) {
1456 # Redirect with callback containing a fragment does not work (by now)
1457 # because the callback info is stored in the session an parsing the
1458 # callback parameters does not support fragments (see SL::Form::redirect).
1459 # So use flash_later for the message and redirect_headers for redirecting.
1460 my $add_doc_url = build_std_url("script=gl.pl", 'action=edit', 'id=' . E($form->{id}), 'fragment=ui-tabs-docs');
1461 SL::Helper::Flash::flash_later('info', $msg);
1462 print $form->redirect_header($add_doc_url);
1463 $::dispatcher->end_request;
1466 $form->{callback} = build_std_url("action=add", "show_details");
1467 $form->redirect($msg);
1470 $main::lxdebug->leave_sub();
1474 $main::lxdebug->enter_sub();
1476 $main::auth->assert('gl_transactions');
1478 my $form = $main::form;
1482 $main::lxdebug->leave_sub();
1487 $main::lxdebug->enter_sub();
1489 $main::auth->assert('gl_transactions');
1491 my $form = $main::form;
1492 my %myconfig = %main::myconfig;
1493 my $locale = $main::locale;
1495 # don't cancel cancelled transactions
1496 if (IS->has_storno(\%myconfig, $form, 'gl')) {
1497 $form->{title} = $locale->text("Cancel Accounts Receivables Transaction");
1498 $form->error($locale->text("Transaction has already been cancelled!"));
1501 GL->storno($form, \%myconfig, $form->{id});
1503 # saving the history
1504 if(!exists $form->{addition} && $form->{id} ne "") {
1505 $form->{snumbers} = qq|gltransaction_| . $form->{id};
1506 $form->{addition} = "STORNO";
1507 $form->{what_done} = "gl_transaction";
1508 $form->save_history;
1510 # /saving the history
1512 $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
1514 $main::lxdebug->leave_sub();
1518 call_sub($main::form->{nextsub});
1521 sub get_tax_dropdown {
1522 my $transdate = $::form->{transdate} ? DateTime->from_kivitendo($::form->{transdate}) : DateTime->today_local;
1523 my $deliverydate = $::form->{deliverydate} ? DateTime->from_kivitendo($::form->{deliverydate}) : undef;
1524 my @tax_accounts = GL->get_active_taxes_for_chart($::form->{accno_id}, $deliverydate // $transdate);
1525 my $html = $::form->parse_html_template("gl/update_tax_accounts", { TAX_ACCOUNTS => \@tax_accounts });
1527 print $::form->ajax_response_header, $html;
1530 sub get_chart_balance {
1531 my %balances = GL->get_chart_balances($::form->{accno_id});
1532 my $balance = $::form->format_amount(\%::myconfig, $balances{ $::form->{accno_id} }, 2, 'DRCR');
1534 print $::form->ajax_response_header, $balance;