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;
46 use SL::DB::ValidityToken;
47 use SL::DB::GLTransaction;
50 use SL::Helper::Flash qw(flash flash_later);
52 use SL::ReportGenerator;
53 use SL::DBUtils qw(selectrow_query selectall_hashref_query);
55 use SL::Locale::String qw(t8);
56 use SL::Helper::GlAttachments qw(count_gl_attachments);
57 use SL::Presenter::Tag;
58 use SL::Presenter::Chart;
59 require "bin/mozilla/common.pl";
60 require "bin/mozilla/reportgenerator.pl";
62 # this is for our long dates
63 # $locale->text('January')
64 # $locale->text('February')
65 # $locale->text('March')
66 # $locale->text('April')
67 # $locale->text('May ')
68 # $locale->text('June')
69 # $locale->text('July')
70 # $locale->text('August')
71 # $locale->text('September')
72 # $locale->text('October')
73 # $locale->text('November')
74 # $locale->text('December')
76 # this is for our short month
77 # $locale->text('Jan')
78 # $locale->text('Feb')
79 # $locale->text('Mar')
80 # $locale->text('Apr')
81 # $locale->text('May')
82 # $locale->text('Jun')
83 # $locale->text('Jul')
84 # $locale->text('Aug')
85 # $locale->text('Sep')
86 # $locale->text('Oct')
87 # $locale->text('Nov')
88 # $locale->text('Dec')
90 sub load_record_template {
91 $::auth->assert('gl_transactions');
93 # Load existing template and verify that its one for this module.
94 my $template = SL::DB::RecordTemplate
95 ->new(id => $::form->{id})
97 with_object => [ qw(customer payment currency record_items record_items.chart) ],
100 die "invalid template type" unless $template->template_type eq 'gl_transaction';
102 $template->substitute_variables;
103 my $payment_suggestion = $::form->{form_defaults}->{amount_1};
105 # Clean the current $::form before rebuilding it from the template.
106 my $form_defaults = delete $::form->{form_defaults};
107 delete @{ $::form }{ grep { !m{^(?:script|login)$}i } keys %{ $::form } };
110 GL->transaction(\%::myconfig, $dummy_form);
112 # Fill $::form from the template.
113 my $today = DateTime->today_local;
114 $::form->{title} = "Add";
115 $::form->{transdate} = $today->to_kivitendo;
116 $::form->{duedate} = $today->to_kivitendo;
117 $::form->{rowcount} = @{ $template->items };
118 $::form->{paidaccounts} = 1;
119 $::form->{$_} = $template->$_ for qw(department_id taxincluded ob_transaction cb_transaction reference description show_details transaction_description);
120 $::form->{$_} = $dummy_form->{$_} for qw(closedto revtrans previous_id previous_gldate);
123 foreach my $item (@{ $template->items }) {
126 my $active_taxkey = $item->chart->get_active_taxkey;
127 my $taxes = SL::DB::Manager::Tax->get_all(
128 where => [ chart_categories => { like => '%' . $item->chart->category . '%' }],
129 sort_by => 'taxkey, rate',
132 my $tax = first { $item->tax_id == $_->id } @{ $taxes };
133 $tax //= first { $active_taxkey->tax_id == $_->id } @{ $taxes };
134 $tax //= $taxes->[0];
141 $::form->{"accno_id_${row}"} = $item->chart_id;
142 $::form->{"previous_accno_id_${row}"} = $item->chart_id;
143 $::form->{"debit_${row}"} = $::form->format_amount(\%::myconfig, ($payment_suggestion ? $payment_suggestion : $item->amount1), 2) if $item->amount1 * 1;
144 $::form->{"credit_${row}"} = $::form->format_amount(\%::myconfig, ($payment_suggestion ? $payment_suggestion : $item->amount2), 2) if $item->amount2 * 1;
145 $::form->{"taxchart_${row}"} = $item->tax_id . '--' . $tax->rate;
146 $::form->{"${_}_${row}"} = $item->$_ for qw(source memo project_id);
149 $::form->{$_} = $form_defaults->{$_} for keys %{ $form_defaults // {} };
151 flash('info', $::locale->text("The record template '#1' has been loaded.", $template->template_name));
153 $::form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_GL_TRANSACTION_POST())->token;
156 keep_rows_without_amount => 1,
157 dont_add_new_row => 1,
161 sub save_record_template {
162 $::auth->assert('gl_transactions');
164 my $template = $::form->{record_template_id} ? SL::DB::RecordTemplate->new(id => $::form->{record_template_id})->load : SL::DB::RecordTemplate->new;
165 my $js = SL::ClientJS->new(controller => SL::Controller::Base->new);
166 my $new_name = $template->template_name_to_use($::form->{record_template_new_template_name});
167 $js->dialog->close('#record_template_dialog');
170 # bank transactions need amounts for assignment
172 $can_save = 1 if ($::form->{credit_1} > 0 && $::form->{debit_2} > 0 && $::form->{credit_2} == 0 && $::form->{debit_1} == 0);
173 $can_save = 1 if ($::form->{credit_2} > 0 && $::form->{debit_1} > 0 && $::form->{credit_1} == 0 && $::form->{debit_2} == 0);
174 return $js->flash('error', t8('Can only save template if amounts,i.e. 1 for debit and credit are set.'))->render unless $can_save;
177 $_->{chart_id} && (($_->{tax_id} // '') ne '')
179 +{ chart_id => $::form->{"accno_id_${_}"},
180 amount1 => $::form->parse_amount(\%::myconfig, $::form->{"debit_${_}"}),
181 amount2 => $::form->parse_amount(\%::myconfig, $::form->{"credit_${_}"}),
182 tax_id => (split m{--}, $::form->{"taxchart_${_}"})[0],
183 project_id => $::form->{"project_id_${_}"} || undef,
184 source => $::form->{"source_${_}"},
185 memo => $::form->{"memo_${_}"},
187 } (1..($::form->{rowcount} || 1));
189 $template->assign_attributes(
190 template_type => 'gl_transaction',
191 template_name => $new_name,
193 currency_id => $::instance_conf->get_currency_id,
194 department_id => $::form->{department_id} || undef,
195 project_id => $::form->{globalproject_id} || undef,
196 taxincluded => $::form->{taxincluded} ? 1 : 0,
197 ob_transaction => $::form->{ob_transaction} ? 1 : 0,
198 cb_transaction => $::form->{cb_transaction} ? 1 : 0,
199 reference => $::form->{reference},
200 description => $::form->{description},
201 show_details => $::form->{show_details},
202 transaction_description => $::form->{transaction_description},
212 ->flash('error', $::locale->text("Saving the record template '#1' failed.", $new_name))
217 ->flash('info', $::locale->text("The record template '#1' has been saved.", $new_name))
222 $main::lxdebug->enter_sub();
224 $main::auth->assert('gl_transactions');
226 my $form = $main::form;
227 my %myconfig = %main::myconfig;
229 $form->{title} = "Add";
231 $form->{callback} = "gl.pl?action=add" unless $form->{callback};
233 # we use this only to set a default date
234 # yep. aber er holt hier auch schon ALL_CHARTS. Aufwand / Nutzen? jb
235 GL->transaction(\%myconfig, \%$form);
237 $form->{rowcount} = 2;
243 $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
245 $form->{show_details} = $myconfig{show_form_details} unless defined $form->{show_details};
247 if (!$form->{form_validity_token}) {
248 $form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_GL_TRANSACTION_POST())->token;
252 $main::lxdebug->leave_sub();
256 sub add_from_email_journal {
257 die "No 'email_journal_id' was given." unless ($::form->{email_journal_id});
261 sub load_record_template_from_email_journal {
262 die "No 'email_journal_id' was given." unless ($::form->{email_journal_id});
263 &load_record_template;
266 sub edit_with_email_journal_workflow {
268 die "No 'email_journal_id' was given." unless ($::form->{email_journal_id});
269 $::form->{workflow_email_journal_id} = delete $::form->{email_journal_id};
270 $::form->{workflow_email_attachment_id} = delete $::form->{email_attachment_id};
271 $::form->{workflow_email_callback} = delete $::form->{callback};
276 sub prepare_transaction {
277 $main::lxdebug->enter_sub();
279 $main::auth->assert('gl_transactions');
281 my $form = $main::form;
282 my %myconfig = %main::myconfig;
284 GL->transaction(\%myconfig, \%$form);
286 $form->{amount} = $form->format_amount(\%myconfig, $form->{amount}, 2);
288 $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
293 foreach my $ref (@{ $form->{GL} }) {
295 if ($tax && ($ref->{accno} eq $taxaccno)) {
296 $form->{"tax_$j"} = abs($ref->{amount});
297 $form->{"taxchart_$j"} = $ref->{id} . "--" . $ref->{taxrate};
298 if ($form->{taxincluded}) {
299 if ($ref->{amount} < 0) {
300 $form->{"debit_$j"} += $form->{"tax_$j"};
302 $form->{"credit_$j"} += $form->{"tax_$j"};
305 $form->{"project_id_$j"} = $ref->{project_id};
308 $form->{"accno_id_$i"} = $ref->{chart_id};
309 for (qw(fx_transaction source memo)) { $form->{"${_}_$i"} = $ref->{$_} }
310 if ($ref->{amount} < 0) {
311 $form->{totaldebit} -= $ref->{amount};
312 $form->{"debit_$i"} = $ref->{amount} * -1;
314 $form->{totalcredit} += $ref->{amount};
315 $form->{"credit_$i"} = $ref->{amount};
317 $form->{"taxchart_$i"} = $ref->{id}."--0.00000";
318 $form->{"project_id_$i"} = $ref->{project_id};
321 if ($ref->{taxaccno} && !$tax) {
322 $taxaccno = $ref->{taxaccno};
330 $form->{rowcount} = $i;
332 ($form->datetonum($form->{transdate}, \%myconfig) <=
333 $form->datetonum($form->{closedto}, \%myconfig));
335 $main::lxdebug->leave_sub();
339 $main::lxdebug->enter_sub();
341 $main::auth->assert('gl_transactions');
343 my $form = $main::form;
344 my %myconfig = %main::myconfig;
346 prepare_transaction();
348 $form->{title} = "Edit";
350 $form->{show_details} = $myconfig{show_form_details} unless defined $form->{show_details};
352 if ($form->{id} && $::instance_conf->get_webdav) {
353 my $webdav = SL::Webdav->new(
354 type => 'general_ledger',
355 number => $form->{id},
357 my @all_objects = $webdav->get_all_objects;
358 @{ $form->{WEBDAV} } = map { { name => $_->filename,
360 link => File::Spec->catfile($_->full_filedescriptor),
367 $main::lxdebug->leave_sub();
372 $::lxdebug->enter_sub;
373 $::auth->assert('general_ledger | gl_transactions');
376 projects => { key => "ALL_PROJECTS", all => 1 },
378 $::form->{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]);
379 $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
381 setup_gl_search_action_bar();
383 $::form->{title} = t8('Journal');
385 print $::form->parse_html_template('gl/search', {
386 employee_label => sub { "$_[0]{id}--$_[0]{name}" },
389 $::lxdebug->leave_sub;
392 sub create_subtotal_row {
393 $main::lxdebug->enter_sub();
395 my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
397 my $form = $main::form;
398 my %myconfig = %main::myconfig;
400 my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
402 map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
404 map { $totals->{$_} = 0 } @{ $subtotal_columns };
406 $main::lxdebug->leave_sub();
411 sub generate_report {
412 $main::lxdebug->enter_sub();
414 $main::auth->assert('general_ledger | gl_transactions');
416 my $form = $main::form;
417 my %myconfig = %main::myconfig;
418 my $locale = $main::locale;
420 # 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
422 # <form method=post action=gl.pl>
423 # <input type=hidden name=sort value=datesort> # form->{sort} setzen
424 # <input type=hidden name=nextsub value=generate_report>
426 # anhand von neuer Variable datesort wird jetzt $form->{sort} auf transdate oder gldate gesetzt
427 # damit ist die Hidden Variable "sort" wahrscheinlich sogar überflüssig
429 # ändert man die Sortierreihenfolge per Klick auf eine der Überschriften wird die Variable "sort" per GET übergeben, z.B. id,transdate, gldate, ...
430 # 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
432 if ( $form->{sort} eq 'datesort' ) { # sollte bei einem Post (Aufruf aus Suchmaske) immer wahr sein
433 # je nachdem ob in Suchmaske "transdate" oder "gldate" ausgesucht wurde erstes Suchergebnis entsprechend sortieren
434 $form->{sort} = $form->{datesort};
438 report_generator_set_default_sort("$form->{datesort}", 1);
439 # report_generator_set_default_sort('transdate', 1);
441 GL->all_transactions(\%myconfig, \%$form);
443 my %acctype = ('A' => $locale->text('Asset'),
444 'C' => $locale->text('Contra'),
445 'L' => $locale->text('Liability'),
446 'Q' => $locale->text('Equity'),
447 'I' => $locale->text('Revenue'),
448 'E' => $locale->text('Expense'),);
450 $form->{title} = $locale->text('Journal');
451 if ($form->{category} ne 'X') {
452 $form->{title} .= " : " . $locale->text($acctype{ $form->{category} });
455 $form->{landscape} = 1;
457 my $ml = ($form->{ml} =~ /(A|E|Q)/) ? -1 : 1;
460 transdate gldate id reference
461 description notes transaction_description source
462 doccnt debit debit_accno
463 credit credit_accno debit_tax debit_tax_accno
464 credit_tax credit_tax_accno balance projectnumbers
468 # add employee here, so that variable is still known and passed in url when choosing a different sort order in resulting table
469 my @hidden_variables = qw(accno source reference description notes project_id datefrom dateto employee_id datesort category l_subtotal department_id transaction_description);
470 push @hidden_variables, map { "l_${_}" } @columns;
472 my $employee = $form->{employee_id} ? SL::DB::Employee->new(id => $form->{employee_id})->load->name : '';
474 my (@options, @date_options);
475 push @options, $locale->text('Account') . " : $form->{accno} $form->{account_description}" if ($form->{accno});
476 push @options, $locale->text('Source') . " : $form->{source}" if ($form->{source});
477 push @options, $locale->text('Reference') . " : $form->{reference}" if ($form->{reference});
478 push @options, $locale->text('Description') . " : $form->{description}" if ($form->{description});
479 push @options, $locale->text('Notes') . " : $form->{notes}" if ($form->{notes});
480 push @options, $locale->text('Transaction description') . " : $form->{transaction_description}" if $form->{transaction_description};
481 push @options, $locale->text('Employee') . " : $employee" if $employee;
482 my $datesorttext = $form->{datesort} eq 'transdate' ? $locale->text('Transdate') : $locale->text('Gldate');
483 push @date_options, "$datesorttext" if ($form->{datesort} and ($form->{datefrom} or $form->{dateto}));
484 push @date_options, $locale->text('From'), $locale->date(\%myconfig, $form->{datefrom}, 1) if ($form->{datefrom});
485 push @date_options, $locale->text('Bis'), $locale->date(\%myconfig, $form->{dateto}, 1) if ($form->{dateto});
486 push @options, join(' ', @date_options) if (scalar @date_options);
488 if ($form->{department_id}) {
489 my $department = SL::DB::Manager::Department->find_by( id => $form->{department_id} );
490 push @options, $locale->text('Department') . " : " . $department->description;
493 my $callback = build_std_url('action=generate_report', grep { $form->{$_} } @hidden_variables);
495 $form->{l_credit_accno} = 'Y';
496 $form->{l_debit_accno} = 'Y';
497 $form->{l_credit_tax} = 'Y';
498 $form->{l_debit_tax} = 'Y';
499 # $form->{l_gldate} = 'Y'; # Spalte mit gldate immer anzeigen
500 $form->{l_credit_tax_accno} = 'Y';
501 $form->{l_datesort} = 'Y';
502 $form->{l_debit_tax_accno} = 'Y';
503 $form->{l_balance} = $form->{accno} ? 'Y' : '';
504 $form->{l_doccnt} = $form->{l_source} ? 'Y' : '';
507 'id' => { 'text' => $locale->text('ID'), },
508 'transdate' => { 'text' => $locale->text('Transdate'), },
509 'gldate' => { 'text' => $locale->text('Gldate'), },
510 'reference' => { 'text' => $locale->text('Reference'), },
511 'source' => { 'text' => $locale->text('Source'), },
512 'doccnt' => { 'text' => $locale->text('Document Count'), },
513 'description' => { 'text' => $locale->text('Description'), },
514 'notes' => { 'text' => $locale->text('Notes'), },
515 'debit' => { 'text' => $locale->text('Debit'), },
516 'debit_accno' => { 'text' => $locale->text('Debit Account'), },
517 'credit' => { 'text' => $locale->text('Credit'), },
518 'credit_accno' => { 'text' => $locale->text('Credit Account'), },
519 'debit_tax' => { 'text' => $locale->text('Debit Tax'), },
520 'debit_tax_accno' => { 'text' => $locale->text('Debit Tax Account'), },
521 'credit_tax' => { 'text' => $locale->text('Credit Tax'), },
522 'credit_tax_accno' => { 'text' => $locale->text('Credit Tax Account'), },
523 'balance' => { 'text' => $locale->text('Balance'), },
524 'projectnumbers' => { 'text' => $locale->text('Project Numbers'), },
525 'department' => { 'text' => $locale->text('Department'), },
526 'employee' => { 'text' => $locale->text('Employee'), },
527 'transaction_description' => { 'text' => $locale->text('Transaction description'), },
530 foreach my $name (qw(id transdate gldate reference description debit_accno credit_accno debit_tax_accno credit_tax_accno department transaction_description)) {
531 my $sortname = $name =~ m/accno/ ? 'accno' : $name;
532 my $sortdir = $sortname eq $form->{sort} ? 1 - $form->{sortdir} : $form->{sortdir};
533 $column_defs{$name}->{link} = $callback . "&sort=$sortname&sortdir=$sortdir";
536 map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
537 map { $column_defs{$_}->{visible} = 0 } qw(debit_accno credit_accno debit_tax_accno credit_tax_accno) if $form->{accno};
539 my %column_alignment;
540 map { $column_alignment{$_} = 'right' } qw(balance id debit credit debit_tax credit_tax balance);
541 map { $column_alignment{$_} = 'center' } qw(transdate gldate reference debit_accno credit_accno debit_tax_accno credit_tax_accno);
542 map { $column_alignment{$_} = 'left' } qw(description source notes);
543 map { $column_defs{$_}->{align} = $column_alignment{$_} } keys %column_alignment;
545 my $report = SL::ReportGenerator->new(\%myconfig, $form);
547 $report->set_columns(%column_defs);
548 $report->set_column_order(@columns);
550 $form->{l_attachments} = 'Y';
551 $report->set_export_options('generate_report', @hidden_variables, qw(sort sortdir l_attachments));
553 $report->set_sort_indicator($form->{sort} eq 'accno' ? 'debit_accno' : $form->{sort}, $form->{sortdir});
555 $report->set_options('top_info_text' => join("\n", @options),
556 'output_format' => 'HTML',
557 'title' => $form->{title},
558 'attachment_basename' => $locale->text('general_ledger_list') . strftime('_%Y%m%d', localtime time),
560 $report->set_options_from_form();
561 $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
563 # add sort to callback
564 $form->{callback} = "$callback&sort=" . E($form->{sort}) . "&sortdir=" . E($form->{sortdir});
567 my @totals_columns = qw(debit credit debit_tax credit_tax);
568 my %subtotals = map { $_ => 0 } @totals_columns;
569 my %totals = map { $_ => 0 } @totals_columns;
572 foreach my $ref (@{ $form->{GL} }) {
576 foreach my $key (qw(debit credit debit_tax credit_tax)) {
578 foreach my $idx (sort keys(%{ $ref->{$key} })) {
579 my $value = $ref->{$key}->{$idx};
580 $subtotals{$key} += $value;
581 $totals{$key} += $value;
582 if ($key =~ /debit.*/) {
587 $form->{balance} = $form->{balance} + $value * $ml;
588 push @{ $rows{$key} }, $form->format_amount(\%myconfig, $value, 2);
592 foreach my $key (qw(debit_accno credit_accno debit_tax_accno credit_tax_accno ac_transdate source)) {
593 my $col = $key eq 'ac_transdate' ? 'transdate' : $key;
594 $rows{$col} = [ map { $ref->{$key}->{$_} } sort keys(%{ $ref->{$key} }) ];
598 map { $row->{$_} = { 'data' => '', 'align' => $column_alignment{$_} } } @columns;
600 if ( $form->{l_doccnt} ) {
601 $row->{doccnt}->{data} = SL::Helper::GlAttachments->count_gl_pdf_attachments($ref->{id},$ref->{type});
605 if ($form->{balance} < 0) {
608 } elsif ($form->{balance} > 0) {
612 my $data = $form->format_amount(\%myconfig, ($form->{balance} * $ml), 2);
615 $row->{balance}->{data} = $data;
616 $row->{projectnumbers}->{data} = join ", ", sort { lc($a) cmp lc($b) } keys %{ $ref->{projectnumbers} };
618 map { $row->{$_}->{data} = $ref->{$_} } qw(id reference description notes gldate employee department transaction_description);
620 map { $row->{$_}->{data} = \@{ $rows{$_} }; } qw(transdate debit credit debit_accno credit_accno debit_tax_accno credit_tax_accno source);
622 foreach my $col (qw(debit_accno credit_accno debit_tax_accno credit_tax_accno)) {
623 $row->{$col}->{link} = [ map { "${callback}&accno=" . E($_) } @{ $rows{$col} } ];
626 map { $row->{$_}->{data} = \@{ $rows{$_} } if ($ref->{"${_}_accno"} ne "") } qw(debit_tax credit_tax);
628 $row->{reference}->{link} = build_std_url("script=$ref->{module}.pl", 'action=edit', 'id=' . E($ref->{id}), 'callback');
630 my $row_set = [ $row ];
632 if ( ($form->{l_subtotal} eq 'Y' && !$form->{report_generator_csv_options_for_import} )
633 && (($idx == (scalar @{ $form->{GL} } - 1))
634 || ($ref->{ $form->{sort} } ne $form->{GL}->[$idx + 1]->{ $form->{sort} }))) {
635 push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, [ qw(debit credit) ], 'listsubtotal');
638 $report->add_data($row_set);
643 # = 0 for balanced ledger
644 my $balanced_ledger = $totals{debit} + $totals{debit_tax} - $totals{credit} - $totals{credit_tax};
646 my $row = create_subtotal_row(\%totals, \@columns, \%column_alignment, [ qw(debit credit debit_tax credit_tax) ], 'listtotal');
649 if ($form->{balance} < 0) {
652 } elsif ($form->{balance} > 0) {
656 my $data = $form->format_amount(\%myconfig, ($form->{balance} * $ml), 2);
659 $row->{balance}->{data} = $data;
661 if ( !$form->{report_generator_csv_options_for_import} ) {
662 $report->add_separator();
663 $report->add_data($row);
666 my $raw_bottom_info_text;
668 if (!$form->{accno} && (abs($balanced_ledger) > 0.001)) {
669 $raw_bottom_info_text .=
670 '<p><span class="unbalanced_ledger">'
671 . $locale->text('Unbalanced Ledger')
673 . $form->format_amount(\%myconfig, $balanced_ledger, 3)
677 $raw_bottom_info_text .= $form->parse_html_template('gl/generate_report_bottom');
679 $report->set_options('raw_bottom_info_text' => $raw_bottom_info_text);
681 setup_gl_transactions_action_bar();
683 $report->generate_with_headers();
685 $main::lxdebug->leave_sub();
689 $::form->{transdate} = DateTime->today_local->to_kivitendo if !$::form->{transdate};
690 $::form->{gldate} = $::form->{transdate} if !$::form->{gldate};
691 $::form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_GL_TRANSACTION_POST())->token;
698 $main::lxdebug->enter_sub();
700 $main::auth->assert('gl_transactions');
702 my $form = $main::form;
703 my %myconfig = %main::myconfig;
705 $form->{oldtransdate} = $form->{transdate};
713 my ($debitcredit, $amount);
715 my $dbh = SL::DB->client->dbh;
716 my ($notax_id) = selectrow_query($form, $dbh, "SELECT id FROM tax WHERE taxkey = 0 LIMIT 1", );
717 my $zerotaxes = selectall_hashref_query($form, $dbh, "SELECT id FROM tax WHERE rate = 0", );
720 qw(accno_id debit credit projectnumber fx_transaction source memo tax taxchart);
722 for my $i (1 .. $form->{rowcount}) {
723 $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) for qw(debit credit tax);
725 next if !$form->{"debit_$i"} && !$form->{"credit_$i"} && !$params{keep_rows_without_amount};
728 $debitcredit = ($form->{"debit_$i"} == 0) ? "0" : "1";
735 if (($debitcount >= 2) && ($creditcount == 2)) {
736 $form->{"credit_$i"} = 0;
737 $form->{"tax_$i"} = 0;
739 $form->{creditlock} = 1;
741 if (($creditcount >= 2) && ($debitcount == 2)) {
742 $form->{"debit_$i"} = 0;
743 $form->{"tax_$i"} = 0;
745 $form->{debitlock} = 1;
747 if (($creditcount == 1) && ($debitcount == 2)) {
748 $form->{creditlock} = 1;
750 if (($creditcount == 2) && ($debitcount == 1)) {
751 $form->{debitlock} = 1;
753 if ($debitcredit && $credittax) {
754 $form->{"taxchart_$i"} = "$notax_id--0.00000";
756 if (!$debitcredit && $debittax) {
757 $form->{"taxchart_$i"} = "$notax_id--0.00000";
760 ($form->{"debit_$i"} == 0)
761 ? $form->{"credit_$i"}
762 : $form->{"debit_$i"};
764 if (($debitcredit && $credittax) || (!$debitcredit && $debittax)) {
765 $form->{"taxchart_$i"} = "$notax_id--0.00000";
766 $form->{"tax_$i"} = 0;
768 my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
769 my $iswithouttax = grep { $_->{id} == $taxkey } @{ $zerotaxes };
770 if (!$iswithouttax) {
777 my ($tmpnetamount,$tmpdiff);
778 ($tmpnetamount,$form->{"tax_$i"},$tmpdiff) = $form->calculate_tax($amount,$rate,$form->{taxincluded} *= 1,2);
780 for (@flds) { $a[$j]->{$_} = $form->{"${_}_$i"} }
784 for my $i (1 .. $count) {
786 for (@flds) { $form->{"${_}_$i"} = $a[$j]->{$_} }
789 for my $i ($count + 1 .. $form->{rowcount}) {
790 for (@flds) { delete $form->{"${_}_$i"} }
793 $form->{rowcount} = $count + ($params{dont_add_new_row} ? 0 : 1);
796 $main::lxdebug->leave_sub();
802 $main::lxdebug->enter_sub();
804 $main::auth->assert('gl_transactions');
806 my $form = $main::form;
807 my %myconfig = %main::myconfig;
811 # for $i (1 .. $form->{rowcount}) {
812 # $form->{totaldebit} += $form->parse_amount(\%myconfig, $form->{"debit_$i"});
813 # $form->{totalcredit} += $form->parse_amount(\%myconfig, $form->{"credit_$i"});
817 &display_rows($init);
819 $main::lxdebug->leave_sub();
825 $main::lxdebug->enter_sub();
827 $main::auth->assert('gl_transactions');
829 my $form = $main::form;
830 my %myconfig = %main::myconfig;
831 my $cgi = $::request->{cgi};
833 my %balances = GL->get_chart_balances(map { $_->{id} } @{ $form->{ALL_CHARTS} });
835 $form->{debit_1} = 0 if !$form->{"debit_1"};
836 $form->{totaldebit} = 0;
837 $form->{totalcredit} = 0;
839 my %charts_by_id = map { ($_->{id} => $_) } @{ $::form->{ALL_CHARTS} };
840 my $default_chart = $::form->{ALL_CHARTS}[0];
841 my $transdate = $::form->{transdate} ? DateTime->from_kivitendo($::form->{transdate}) : DateTime->today_local;
842 my $deliverydate = $::form->{deliverydate} ? DateTime->from_kivitendo($::form->{deliverydate}) : undef;
844 my ($source, $memo, $source_hidden, $memo_hidden);
845 for my $i (1 .. $form->{rowcount}) {
846 if ($form->{show_details}) {
848 <td><input name="source_$i" value="$form->{"source_$i"}" size="16"></td>|;
850 <td><input name="memo_$i" value="$form->{"memo_$i"}" size="16"></td>|;
853 <input type="hidden" name="source_$i" value="$form->{"source_$i"}" size="16">|;
855 <input type="hidden" name="memo_$i" value="$form->{"memo_$i"}" size="16">|;
858 my %taxchart_labels = ();
859 my @taxchart_values = ();
861 my $accno_id = $::form->{"accno_id_$i"};
862 my $chart = $charts_by_id{$accno_id} // $default_chart;
863 $accno_id = $chart->{id};
864 my ($first_taxchart, $default_taxchart, $taxchart_to_use);
867 if ( $form->{"taxchart_$i"} ) {
868 ($used_tax_id) = split(/--/, $form->{"taxchart_$i"});
871 my $taxdate = $deliverydate ? $deliverydate : $transdate;
872 foreach my $item ( GL->get_active_taxes_for_chart($accno_id, $taxdate, $used_tax_id) ) {
873 my $key = $item->id . "--" . $item->rate;
874 $first_taxchart //= $item;
875 $default_taxchart = $item if $item->{is_default};
876 $taxchart_to_use = $item if $key eq $form->{"taxchart_$i"};
878 push(@taxchart_values, $key);
879 $taxchart_labels{$key} = $item->taxkey . " - " . $item->taxdescription . " " . $item->rate * 100 . ' %';
882 $taxchart_to_use //= $default_taxchart // $first_taxchart;
883 my $selected_taxchart = $taxchart_to_use->id . '--' . $taxchart_to_use->rate;
885 my $accno = qq|<td>| .
886 SL::Presenter::Chart::picker("accno_id_$i", $accno_id, style => "width: 300px") .
887 SL::Presenter::Tag::hidden_tag("previous_accno_id_$i", $accno_id)
889 my $tax_ddbox = qq|<td>| .
890 NTI($cgi->popup_menu('-name' => "taxchart_$i",
891 '-id' => "taxchart_$i",
892 '-style' => 'width:200px',
893 '-values' => \@taxchart_values,
894 '-labels' => \%taxchart_labels,
895 '-default' => $selected_taxchart))
898 my ($fx_transaction, $checked);
900 if ($form->{transfer}) {
901 $fx_transaction = qq|
902 <td><input name="fx_transaction_$i" class=checkbox type=checkbox value=1></td>
907 if ($form->{"debit_$i"} != 0) {
908 $form->{totaldebit} += $form->{"debit_$i"};
909 if (!$form->{taxincluded}) {
910 $form->{totaldebit} += $form->{"tax_$i"};
913 $form->{totalcredit} += $form->{"credit_$i"};
914 if (!$form->{taxincluded}) {
915 $form->{totalcredit} += $form->{"tax_$i"};
919 for (qw(debit credit tax)) {
922 ? $form->format_amount(\%myconfig, $form->{"${_}_$i"}, 2)
926 if ($i < $form->{rowcount}) {
927 if ($form->{transfer}) {
928 $checked = ($form->{"fx_transaction_$i"}) ? "1" : "";
929 my $x = ($checked) ? "x" : "";
930 $fx_transaction = qq|
931 <td><input type=hidden name="fx_transaction_$i" value="$checked">$x</td>
934 $form->hide_form("accno_$i");
937 if ($form->{transfer}) {
938 $fx_transaction = qq|
939 <td><input name="fx_transaction_$i" class=checkbox type=checkbox value=1></td>
944 my $debitreadonly = "";
945 my $creditreadonly = "";
946 if ($i == $form->{rowcount}) {
947 if ($form->{debitlock}) {
948 $debitreadonly = "readonly";
949 } elsif ($form->{creditlock}) {
950 $creditreadonly = "readonly";
954 my $projectnumber = SL::Presenter::Project::picker("project_id_$i", $form->{"project_id_$i"});
955 my $projectnumber_hidden = SL::Presenter::Tag::hidden_tag("project_id_$i", $form->{"project_id_$i"});
957 my $copy2credit = $i == 1 ? 'onkeyup="copy_debit_to_credit()"' : '';
958 my $balance = $form->format_amount(\%::myconfig, $balances{$accno_id} // 0, 2, 'DRCR');
960 # if we have a bt_chart_id we disallow changing the amount of the bank account
961 if ($form->{bt_chart_id}) {
962 $debitreadonly = $creditreadonly = "readonly" if ($form->{"accno_id_$i"} eq $form->{bt_chart_id});
963 $copy2credit = '' if $i == 1; # and disallow copy2credit
966 print qq|<tr valign=top>
968 <td id="chart_balance_$i" align="right">${balance}</td>
970 <td><input name="debit_$i" size="8" value="$form->{"debit_$i"}" accesskey=$i $copy2credit $debitreadonly></td>
971 <td><input name="credit_$i" size=8 value="$form->{"credit_$i"}" $creditreadonly></td>
972 <td><input type="hidden" name="tax_$i" value="$form->{"tax_$i"}">$form->{"tax_$i"}</td>
975 if ($form->{show_details}) {
979 <td>$projectnumber</td>
985 $projectnumber_hidden
993 $form->hide_form(qw(rowcount selectaccno));
995 $main::lxdebug->leave_sub();
1000 return ($::instance_conf->get_gl_changeable == 2) ? ($::form->current_date(\%::myconfig) eq $::form->{gldate}) : ($::instance_conf->get_gl_changeable == 1);
1003 sub setup_gl_action_bar {
1006 my $change_never = $::instance_conf->get_gl_changeable == 0;
1007 my $change_on_same_day_only = $::instance_conf->get_gl_changeable == 2 && ($form->current_date(\%::myconfig) ne $form->{gldate});
1008 my ($is_linked_bank_transaction, $is_linked_ap_transaction, $is_reconciled_bank_transaction);
1010 if ($form->{id} && SL::DB::Manager::BankTransactionAccTrans->find_by(gl_id => $form->{id})) {
1011 $is_linked_bank_transaction = 1;
1013 if ($form->{id} && SL::DB::Manager::ApGl->find_by(gl_id => $form->{id})) {
1014 $is_linked_ap_transaction = 1;
1016 # dont edit reconcilated bookings!
1018 my @acc_trans = map { $_->acc_trans_id } @{ SL::DB::Manager::AccTransaction->get_all( where => [ trans_id => $form->{id} ] ) };
1019 if (scalar @acc_trans && scalar @{ SL::DB::Manager::ReconciliationLink->get_all(where => [ acc_trans_id => [ @acc_trans ] ]) }) {
1020 $is_reconciled_bank_transaction = 1;
1023 my $create_post_action = sub {
1024 # $_[0]: description
1025 # $_[1]: after_action
1028 submit => [ '#form', { action => 'post', after_action => $_[1] } ],
1029 disabled => $form->{locked} ? t8('The billing period has already been locked.')
1030 : $form->{storno} ? t8('A canceled general ledger transaction cannot be posted.')
1031 : ($form->{id} && $change_never) ? t8('Changing general ledger transaction has been disabled in the configuration.')
1032 : ($form->{id} && $change_on_same_day_only) ? t8('General ledger transactions can only be changed on the day they are posted.')
1033 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
1034 : $is_linked_ap_transaction ? t8('This transaction is linked with a AP transaction. Please undo and redo the AP transaction booking if needed.')
1035 : $is_reconciled_bank_transaction ? t8('This transaction is reconciled with a bank transaction. Please undo the reconciliation if needed.')
1041 if ($::instance_conf->get_gl_add_doc && $::instance_conf->get_doc_storage) {
1042 %post_entry = (combobox => [ $create_post_action->(t8('Post'), 'doc-tab'),
1043 $create_post_action->(t8('Post and new booking')) ]);
1044 } elsif ($::instance_conf->get_doc_storage) {
1045 %post_entry = (combobox => [ $create_post_action->(t8('Post')),
1046 $create_post_action->(t8('Post and upload document'), 'doc-tab') ]);
1048 %post_entry = $create_post_action->(t8('Post'));
1050 push @{$post_entry{combobox}}, $create_post_action->(t8('Post and Close'), 'callback');
1052 for my $bar ($::request->layout->get('actionbar')) {
1056 submit => [ '#form', { action => 'update' } ],
1057 id => 'update_button',
1058 accesskey => 'enter',
1062 action => [ t8('Storno'),
1063 submit => [ '#form', { action => 'storno' } ],
1064 confirm => t8('Do you really want to cancel this general ledger transaction?'),
1065 disabled => !$form->{id} ? t8('This general ledger transaction has not been posted yet.')
1066 : $form->{storno} ? t8('A canceled general ledger transaction cannot be canceled again.')
1067 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
1068 : $is_linked_ap_transaction ? t8('This transaction is linked with a AP transaction. Please undo and redo the AP transaction booking if needed.')
1069 : $is_reconciled_bank_transaction ? t8('This transaction is reconciled with a bank transaction. Please undo the reconciliation if needed.')
1072 action => [ t8('Delete'),
1073 submit => [ '#form', { action => 'delete' } ],
1074 confirm => t8('Do you really want to delete this object?'),
1075 disabled => !$form->{id} ? t8('This invoice has not been posted yet.')
1076 : $form->{locked} ? t8('The billing period has already been locked.')
1077 : $change_never ? t8('Changing invoices has been disabled in the configuration.')
1078 : $change_on_same_day_only ? t8('Invoices can only be changed on the day they are posted.')
1079 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
1080 : $is_linked_ap_transaction ? t8('This transaction is linked with a AP transaction. Please undo and redo the AP transaction booking if needed.')
1081 : $is_reconciled_bank_transaction ? t8('This transaction is reconciled with a bank transaction. Please undo the reconciliation if needed.')
1082 : $form->{storno} ? t8('A canceled general ledger transaction cannot be deleted.')
1085 ], # end of combobox "Storno"
1088 action => [ t8('Workflow') ],
1091 submit => [ '#form', { action => "use_as_new" } ],
1092 checks => [ 'kivi.validate_form' ],
1093 disabled => !$form->{id} ? t8('This general ledger transaction has not been posted yet.')
1096 ], # end of combobox "Workflow"
1099 action => [ t8('more') ],
1102 call => [ 'set_history_window', $form->{id} * 1, 'glid' ],
1103 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
1107 call => [ 'follow_up_window' ],
1108 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
1111 t8('Record templates'),
1112 call => [ 'kivi.RecordTemplate.popup', 'gl_transaction' ],
1116 call => [ 'kivi.Draft.popup', 'gl', 'unknown', $form->{draft_id}, $form->{draft_description} ],
1117 disabled => $form->{id} ? t8('This invoice has already been posted.')
1118 : $form->{locked} ? t8('The billing period has already been locked.')
1121 ], # end of combobox "more"
1126 sub setup_gl_search_action_bar {
1129 for my $bar ($::request->layout->get('actionbar')) {
1133 submit => [ '#form', { action => 'continue', nextsub => 'generate_report' } ],
1134 accesskey => 'enter',
1140 sub setup_gl_transactions_action_bar {
1143 for my $bar ($::request->layout->get('actionbar')) {
1146 action => [ $::locale->text('Create new') ],
1148 $::locale->text('GL Transaction'),
1149 submit => [ '#create_new_form', { action => 'gl_transaction' } ],
1152 $::locale->text('AR Transaction'),
1153 submit => [ '#create_new_form', { action => 'ar_transaction' } ],
1156 $::locale->text('AP Transaction'),
1157 submit => [ '#create_new_form', { action => 'ap_transaction' } ],
1160 $::locale->text('Sales Invoice'),
1161 submit => [ '#create_new_form', { action => 'sales_invoice' } ],
1164 $::locale->text('Vendor Invoice'),
1165 submit => [ '#create_new_form', { action => 'vendor_invoice' } ],
1167 ], # end of combobox "Create new"
1173 $::lxdebug->enter_sub;
1174 $::auth->assert('gl_transactions');
1178 $::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");
1180 my @old_project_ids = grep { $_ } map{ $::form->{"project_id_$_"} } 1..$::form->{rowcount};
1181 my @conditions = @old_project_ids ? (id => \@old_project_ids) : ();
1182 $::form->{ALL_PROJECTS} = SL::DB::Manager::Project->get_all_sorted(query => [ or => [ active => 1, @conditions ]]);
1185 "charts" => { "key" => "ALL_CHARTS", "transdate" => $::form->{transdate} },
1188 # we cannot book on charttype header
1189 @{ $::form->{ALL_CHARTS} } = grep { $_->{charttype} ne 'H' } @{ $::form->{ALL_CHARTS} };
1190 $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
1192 my $title = $::form->{title};
1193 $::form->{title} = $::locale->text("$title General Ledger Transaction");
1194 # $locale->text('Add General Ledger Transaction')
1195 # $locale->text('Edit General Ledger Transaction')
1197 map { $::form->{$_} =~ s/\"/"/g }
1201 $::request->{layout}->focus("#reference");
1202 $::form->{taxincluded} = "1";
1204 $::request->{layout}->focus("#accno_id_$::form->{rowcount}_name");
1207 $::form->{previous_id} ||= "--";
1208 $::form->{previous_gldate} ||= "--";
1210 setup_gl_action_bar();
1213 print $::form->parse_html_template('gl/form_header', {
1214 hide_title => $title,
1215 readonly => $::form->{id} && ($::form->{locked} || !_get_radieren()),
1218 $::lxdebug->leave_sub;
1223 $::lxdebug->enter_sub;
1224 $::auth->assert('gl_transactions');
1226 my ($follow_ups, $follow_ups_due);
1228 if ($::form->{id}) {
1229 $follow_ups = FU->follow_ups('trans_id' => $::form->{id}, 'not_done' => 1);
1230 $follow_ups_due = sum map { $_->{due} * 1 } @{ $follow_ups || [] };
1233 print $::form->parse_html_template('gl/form_footer', {
1234 radieren => _get_radieren(),
1235 follow_ups => $follow_ups,
1236 follow_ups_due => $follow_ups_due,
1239 $::lxdebug->leave_sub;
1243 $main::lxdebug->enter_sub();
1245 my $form = $main::form;
1246 my %myconfig = %main::myconfig;
1247 my $locale = $main::locale;
1249 if (GL->delete_transaction(\%myconfig, \%$form)){
1250 # saving the history
1251 if(!exists $form->{addition} && $form->{id} ne "") {
1252 $form->{snumbers} = qq|gltransaction_| . $form->{id};
1253 $form->{addition} = "DELETED";
1254 $form->{what_done} = "gl_transaction";
1255 $form->save_history;
1257 # /saving the history
1258 $form->redirect($locale->text('Transaction deleted!'))
1260 $form->error($locale->text('Cannot delete transaction!'));
1261 $main::lxdebug->leave_sub();
1265 sub post_transaction {
1266 $main::lxdebug->enter_sub();
1268 my $form = $main::form;
1269 my %myconfig = %main::myconfig;
1270 my $locale = $main::locale;
1272 # check if there is something in reference and date
1273 $form->isblank("reference", $locale->text('Reference missing!'));
1274 $form->isblank("transdate", $locale->text('Transaction Date missing!'));
1275 $form->isblank("description", $locale->text('Description missing!'));
1276 $form->isblank("transaction_description", $locale->text('A transaction description is required.')) if $::instance_conf->get_require_transaction_description_ps;
1278 my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
1279 my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
1286 my $creditcount = 0;
1288 my %split_safety = ();
1290 my $dbh = SL::DB->client->dbh;
1291 my ($notax_id) = selectrow_query($form, $dbh, "SELECT id FROM tax WHERE taxkey = 0 LIMIT 1", );
1292 my $zerotaxes = selectall_hashref_query($form, $dbh, "SELECT id FROM tax WHERE rate = 0", );
1294 my @flds = qw(accno_id debit credit projectnumber fx_transaction source memo tax taxchart);
1296 for my $i (1 .. $form->{rowcount}) {
1297 next if $form->{"debit_$i"} eq "" && $form->{"credit_$i"} eq "";
1299 for (qw(debit credit tax)) {
1300 $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"});
1304 $debitcredit = ($form->{"debit_$i"} == 0) ? "0" : "1";
1306 $split_safety{ $form->{"debit_$i"} <=> 0 }++;
1307 $split_safety{ - $form->{"credit_$i"} <=> 0 }++;
1315 if (($debitcount >= 2) && ($creditcount == 2)) {
1316 $form->{"credit_$i"} = 0;
1317 $form->{"tax_$i"} = 0;
1319 $form->{creditlock} = 1;
1321 if (($creditcount >= 2) && ($debitcount == 2)) {
1322 $form->{"debit_$i"} = 0;
1323 $form->{"tax_$i"} = 0;
1325 $form->{debitlock} = 1;
1327 if (($creditcount == 1) && ($debitcount == 2)) {
1328 $form->{creditlock} = 1;
1330 if (($creditcount == 2) && ($debitcount == 1)) {
1331 $form->{debitlock} = 1;
1333 if ($debitcredit && $credittax) {
1334 $form->{"taxchart_$i"} = "$notax_id--0.00000";
1336 if (!$debitcredit && $debittax) {
1337 $form->{"taxchart_$i"} = "$notax_id--0.00000";
1339 my $amount = ($form->{"debit_$i"} == 0)
1340 ? $form->{"credit_$i"}
1341 : $form->{"debit_$i"};
1343 if (($debitcredit && $credittax) || (!$debitcredit && $debittax)) {
1344 $form->{"taxchart_$i"} = "$notax_id--0.00000";
1345 $form->{"tax_$i"} = 0;
1347 my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
1348 my $iswithouttax = grep { $_->{id} == $taxkey } @{ $zerotaxes };
1349 if (!$iswithouttax) {
1356 my ($tmpnetamount,$tmpdiff);
1357 ($tmpnetamount,$form->{"tax_$i"},$tmpdiff) = $form->calculate_tax($amount,$rate,$form->{taxincluded} *= 1,2);
1359 $form->{"debit_$i"} = $tmpnetamount;
1361 $form->{"credit_$i"} = $tmpnetamount;
1365 $form->{"tax_$i"} = 0;
1368 for (@flds) { $a[$j]->{$_} = $form->{"${_}_$i"} }
1372 if ($split_safety{-1} > 1 && $split_safety{1} > 1) {
1373 $::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. " .
1374 "Due to known problems involving accounting software kivitendo does not allow these."));
1377 for my $i (1 .. $count) {
1379 for (@flds) { $form->{"${_}_$i"} = $a[$j]->{$_} }
1382 for my $i ($count + 1 .. $form->{rowcount}) {
1383 for (@flds) { delete $form->{"${_}_$i"} }
1386 my ($debit, $credit, $taxtotal);
1387 for my $i (1 .. $form->{rowcount}) {
1388 my $dr = $form->{"debit_$i"};
1389 my $cr = $form->{"credit_$i"};
1390 my $tax = $form->{"tax_$i"};
1392 $form->error($locale->text('Cannot post transaction with a debit and credit entry for the same account!'));
1394 $debit += $dr + $tax if $dr;
1395 $credit += $cr + $tax if $cr;
1396 $taxtotal += $tax if $form->{taxincluded}
1399 $form->{taxincluded} = 0 if !$taxtotal;
1401 # this is just for the wise guys
1403 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
1404 if ($form->date_max_future($form->{"transdate"}, \%myconfig));
1405 $form->error($locale->text('Cannot post transaction for a closed period!'))
1406 if ($form->date_closed($form->{"transdate"}, \%myconfig));
1407 if ($form->round_amount($debit, 2) != $form->round_amount($credit, 2)) {
1408 $form->error($locale->text('Out of balance transaction!'));
1411 if ($form->round_amount($debit, 2) + $form->round_amount($credit, 2) == 0) {
1412 $form->error($locale->text('Empty transaction!'));
1416 # start transaction (post + history + (optional) banktrans)
1417 SL::DB->client->with_transaction(sub {
1419 if ((my $errno = GL->post_transaction(\%myconfig, \%$form)) <= -1) {
1422 $err[1] = $locale->text('Cannot have a value in both Debit and Credit!');
1423 $err[2] = $locale->text('Debit and credit out of balance!');
1424 $err[3] = $locale->text('Cannot post a transaction without a value!');
1428 # saving the history
1429 if(!exists $form->{addition} && $form->{id} ne "") {
1430 $form->{snumbers} = qq|gltransaction_| . $form->{id};
1431 $form->{addition} = "POSTED";
1432 $form->{what_done} = "gl transaction";
1433 $form->save_history;
1436 # Case BankTransaction: update RecordLink and BankTransaction
1437 if ($form->{callback} =~ /BankTransaction/ && $form->{bt_id}) {
1438 # set invoice_amount - we only rely on bt_id in form, do all other stuff ui independent
1439 # die if we have a unlogic or NYI case and abort the whole transaction
1440 my ($bt, $chart_id, $payment);
1441 require SL::DB::Manager::BankTransaction;
1443 $bt = SL::DB::Manager::BankTransaction->find_by(id => $::form->{bt_id});
1444 die "No bank transaction found" unless $bt;
1446 $chart_id = SL::DB::Manager::BankAccount->find_by(id => $bt->local_bank_account_id)->chart_id;
1447 die "no chart id" unless $chart_id;
1449 $payment = SL::DB::Manager::AccTransaction->get_all(where => [ trans_id => $::form->{id},
1450 chart_link => { like => '%_paid%' },
1451 chart_id => $chart_id ]);
1452 die "guru meditation error: Can only assign amount to one bank account booking" if scalar @{ $payment } > 1;
1454 # credit/debit * -1 matches the sign for bt.amount and bt.invoice_amount
1456 die "Can only assign the full (partial) bank amount to a single general ledger booking: " . $bt->not_assigned_amount . " " . ($payment->[0]->amount * -1)
1457 unless (abs($bt->not_assigned_amount - ($payment->[0]->amount * -1)) < 0.001);
1459 $bt->update_attributes(invoice_amount => $bt->invoice_amount + ($payment->[0]->amount * -1));
1461 # create record_link
1463 from_table => 'bank_transactions',
1464 from_id => $::form->{bt_id},
1466 to_id => $::form->{id},
1468 SL::DB::RecordLink->new(%props)->save;
1469 # and tighten holy acc_trans_id for this bank_transaction
1471 acc_trans_id => $payment->[0]->acc_trans_id,
1472 bank_transaction_id => $bt->id,
1473 gl_id => $payment->[0]->trans_id,
1475 my $bta = SL::DB::BankTransactionAccTrans->new(%props_acc);
1480 }) or do { die SL::DB->client->error };
1482 $main::lxdebug->leave_sub();
1486 $main::lxdebug->enter_sub();
1488 $main::auth->assert('gl_transactions');
1490 my $form = $main::form;
1491 my $locale = $main::locale;
1493 if ($::myconfig{mandatory_departments} && !$form->{department_id}) {
1494 $form->error($locale->text('You have to specify a department.'));
1497 $form->{title} = $locale->text("$form->{title} General Ledger Transaction");
1498 $form->{storno} = 0;
1502 if ($::instance_conf->get_webdav) {
1503 SL::Webdav->new(type => 'general_ledger',
1504 number => $form->{id},
1508 if ($form->{email_journal_id} && $form->{id} ne "") {
1509 my $ar_transaction = SL::DB::GLTransaction->new(id => $form->{id})->load;
1510 my $email_journal = SL::DB::EmailJournal->new(
1511 id => delete $form->{email_journal_id}
1513 $email_journal->link_to_record_with_attachment($ar_transaction, delete $::form->{email_attachment_id});
1516 my $msg = $::locale->text("General ledger transaction '#1' posted (ID: #2)", $form->{reference}, $form->{id});
1517 if ($form->{callback} =~ /BankTransaction/ && $form->{bt_id}) {
1518 SL::Helper::Flash::flash_later('info', $msg) if $msg;
1519 print $::form->redirect_header($form->{callback});
1520 } elsif ('doc-tab' eq $form->{after_action}) {
1521 # Redirect with callback containing a fragment does not work (by now)
1522 # because the callback info is stored in the session an parsing the
1523 # callback parameters does not support fragments (see SL::Form::redirect).
1524 # So use flash_later for the message and redirect_headers for redirecting.
1525 my $add_doc_url = build_std_url("script=gl.pl", 'action=edit', 'id=' . E($form->{id}), 'fragment=ui-tabs-docs');
1526 SL::Helper::Flash::flash_later('info', $msg);
1527 print $form->redirect_header($add_doc_url);
1528 $::dispatcher->end_request;
1529 } elsif ('callback' eq $form->{after_action}) {
1530 my $callback = $form->{callback}
1531 || "controller.pl?action=LoginScreen/user_login";
1532 SL::Helper::Flash::flash_later('info', $msg);
1533 print $form->redirect_header($callback);
1534 $::dispatcher->end_request;
1536 $form->{callback} = build_std_url("action=add", "show_details");
1537 $form->redirect($msg);
1540 $main::lxdebug->leave_sub();
1544 $main::lxdebug->enter_sub();
1546 $main::auth->assert('gl_transactions');
1548 my $form = $main::form;
1549 my %myconfig = %main::myconfig;
1550 my $locale = $main::locale;
1552 # don't cancel cancelled transactions
1553 if (IS->has_storno(\%myconfig, $form, 'gl')) {
1554 $form->{title} = $locale->text("Cancel Accounts Receivables Transaction");
1555 $form->error($locale->text("Transaction has already been cancelled!"));
1558 GL->storno($form, \%myconfig, $form->{id});
1560 # saving the history
1561 if(!exists $form->{addition} && $form->{id} ne "") {
1562 $form->{snumbers} = qq|gltransaction_| . $form->{id};
1563 $form->{addition} = "STORNO";
1564 $form->{what_done} = "gl_transaction";
1565 $form->save_history;
1567 # /saving the history
1569 $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
1571 $main::lxdebug->leave_sub();
1575 $::auth->assert('gl_transactions');
1577 $::form->{email_journal_id} = delete $::form->{workflow_email_journal_id};
1578 $::form->{email_attachment_id} = delete $::form->{workflow_email_attachment_id};
1579 $::form->{callback} = delete $::form->{workflow_email_callback};
1581 delete $::form->{$_} for qw(id gldate tax_point deliverydate storno);
1583 $::form->{title} = "Add";
1584 $::form->{transdate} = DateTime->today_local->to_kivitendo;
1586 $::form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_GL_TRANSACTION_POST())->token;
1592 call_sub($main::form->{nextsub});
1595 sub get_tax_dropdown {
1596 my $transdate = $::form->{transdate} ? DateTime->from_kivitendo($::form->{transdate}) : DateTime->today_local;
1597 my $deliverydate = $::form->{deliverydate} ? DateTime->from_kivitendo($::form->{deliverydate}) : undef;
1598 my @tax_accounts = GL->get_active_taxes_for_chart($::form->{accno_id}, $deliverydate // $transdate);
1599 my $html = $::form->parse_html_template("gl/update_tax_accounts", { TAX_ACCOUNTS => \@tax_accounts });
1601 print $::form->ajax_response_header, $html;
1604 sub get_chart_balance {
1605 my %balances = GL->get_chart_balances($::form->{accno_id});
1606 my $balance = $::form->format_amount(\%::myconfig, $balances{ $::form->{accno_id} }, 2, 'DRCR');
1608 print $::form->ajax_response_header, $balance;