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);
41 use SL::DB::RecordTemplate;
45 use SL::Helper::Flash qw(flash);
47 use SL::ReportGenerator;
48 use SL::DBUtils qw(selectrow_query selectall_hashref_query);
50 use SL::Locale::String qw(t8);
52 require "bin/mozilla/common.pl";
53 require "bin/mozilla/reportgenerator.pl";
55 # this is for our long dates
56 # $locale->text('January')
57 # $locale->text('February')
58 # $locale->text('March')
59 # $locale->text('April')
60 # $locale->text('May ')
61 # $locale->text('June')
62 # $locale->text('July')
63 # $locale->text('August')
64 # $locale->text('September')
65 # $locale->text('October')
66 # $locale->text('November')
67 # $locale->text('December')
69 # this is for our short month
70 # $locale->text('Jan')
71 # $locale->text('Feb')
72 # $locale->text('Mar')
73 # $locale->text('Apr')
74 # $locale->text('May')
75 # $locale->text('Jun')
76 # $locale->text('Jul')
77 # $locale->text('Aug')
78 # $locale->text('Sep')
79 # $locale->text('Oct')
80 # $locale->text('Nov')
81 # $locale->text('Dec')
83 sub load_record_template {
84 $::auth->assert('gl_transactions');
86 # Load existing template and verify that its one for this module.
87 my $template = SL::DB::RecordTemplate
88 ->new(id => $::form->{id})
90 with_object => [ qw(customer payment currency record_items record_items.chart) ],
93 die "invalid template type" unless $template->template_type eq 'gl_transaction';
95 $template->substitute_variables;
97 # Clean the current $::form before rebuilding it from the template.
98 delete @{ $::form }{ grep { !m{^(?:script|login)$}i } keys %{ $::form } };
101 GL->transaction(\%::myconfig, $dummy_form);
103 # Fill $::form from the template.
104 my $today = DateTime->today_local;
105 $::form->{title} = "Add";
106 $::form->{transdate} = $today->to_kivitendo;
107 $::form->{duedate} = $today->to_kivitendo;
108 $::form->{rowcount} = @{ $template->items } + 1;
109 $::form->{paidaccounts} = 1;
110 $::form->{$_} = $template->$_ for qw(department_id taxincluded ob_transaction cb_transaction reference description);
111 $::form->{$_} = $dummy_form->{$_} for qw(closedto revtrans previous_id previous_gldate);
114 foreach my $item (@{ $template->items }) {
117 my $active_taxkey = $item->chart->get_active_taxkey;
118 my $taxes = SL::DB::Manager::Tax->get_all(
119 where => [ chart_categories => { like => '%' . $item->chart->category . '%' }],
120 sort_by => 'taxkey, rate',
123 my $tax = first { $item->tax_id == $_->id } @{ $taxes };
124 $tax //= first { $active_taxkey->tax_id == $_->id } @{ $taxes };
125 $tax //= $taxes->[0];
132 $::form->{"accno_id_${row}"} = $item->chart_id;
133 $::form->{"previous_accno_id_${row}"} = $item->chart_id;
134 $::form->{"debit_${row}"} = $::form->format_amount(\%::myconfig, $item->amount1, 2) if $item->amount1 * 1;
135 $::form->{"credit_${row}"} = $::form->format_amount(\%::myconfig, $item->amount2, 2) if $item->amount2 * 1;
136 $::form->{"taxchart_${row}"} = $item->tax_id . '--' . $tax->rate;
137 $::form->{"${_}_${row}"} = $item->$_ for qw(source memo project_id);
140 flash('info', $::locale->text("The record template '#1' has been loaded.", $template->template_name));
146 $main::lxdebug->enter_sub();
148 $main::auth->assert('gl_transactions');
150 my $form = $main::form;
151 my %myconfig = %main::myconfig;
153 $form->{title} = "Add";
155 $form->{callback} = "gl.pl?action=add" unless $form->{callback};
157 # we use this only to set a default date
158 # yep. aber er holt hier auch schon ALL_CHARTS. Aufwand / Nutzen? jb
159 GL->transaction(\%myconfig, \%$form);
161 $form->{rowcount} = 2;
167 $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all;
169 $form->{show_details} = $myconfig{show_form_details} unless defined $form->{show_details};
172 $main::lxdebug->leave_sub();
176 sub prepare_transaction {
177 $main::lxdebug->enter_sub();
179 $main::auth->assert('gl_transactions');
181 my $form = $main::form;
182 my %myconfig = %main::myconfig;
184 GL->transaction(\%myconfig, \%$form);
186 $form->{amount} = $form->format_amount(\%myconfig, $form->{amount}, 2);
188 $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all;
193 foreach my $ref (@{ $form->{GL} }) {
195 if ($tax && ($ref->{accno} eq $taxaccno)) {
196 $form->{"tax_$j"} = abs($ref->{amount});
197 $form->{"taxchart_$j"} = $ref->{id} . "--" . $ref->{taxrate};
198 if ($form->{taxincluded}) {
199 if ($ref->{amount} < 0) {
200 $form->{"debit_$j"} += $form->{"tax_$j"};
202 $form->{"credit_$j"} += $form->{"tax_$j"};
205 $form->{"project_id_$j"} = $ref->{project_id};
208 $form->{"accno_id_$i"} = $ref->{chart_id};
209 for (qw(fx_transaction source memo)) { $form->{"${_}_$i"} = $ref->{$_} }
210 if ($ref->{amount} < 0) {
211 $form->{totaldebit} -= $ref->{amount};
212 $form->{"debit_$i"} = $ref->{amount} * -1;
214 $form->{totalcredit} += $ref->{amount};
215 $form->{"credit_$i"} = $ref->{amount};
217 $form->{"taxchart_$i"} = $ref->{id}."--0.00000";
218 $form->{"project_id_$i"} = $ref->{project_id};
221 if ($ref->{taxaccno} && !$tax) {
222 $taxaccno = $ref->{taxaccno};
230 $form->{rowcount} = $i;
232 ($form->datetonum($form->{transdate}, \%myconfig) <=
233 $form->datetonum($form->{closedto}, \%myconfig));
235 $main::lxdebug->leave_sub();
239 $main::lxdebug->enter_sub();
241 $main::auth->assert('gl_transactions');
243 my $form = $main::form;
244 my %myconfig = %main::myconfig;
246 prepare_transaction();
248 $form->{title} = "Edit";
250 $form->{show_details} = $myconfig{show_form_details} unless defined $form->{show_details};
252 if ($form->{reference} && $::instance_conf->get_webdav) {
253 my $webdav = SL::Webdav->new(
254 type => 'general_ledger',
255 number => $form->{reference},
257 my $webdav_path = $webdav->webdav_path;
258 my @all_objects = $webdav->get_all_objects;
259 @{ $form->{WEBDAV} } = map { { name => $_->filename,
261 link => File::Spec->catfile($_->full_filedescriptor),
268 $main::lxdebug->leave_sub();
273 $::lxdebug->enter_sub;
274 $::auth->assert('general_ledger | gl_transactions');
277 projects => { key => "ALL_PROJECTS", all => 1 },
279 $::form->{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]);
280 $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all;
283 print $::form->parse_html_template('gl/search', {
284 employee_label => sub { "$_[0]{id}--$_[0]{name}" },
287 $::lxdebug->leave_sub;
290 sub create_subtotal_row {
291 $main::lxdebug->enter_sub();
293 my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
295 my $form = $main::form;
296 my %myconfig = %main::myconfig;
298 my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
300 map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
302 map { $totals->{$_} = 0 } @{ $subtotal_columns };
304 $main::lxdebug->leave_sub();
309 sub generate_report {
310 $main::lxdebug->enter_sub();
312 $main::auth->assert('general_ledger | gl_transactions');
314 my $form = $main::form;
315 my %myconfig = %main::myconfig;
316 my $locale = $main::locale;
318 # 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
320 # <form method=post action=gl.pl>
321 # <input type=hidden name=sort value=datesort> # form->{sort} setzen
322 # <input type=hidden name=nextsub value=generate_report>
324 # anhand von neuer Variable datesort wird jetzt $form->{sort} auf transdate oder gldate gesetzt
325 # damit ist die Hidden Variable "sort" wahrscheinlich sogar überflüssig
327 # ändert man die Sortierreihenfolge per Klick auf eine der Überschriften wird die Variable "sort" per GET übergeben, z.B. id,transdate, gldate, ...
328 # 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
330 if ( $form->{sort} eq 'datesort' ) { # sollte bei einem Post (Aufruf aus Suchmaske) immer wahr sein
331 # je nachdem ob in Suchmaske "transdate" oder "gldate" ausgesucht wurde erstes Suchergebnis entsprechend sortieren
332 $form->{sort} = $form->{datesort};
336 report_generator_set_default_sort("$form->{datesort}", 1);
337 # report_generator_set_default_sort('transdate', 1);
339 GL->all_transactions(\%myconfig, \%$form);
341 my %acctype = ('A' => $locale->text('Asset'),
342 'C' => $locale->text('Contra'),
343 'L' => $locale->text('Liability'),
344 'Q' => $locale->text('Equity'),
345 'I' => $locale->text('Revenue'),
346 'E' => $locale->text('Expense'),);
348 $form->{title} = $locale->text('Journal');
349 if ($form->{category} ne 'X') {
350 $form->{title} .= " : " . $locale->text($acctype{ $form->{category} });
353 $form->{landscape} = 1;
355 my $ml = ($form->{ml} =~ /(A|E|Q)/) ? -1 : 1;
358 gldate transdate id reference description
359 notes source debit debit_accno
360 credit credit_accno debit_tax debit_tax_accno
361 credit_tax credit_tax_accno projectnumbers balance employee
364 # add employee here, so that variable is still known and passed in url when choosing a different sort order in resulting table
365 my @hidden_variables = qw(accno source reference description notes project_id datefrom dateto employee_id datesort category l_subtotal);
366 push @hidden_variables, map { "l_${_}" } @columns;
368 my $employee = $form->{employee_id} ? SL::DB::Employee->new(id => $form->{employee_id})->load->name : '';
370 my (@options, @date_options);
371 push @options, $locale->text('Account') . " : $form->{accno} $form->{account_description}" if ($form->{accno});
372 push @options, $locale->text('Source') . " : $form->{source}" if ($form->{source});
373 push @options, $locale->text('Reference') . " : $form->{reference}" if ($form->{reference});
374 push @options, $locale->text('Description') . " : $form->{description}" if ($form->{description});
375 push @options, $locale->text('Notes') . " : $form->{notes}" if ($form->{notes});
376 push @options, $locale->text('Employee') . " : $employee" if $employee;
377 my $datesorttext = $form->{datesort} eq 'transdate' ? $locale->text('Invoice Date') : $locale->text('Booking Date');
378 push @date_options, "$datesorttext" if ($form->{datesort} and ($form->{datefrom} or $form->{dateto}));
379 push @date_options, $locale->text('From'), $locale->date(\%myconfig, $form->{datefrom}, 1) if ($form->{datefrom});
380 push @date_options, $locale->text('Bis'), $locale->date(\%myconfig, $form->{dateto}, 1) if ($form->{dateto});
381 push @options, join(' ', @date_options) if (scalar @date_options);
383 if ($form->{department_id}) {
384 my $department = SL::DB::Manager::Department->find_by( id => $form->{department_id} );
385 push @options, $locale->text('Department') . " : " . $department->description;
388 my $callback = build_std_url('action=generate_report', grep { $form->{$_} } @hidden_variables);
390 $form->{l_credit_accno} = 'Y';
391 $form->{l_debit_accno} = 'Y';
392 $form->{l_credit_tax} = 'Y';
393 $form->{l_debit_tax} = 'Y';
394 # $form->{l_gldate} = 'Y'; # Spalte mit gldate immer anzeigen
395 $form->{l_credit_tax_accno} = 'Y';
396 $form->{l_datesort} = 'Y';
397 $form->{l_debit_tax_accno} = 'Y';
398 $form->{l_balance} = $form->{accno} ? 'Y' : '';
401 'id' => { 'text' => $locale->text('ID'), },
402 'transdate' => { 'text' => $locale->text('Invoice Date'), },
403 'gldate' => { 'text' => $locale->text('Booking Date'), },
404 'reference' => { 'text' => $locale->text('Reference'), },
405 'source' => { 'text' => $locale->text('Source'), },
406 'description' => { 'text' => $locale->text('Description'), },
407 'notes' => { 'text' => $locale->text('Notes'), },
408 'debit' => { 'text' => $locale->text('Debit'), },
409 'debit_accno' => { 'text' => $locale->text('Debit Account'), },
410 'credit' => { 'text' => $locale->text('Credit'), },
411 'credit_accno' => { 'text' => $locale->text('Credit Account'), },
412 'debit_tax' => { 'text' => $locale->text('Debit Tax'), },
413 'debit_tax_accno' => { 'text' => $locale->text('Debit Tax Account'), },
414 'credit_tax' => { 'text' => $locale->text('Credit Tax'), },
415 'credit_tax_accno' => { 'text' => $locale->text('Credit Tax Account'), },
416 'balance' => { 'text' => $locale->text('Balance'), },
417 'projectnumbers' => { 'text' => $locale->text('Project Numbers'), },
418 'employee' => { 'text' => $locale->text('Employee'), },
421 foreach my $name (qw(id transdate gldate reference description debit_accno credit_accno debit_tax_accno credit_tax_accno)) {
422 my $sortname = $name =~ m/accno/ ? 'accno' : $name;
423 my $sortdir = $sortname eq $form->{sort} ? 1 - $form->{sortdir} : $form->{sortdir};
424 $column_defs{$name}->{link} = $callback . "&sort=$sortname&sortdir=$sortdir";
427 map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
428 map { $column_defs{$_}->{visible} = 0 } qw(debit_accno credit_accno debit_tax_accno credit_tax_accno) if $form->{accno};
430 my %column_alignment;
431 map { $column_alignment{$_} = 'right' } qw(balance id debit credit debit_tax credit_tax balance);
432 map { $column_alignment{$_} = 'center' } qw(transdate gldate reference debit_accno credit_accno debit_tax_accno credit_tax_accno);
433 map { $column_alignment{$_} = 'left' } qw(description source notes);
434 map { $column_defs{$_}->{align} = $column_alignment{$_} } keys %column_alignment;
436 my $report = SL::ReportGenerator->new(\%myconfig, $form);
438 $report->set_columns(%column_defs);
439 $report->set_column_order(@columns);
441 $report->set_export_options('generate_report', @hidden_variables, qw(sort sortdir));
443 $report->set_sort_indicator($form->{sort} eq 'accno' ? 'debit_accno' : $form->{sort}, $form->{sortdir});
445 $report->set_options('top_info_text' => join("\n", @options),
446 'output_format' => 'HTML',
447 'title' => $form->{title},
448 'attachment_basename' => $locale->text('general_ledger_list') . strftime('_%Y%m%d', localtime time),
450 $report->set_options_from_form();
451 $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
453 # add sort to callback
454 $form->{callback} = "$callback&sort=" . E($form->{sort}) . "&sortdir=" . E($form->{sortdir});
457 my @totals_columns = qw(debit credit debit_tax credit_tax);
458 my %subtotals = map { $_ => 0 } @totals_columns;
459 my %totals = map { $_ => 0 } @totals_columns;
462 foreach my $ref (@{ $form->{GL} }) {
466 foreach my $key (qw(debit credit debit_tax credit_tax)) {
468 foreach my $idx (sort keys(%{ $ref->{$key} })) {
469 my $value = $ref->{$key}->{$idx};
470 $subtotals{$key} += $value;
471 $totals{$key} += $value;
472 if ($key =~ /debit.*/) {
477 $form->{balance} = $form->{balance} + $value * $ml;
478 push @{ $rows{$key} }, $form->format_amount(\%myconfig, $value, 2);
482 foreach my $key (qw(debit_accno credit_accno debit_tax_accno credit_tax_accno ac_transdate source)) {
483 my $col = $key eq 'ac_transdate' ? 'transdate' : $key;
484 $rows{$col} = [ map { $ref->{$key}->{$_} } sort keys(%{ $ref->{$key} }) ];
488 map { $row->{$_} = { 'data' => '', 'align' => $column_alignment{$_} } } @columns;
491 if ($form->{balance} < 0) {
494 } elsif ($form->{balance} > 0) {
498 my $data = $form->format_amount(\%myconfig, ($form->{balance} * $ml), 2);
501 $row->{balance}->{data} = $data;
502 $row->{projectnumbers}->{data} = join ", ", sort { lc($a) cmp lc($b) } keys %{ $ref->{projectnumbers} };
504 map { $row->{$_}->{data} = $ref->{$_} } qw(id reference description notes gldate employee);
506 map { $row->{$_}->{data} = \@{ $rows{$_} }; } qw(transdate debit credit debit_accno credit_accno debit_tax_accno credit_tax_accno source);
508 foreach my $col (qw(debit_accno credit_accno debit_tax_accno credit_tax_accno)) {
509 $row->{$col}->{link} = [ map { "${callback}&accno=" . E($_) } @{ $rows{$col} } ];
512 map { $row->{$_}->{data} = \@{ $rows{$_} } if ($ref->{"${_}_accno"} ne "") } qw(debit_tax credit_tax);
514 $row->{reference}->{link} = build_std_url("script=$ref->{module}.pl", 'action=edit', 'id=' . E($ref->{id}), 'callback');
516 my $row_set = [ $row ];
518 if ( ($form->{l_subtotal} eq 'Y' && !$form->{report_generator_csv_options_for_import} )
519 && (($idx == (scalar @{ $form->{GL} } - 1))
520 || ($ref->{ $form->{sort} } ne $form->{GL}->[$idx + 1]->{ $form->{sort} }))) {
521 push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, [ qw(debit credit) ], 'listsubtotal');
524 $report->add_data($row_set);
529 # = 0 for balanced ledger
530 my $balanced_ledger = $totals{debit} + $totals{debit_tax} - $totals{credit} - $totals{credit_tax};
532 my $row = create_subtotal_row(\%totals, \@columns, \%column_alignment, [ qw(debit credit debit_tax credit_tax) ], 'listtotal');
535 if ($form->{balance} < 0) {
538 } elsif ($form->{balance} > 0) {
542 my $data = $form->format_amount(\%myconfig, ($form->{balance} * $ml), 2);
545 $row->{balance}->{data} = $data;
547 if ( !$form->{report_generator_csv_options_for_import} ) {
548 $report->add_separator();
549 $report->add_data($row);
552 my $raw_bottom_info_text;
554 if (!$form->{accno} && (abs($balanced_ledger) > 0.001)) {
555 $raw_bottom_info_text .=
556 '<p><span class="unbalanced_ledger">'
557 . $locale->text('Unbalanced Ledger')
559 . $form->format_amount(\%myconfig, $balanced_ledger, 3)
563 $raw_bottom_info_text .= $form->parse_html_template('gl/generate_report_bottom');
565 $report->set_options('raw_bottom_info_text' => $raw_bottom_info_text);
567 $report->generate_with_headers();
569 $main::lxdebug->leave_sub();
573 $::form->{transdate} = DateTime->today_local->to_kivitendo if !$::form->{transdate};
574 $::form->{gldate} = $::form->{transdate} if !$::form->{gldate};
579 $main::lxdebug->enter_sub();
581 $main::auth->assert('gl_transactions');
583 my $form = $main::form;
584 my %myconfig = %main::myconfig;
586 $form->{oldtransdate} = $form->{transdate};
594 my ($debitcredit, $amount);
596 my $dbh = SL::DB->client->dbh;
597 my ($notax_id) = selectrow_query($form, $dbh, "SELECT id FROM tax WHERE taxkey = 0 LIMIT 1", );
598 my $zerotaxes = selectall_hashref_query($form, $dbh, "SELECT id FROM tax WHERE rate = 0", );
601 qw(accno debit credit projectnumber fx_transaction source memo tax taxchart);
603 for my $i (1 .. $form->{rowcount}) {
605 unless (($form->{"debit_$i"} eq "") && ($form->{"credit_$i"} eq "")) {
606 for (qw(debit credit tax)) {
608 $form->parse_amount(\%myconfig, $form->{"${_}_$i"});
612 $debitcredit = ($form->{"debit_$i"} == 0) ? "0" : "1";
619 if (($debitcount >= 2) && ($creditcount == 2)) {
620 $form->{"credit_$i"} = 0;
621 $form->{"tax_$i"} = 0;
623 $form->{creditlock} = 1;
625 if (($creditcount >= 2) && ($debitcount == 2)) {
626 $form->{"debit_$i"} = 0;
627 $form->{"tax_$i"} = 0;
629 $form->{debitlock} = 1;
631 if (($creditcount == 1) && ($debitcount == 2)) {
632 $form->{creditlock} = 1;
634 if (($creditcount == 2) && ($debitcount == 1)) {
635 $form->{debitlock} = 1;
637 if ($debitcredit && $credittax) {
638 $form->{"taxchart_$i"} = "$notax_id--0.00";
640 if (!$debitcredit && $debittax) {
641 $form->{"taxchart_$i"} = "$notax_id--0.00";
644 ($form->{"debit_$i"} == 0)
645 ? $form->{"credit_$i"}
646 : $form->{"debit_$i"};
648 if (($debitcredit && $credittax) || (!$debitcredit && $debittax)) {
649 $form->{"taxchart_$i"} = "$notax_id--0.00";
650 $form->{"tax_$i"} = 0;
652 my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
653 my $iswithouttax = grep { $_->{id} == $taxkey } @{ $zerotaxes };
654 if (!$iswithouttax) {
661 my ($tmpnetamount,$tmpdiff);
662 ($tmpnetamount,$form->{"tax_$i"},$tmpdiff) = $form->calculate_tax($amount,$rate,$form->{taxincluded} *= 1,2);
664 for (@flds) { $a[$j]->{$_} = $form->{"${_}_$i"} }
669 for my $i (1 .. $count) {
671 for (@flds) { $form->{"${_}_$i"} = $a[$j]->{$_} }
674 for my $i ($count + 1 .. $form->{rowcount}) {
675 for (@flds) { delete $form->{"${_}_$i"} }
678 $form->{rowcount} = $count + 1;
681 $main::lxdebug->leave_sub();
687 $main::lxdebug->enter_sub();
689 $main::auth->assert('gl_transactions');
691 my $form = $main::form;
692 my %myconfig = %main::myconfig;
696 # for $i (1 .. $form->{rowcount}) {
697 # $form->{totaldebit} += $form->parse_amount(\%myconfig, $form->{"debit_$i"});
698 # $form->{totalcredit} += $form->parse_amount(\%myconfig, $form->{"credit_$i"});
702 &display_rows($init);
704 $main::lxdebug->leave_sub();
710 $main::lxdebug->enter_sub();
712 $main::auth->assert('gl_transactions');
714 my $form = $main::form;
715 my %myconfig = %main::myconfig;
716 my $cgi = $::request->{cgi};
718 my %balances = GL->get_chart_balances(map { $_->{id} } @{ $form->{ALL_CHARTS} });
720 $form->{debit_1} = 0 if !$form->{"debit_1"};
721 $form->{totaldebit} = 0;
722 $form->{totalcredit} = 0;
724 my %project_labels = ();
725 my @project_values = ("");
726 foreach my $item (@{ $form->{"ALL_PROJECTS"} }) {
727 push(@project_values, $item->{"id"});
728 $project_labels{$item->{"id"}} = $item->{"projectnumber"};
731 my %charts_by_id = map { ($_->{id} => $_) } @{ $::form->{ALL_CHARTS} };
732 my $default_chart = $::form->{ALL_CHARTS}[0];
733 my $transdate = $::form->{transdate} ? DateTime->from_kivitendo($::form->{transdate}) : DateTime->today_local;
735 my ($source, $memo, $source_hidden, $memo_hidden);
736 for my $i (1 .. $form->{rowcount}) {
737 if ($form->{show_details}) {
739 <td><input name="source_$i" value="$form->{"source_$i"}" size="16"></td>|;
741 <td><input name="memo_$i" value="$form->{"memo_$i"}" size="16"></td>|;
744 <input type="hidden" name="source_$i" value="$form->{"source_$i"}" size="16">|;
746 <input type="hidden" name="memo_$i" value="$form->{"memo_$i"}" size="16">|;
749 my %taxchart_labels = ();
750 my @taxchart_values = ();
752 my $accno_id = $::form->{"accno_id_$i"};
753 my $chart = $charts_by_id{$accno_id} // $default_chart;
754 $accno_id = $chart->{id};
755 my $chart_has_changed = $::form->{"previous_accno_id_$i"} && ($accno_id != $::form->{"previous_accno_id_$i"});
756 my ($first_taxchart, $default_taxchart, $taxchart_to_use);
758 foreach my $item ( GL->get_active_taxes_for_chart($accno_id, $transdate) ) {
759 my $key = $item->id . "--" . $item->rate;
760 $first_taxchart //= $item;
761 $default_taxchart = $item if $item->{is_default};
762 $taxchart_to_use = $item if $key eq $form->{"taxchart_$i"};
764 push(@taxchart_values, $key);
765 $taxchart_labels{$key} = $item->taxdescription . " " . $item->rate * 100 . ' %';
768 $taxchart_to_use = $default_taxchart // $first_taxchart if $chart_has_changed || !$taxchart_to_use;
769 my $selected_taxchart = $taxchart_to_use->id . '--' . $taxchart_to_use->rate;
771 my $accno = qq|<td>| .
772 $::request->presenter->chart_picker("accno_id_$i", $accno_id, style => "width: 300px") .
773 $::request->presenter->hidden_tag("previous_accno_id_$i", $accno_id)
775 my $tax_ddbox = qq|<td>| .
776 NTI($cgi->popup_menu('-name' => "taxchart_$i",
777 '-id' => "taxchart_$i",
778 '-style' => 'width:200px',
779 '-values' => \@taxchart_values,
780 '-labels' => \%taxchart_labels,
781 '-default' => $selected_taxchart))
784 my ($fx_transaction, $checked);
786 if ($form->{transfer}) {
787 $fx_transaction = qq|
788 <td><input name="fx_transaction_$i" class=checkbox type=checkbox value=1></td>
793 if ($form->{"debit_$i"} != 0) {
794 $form->{totaldebit} += $form->{"debit_$i"};
795 if (!$form->{taxincluded}) {
796 $form->{totaldebit} += $form->{"tax_$i"};
799 $form->{totalcredit} += $form->{"credit_$i"};
800 if (!$form->{taxincluded}) {
801 $form->{totalcredit} += $form->{"tax_$i"};
805 for (qw(debit credit tax)) {
808 ? $form->format_amount(\%myconfig, $form->{"${_}_$i"}, 2)
812 if ($i < $form->{rowcount}) {
813 if ($form->{transfer}) {
814 $checked = ($form->{"fx_transaction_$i"}) ? "1" : "";
815 my $x = ($checked) ? "x" : "";
816 $fx_transaction = qq|
817 <td><input type=hidden name="fx_transaction_$i" value="$checked">$x</td>
820 $form->hide_form("accno_$i");
823 if ($form->{transfer}) {
824 $fx_transaction = qq|
825 <td><input name="fx_transaction_$i" class=checkbox type=checkbox value=1></td>
830 my $debitreadonly = "";
831 my $creditreadonly = "";
832 if ($i == $form->{rowcount}) {
833 if ($form->{debitlock}) {
834 $debitreadonly = "readonly";
835 } elsif ($form->{creditlock}) {
836 $creditreadonly = "readonly";
841 NTI($cgi->popup_menu('-name' => "project_id_$i",
842 '-values' => \@project_values,
843 '-labels' => \%project_labels,
844 '-default' => $form->{"project_id_$i"} ));
845 my $projectnumber_hidden = qq|
846 <input type="hidden" name="project_id_$i" value="$form->{"project_id_$i"}">|;
848 my $copy2credit = $i == 1 ? 'onkeyup="copy_debit_to_credit()"' : '';
849 my $balance = $form->format_amount(\%::myconfig, $balances{$accno_id} // 0, 2, 'DRCR');
851 print qq|<tr valign=top>
853 <td id="chart_balance_$i" align="right">${balance}</td>
855 <td><input name="debit_$i" size="8" value="$form->{"debit_$i"}" accesskey=$i $copy2credit $debitreadonly></td>
856 <td><input name="credit_$i" size=8 value="$form->{"credit_$i"}" $creditreadonly></td>
857 <td><input type="hidden" name="tax_$i" value="$form->{"tax_$i"}">$form->{"tax_$i"}</td>
860 if ($form->{show_details}) {
864 <td>$projectnumber</td>
870 $projectnumber_hidden
878 $form->hide_form(qw(rowcount selectaccno));
880 $main::lxdebug->leave_sub();
885 return ($::instance_conf->get_gl_changeable == 2) ? ($::form->current_date(\%::myconfig) eq $::form->{gldate}) : ($::instance_conf->get_gl_changeable == 1);
889 $::lxdebug->enter_sub;
890 $::auth->assert('gl_transactions');
894 $::request->layout->add_javascripts("autocomplete_chart.js", "kivi.GL.js");
896 my @old_project_ids = grep { $_ } map{ $::form->{"project_id_$_"} } 1..$::form->{rowcount};
898 $::form->get_lists("projects" => { "key" => "ALL_PROJECTS",
900 "old_id" => \@old_project_ids },
902 "charts" => { "key" => "ALL_CHARTS",
903 "transdate" => $::form->{transdate} });
905 $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all;
907 my $title = $::form->{title};
908 $::form->{title} = $::locale->text("$title General Ledger Transaction");
909 # $locale->text('Add General Ledger Transaction')
910 # $locale->text('Edit General Ledger Transaction')
912 map { $::form->{$_} =~ s/\"/"/g }
916 $::request->{layout}->focus("#reference");
917 $::form->{taxincluded} = "1";
919 $::request->{layout}->focus("#accno_id_$::form->{rowcount}_name");
922 $::form->{previous_id} ||= "--";
923 $::form->{previous_gldate} ||= "--";
926 print $::form->parse_html_template('gl/form_header', {
927 hide_title => $title,
928 readonly => $::form->{id} && ($::form->{locked} || !_get_radieren()),
931 $::lxdebug->leave_sub;
936 $::lxdebug->enter_sub;
937 $::auth->assert('gl_transactions');
939 my ($follow_ups, $follow_ups_due);
942 $follow_ups = FU->follow_ups('trans_id' => $::form->{id}, 'not_done' => 1);
943 $follow_ups_due = sum map { $_->{due} * 1 } @{ $follow_ups || [] };
946 print $::form->parse_html_template('gl/form_footer', {
947 radieren => _get_radieren(),
948 follow_ups => $follow_ups,
949 follow_ups_due => $follow_ups_due,
952 $::lxdebug->leave_sub;
956 $main::lxdebug->enter_sub();
958 my $form = $main::form;
959 my $locale = $main::locale;
964 <form method=post action=gl.pl>
967 map { $form->{$_} =~ s/\"/"/g } qw(reference description);
969 delete $form->{header};
971 foreach my $key (keys %$form) {
972 next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
973 print qq|<input type="hidden" name="$key" value="$form->{$key}">\n|;
977 <h2 class=confirm>| . $locale->text('Confirm!') . qq|</h2>
980 . $locale->text('Are you sure you want to delete Transaction')
981 . qq| $form->{reference}</h4>
983 <input name=action class=submit type=submit value="|
984 . $locale->text('Yes') . qq|">
987 $main::lxdebug->leave_sub();
992 $main::lxdebug->enter_sub();
994 my $form = $main::form;
995 my %myconfig = %main::myconfig;
996 my $locale = $main::locale;
998 if (GL->delete_transaction(\%myconfig, \%$form)){
1000 if(!exists $form->{addition} && $form->{id} ne "") {
1001 $form->{snumbers} = qq|gltransaction_| . $form->{id};
1002 $form->{addition} = "DELETED";
1003 $form->{what_done} = "gl_transaction";
1004 $form->save_history;
1006 # /saving the history
1007 $form->redirect($locale->text('Transaction deleted!'))
1009 $form->error($locale->text('Cannot delete transaction!'));
1010 $main::lxdebug->leave_sub();
1014 sub post_transaction {
1015 $main::lxdebug->enter_sub();
1017 my $form = $main::form;
1018 my %myconfig = %main::myconfig;
1019 my $locale = $main::locale;
1021 # check if there is something in reference and date
1022 $form->isblank("reference", $locale->text('Reference missing!'));
1023 $form->isblank("transdate", $locale->text('Transaction Date missing!'));
1024 $form->isblank("description", $locale->text('Description missing!'));
1026 my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
1027 my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
1034 my $creditcount = 0;
1036 my %split_safety = ();
1038 my $dbh = SL::DB->client->dbh;
1039 my ($notax_id) = selectrow_query($form, $dbh, "SELECT id FROM tax WHERE taxkey = 0 LIMIT 1", );
1040 my $zerotaxes = selectall_hashref_query($form, $dbh, "SELECT id FROM tax WHERE rate = 0", );
1042 my @flds = qw(accno debit credit projectnumber fx_transaction source memo tax taxchart);
1044 for my $i (1 .. $form->{rowcount}) {
1045 next if $form->{"debit_$i"} eq "" && $form->{"credit_$i"} eq "";
1047 for (qw(debit credit tax)) {
1048 $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"});
1052 $debitcredit = ($form->{"debit_$i"} == 0) ? "0" : "1";
1054 $split_safety{ $form->{"debit_$i"} <=> 0 }++;
1055 $split_safety{ - $form->{"credit_$i"} <=> 0 }++;
1063 if (($debitcount >= 2) && ($creditcount == 2)) {
1064 $form->{"credit_$i"} = 0;
1065 $form->{"tax_$i"} = 0;
1067 $form->{creditlock} = 1;
1069 if (($creditcount >= 2) && ($debitcount == 2)) {
1070 $form->{"debit_$i"} = 0;
1071 $form->{"tax_$i"} = 0;
1073 $form->{debitlock} = 1;
1075 if (($creditcount == 1) && ($debitcount == 2)) {
1076 $form->{creditlock} = 1;
1078 if (($creditcount == 2) && ($debitcount == 1)) {
1079 $form->{debitlock} = 1;
1081 if ($debitcredit && $credittax) {
1082 $form->{"taxchart_$i"} = "$notax_id--0.00";
1084 if (!$debitcredit && $debittax) {
1085 $form->{"taxchart_$i"} = "$notax_id--0.00";
1087 my $amount = ($form->{"debit_$i"} == 0)
1088 ? $form->{"credit_$i"}
1089 : $form->{"debit_$i"};
1091 if (($debitcredit && $credittax) || (!$debitcredit && $debittax)) {
1092 $form->{"taxchart_$i"} = "$notax_id--0.00";
1093 $form->{"tax_$i"} = 0;
1095 my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
1096 my $iswithouttax = grep { $_->{id} == $taxkey } @{ $zerotaxes };
1097 if (!$iswithouttax) {
1104 my ($tmpnetamount,$tmpdiff);
1105 ($tmpnetamount,$form->{"tax_$i"},$tmpdiff) = $form->calculate_tax($amount,$rate,$form->{taxincluded} *= 1,2);
1107 $form->{"debit_$i"} = $tmpnetamount;
1109 $form->{"credit_$i"} = $tmpnetamount;
1113 $form->{"tax_$i"} = 0;
1116 for (@flds) { $a[$j]->{$_} = $form->{"${_}_$i"} }
1120 if ($split_safety{-1} > 1 && $split_safety{1} > 1) {
1121 $::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. " .
1122 "Due to known problems involving accounting software kivitendo does not allow these."));
1125 for my $i (1 .. $count) {
1127 for (@flds) { $form->{"${_}_$i"} = $a[$j]->{$_} }
1130 for my $i ($count + 1 .. $form->{rowcount}) {
1131 for (@flds) { delete $form->{"${_}_$i"} }
1134 my ($debit, $credit, $taxtotal);
1135 for my $i (1 .. $form->{rowcount}) {
1136 my $dr = $form->{"debit_$i"};
1137 my $cr = $form->{"credit_$i"};
1138 my $tax = $form->{"tax_$i"};
1140 $form->error($locale->text('Cannot post transaction with a debit and credit entry for the same account!'));
1142 $debit += $dr + $tax if $dr;
1143 $credit += $cr + $tax if $cr;
1144 $taxtotal += $tax if $form->{taxincluded}
1147 $form->{taxincluded} = 0 if !$taxtotal;
1149 # this is just for the wise guys
1151 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
1152 if ($form->date_max_future($form->{"transdate"}, \%myconfig));
1153 $form->error($locale->text('Cannot post transaction for a closed period!'))
1154 if ($form->date_closed($form->{"transdate"}, \%myconfig));
1155 if ($form->round_amount($debit, 2) != $form->round_amount($credit, 2)) {
1156 $form->error($locale->text('Out of balance transaction!'));
1159 if ($form->round_amount($debit, 2) + $form->round_amount($credit, 2) == 0) {
1160 $form->error($locale->text('Empty transaction!'));
1163 if ((my $errno = GL->post_transaction(\%myconfig, \%$form)) <= -1) {
1166 $err[1] = $locale->text('Cannot have a value in both Debit and Credit!');
1167 $err[2] = $locale->text('Debit and credit out of balance!');
1168 $err[3] = $locale->text('Cannot post a transaction without a value!');
1170 $form->error($err[$errno]);
1172 undef($form->{callback});
1173 # saving the history
1174 if(!exists $form->{addition} && $form->{id} ne "") {
1175 $form->{snumbers} = qq|gltransaction_| . $form->{id};
1176 $form->{addition} = "POSTED";
1177 $form->{what_done} = "gl transaction";
1178 $form->save_history;
1180 # /saving the history
1182 $main::lxdebug->leave_sub();
1186 $main::lxdebug->enter_sub();
1188 $main::auth->assert('gl_transactions');
1190 my $form = $main::form;
1191 my $locale = $main::locale;
1193 if ($::myconfig{mandatory_departments} && !$form->{department_id}) {
1194 $form->{saved_message} = $::locale->text('You have to specify a department.');
1199 $form->{title} = $locale->text("$form->{title} General Ledger Transaction");
1200 $form->{storno} = 0;
1203 if ($::instance_conf->get_webdav) {
1204 SL::Webdav->new(type => 'general_ledger',
1205 number => $form->{reference},
1209 $form->{callback} = build_std_url("action=add", "show_details");
1210 $form->redirect($::locale->text("General ledger transaction '#1' posted", $form->{reference}));
1212 $main::lxdebug->leave_sub();
1216 $main::lxdebug->enter_sub();
1218 $main::auth->assert('gl_transactions');
1220 my $form = $main::form;
1224 $main::lxdebug->leave_sub();
1229 $main::lxdebug->enter_sub();
1231 $main::auth->assert('gl_transactions');
1233 my $form = $main::form;
1234 my %myconfig = %main::myconfig;
1235 my $locale = $main::locale;
1237 # don't cancel cancelled transactions
1238 if (IS->has_storno(\%myconfig, $form, 'gl')) {
1239 $form->{title} = $locale->text("Cancel Accounts Receivables Transaction");
1240 $form->error($locale->text("Transaction has already been cancelled!"));
1243 GL->storno($form, \%myconfig, $form->{id});
1245 # saving the history
1246 if(!exists $form->{addition} && $form->{id} ne "") {
1247 $form->{snumbers} = qq|gltransaction_| . $form->{id};
1248 $form->{addition} = "STORNO";
1249 $form->{what_done} = "gl_transaction";
1250 $form->save_history;
1252 # /saving the history
1254 $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
1256 $main::lxdebug->leave_sub();
1260 call_sub($main::form->{nextsub});
1263 sub get_tax_dropdown {
1264 my $transdate = $::form->{transdate} ? DateTime->from_kivitendo($::form->{transdate}) : DateTime->today_local;
1265 my @tax_accounts = GL->get_active_taxes_for_chart($::form->{accno_id}, $transdate);
1266 my $html = $::form->parse_html_template("gl/update_tax_accounts", { TAX_ACCOUNTS => \@tax_accounts });
1268 print $::form->ajax_response_header, $html;
1271 sub get_chart_balance {
1272 my %balances = GL->get_chart_balances($::form->{accno_id});
1273 my $balance = $::form->format_amount(\%::myconfig, $balances{ $::form->{accno_id} }, 2, 'DRCR');
1275 print $::form->ajax_response_header, $balance;