Belegvorlagen: Speichern bei Debitorenbuchungen
[kivitendo-erp.git] / bin / mozilla / ar.pl
1 #=====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (c) 2001
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 #
16 # This program is free software; you can redistribute it and/or modify
17 # it under the terms of the GNU General Public License as published by
18 # the Free Software Foundation; either version 2 of the License, or
19 # (at your option) any later version.
20 #
21 # This program is distributed in the hope that it will be useful,
22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 # GNU General Public License for more details.
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
28 # MA 02110-1335, USA.
29 #======================================================================
30 #
31 # Accounts Receivables
32 #
33 #======================================================================
34
35 use POSIX qw(strftime);
36 use List::Util qw(sum first max);
37 use List::UtilsBy qw(sort_by);
38
39 use SL::AR;
40 use SL::Controller::Base;
41 use SL::FU;
42 use SL::GL;
43 use SL::IS;
44 use SL::DB::Business;
45 use SL::DB::Chart;
46 use SL::DB::Currency;
47 use SL::DB::Default;
48 use SL::DB::Employee;
49 use SL::DB::Invoice;
50 use SL::DB::RecordTemplate;
51 use SL::DB::Tax;
52 use SL::Helper::Flash qw(flash);
53 use SL::ReportGenerator;
54
55 require "bin/mozilla/common.pl";
56 require "bin/mozilla/reportgenerator.pl";
57
58 use strict;
59 #use warnings;
60
61 # this is for our long dates
62 # $locale->text('January')
63 # $locale->text('February')
64 # $locale->text('March')
65 # $locale->text('April')
66 # $locale->text('May ')
67 # $locale->text('June')
68 # $locale->text('July')
69 # $locale->text('August')
70 # $locale->text('September')
71 # $locale->text('October')
72 # $locale->text('November')
73 # $locale->text('December')
74
75 # this is for our short month
76 # $locale->text('Jan')
77 # $locale->text('Feb')
78 # $locale->text('Mar')
79 # $locale->text('Apr')
80 # $locale->text('May')
81 # $locale->text('Jun')
82 # $locale->text('Jul')
83 # $locale->text('Aug')
84 # $locale->text('Sep')
85 # $locale->text('Oct')
86 # $locale->text('Nov')
87 # $locale->text('Dec')
88
89 sub load_record_template {
90   $::auth->assert('ar_transactions');
91
92   # Load existing template and verify that its one for this module.
93   my $template = SL::DB::RecordTemplate
94     ->new(id => $::form->{id})
95     ->load(
96       with_object => [ qw(customer payment currency record_items record_items.chart) ],
97     );
98
99   die "invalid template type" unless $template->template_type eq 'ar_transaction';
100
101   $template->substitute_variables;
102
103   # Clean the current $::form before rebuilding it from the template.
104   delete @{ $::form }{ grep { !m{^(?:script|login)$}i } keys %{ $::form } };
105
106   # Fill $::form from the template.
107   my $today                   = DateTime->today_local;
108   $::form->{title}            = "Add";
109   $::form->{currency}         = $template->currency->name;
110   $::form->{direct_debit}     = $template->direct_debit;
111   $::form->{globalproject_id} = $template->project_id;
112   $::form->{AR_chart_id}      = $template->ar_ap_chart_id;
113   $::form->{transdate}        = $today->to_kivitendo;
114   $::form->{duedate}          = $today->to_kivitendo;
115   $::form->{rowcount}         = @{ $template->items } + 1;
116   $::form->{paidaccounts}     = 1;
117   $::form->{$_}               = $template->$_ for qw(department_id ordnumber taxincluded employee_id notes);
118
119   if ($template->customer) {
120     $::form->{customer_id} = $template->customer_id;
121     $::form->{customer}    = $template->customer->name;
122     $::form->{duedate}     = $template->customer->payment->calc_date(reference_date => $today)->to_kivitendo if $template->customer->payment;
123   }
124
125   my $row = 0;
126   foreach my $item (@{ $template->items }) {
127     $row++;
128
129     my $active_taxkey = $item->chart->get_active_taxkey;
130     my $taxes         = SL::DB::Manager::Tax->get_all(
131       where   => [ chart_categories => { like => '%' . $item->chart->category . '%' }],
132       sort_by => 'taxkey, rate',
133     );
134
135     my $tax   = first { $item->tax_id          == $_->id } @{ $taxes };
136     $tax    //= first { $active_taxkey->tax_id == $_->id } @{ $taxes };
137     $tax    //= $taxes->[0];
138
139     if (!$tax) {
140       $row--;
141       next;
142     }
143
144     $::form->{"AR_amount_chart_id_${row}"}          = $item->chart_id;
145     $::form->{"previous_AR_amount_chart_id_${row}"} = $item->chart_id;
146     $::form->{"amount_${row}"}                      = $::form->format_amount(\%::myconfig, $item->amount1, 2);
147     $::form->{"taxchart_${row}"}                    = $item->tax_id . '--' . $tax->rate;
148     $::form->{"project_id_${row}"}                  = $item->project_id;
149   }
150
151   flash('info', $::locale->text("The record template '#1' has been loaded.", $template->template_name));
152
153   update();
154 }
155
156 sub save_record_template {
157   $::auth->assert('ar_transactions');
158
159   my $template = $::form->{record_template_id} ? SL::DB::RecordTemplate->new(id => $::form->{record_template_id})->load : SL::DB::RecordTemplate->new;
160   my $js       = SL::ClientJS->new(controller => SL::Controller::Base->new);
161   my $new_name = $template->template_name_to_use($::form->{record_template_new_template_name});
162
163   $js->dialog->close('#record_template_dialog');
164
165   my @items = grep {
166     $_->{chart_id} && (($_->{tax_id} // '') ne '') && ($_->{amount1} != 0)
167   } map {
168     +{ chart_id   => $::form->{"AR_amount_chart_id_${_}"},
169        amount1    => $::form->parse_amount(\%::myconfig, $::form->{"amount_${_}"}),
170        tax_id     => (split m{--}, $::form->{"taxchart_${_}"})[0],
171        project_id => $::form->{"project_id_${_}"} || undef,
172      }
173   } (1..($::form->{rowcount} || 1));
174
175   $template->assign_attributes(
176     template_type  => 'ar_transaction',
177     template_name  => $new_name,
178
179     currency_id    => SL::DB::Manager::Currency->find_by(name => $::form->{currency})->id,
180     ar_ap_chart_id => $::form->{AR_chart_id}      || undef,
181     customer_id    => $::form->{customer_id}      || undef,
182     department_id  => $::form->{department_id}    || undef,
183     project_id     => $::form->{globalproject_id} || undef,
184     employee_id    => $::form->{employee_id}      || undef,
185     taxincluded    => $::form->{taxincluded}  ? 1 : 0,
186     direct_debit   => $::form->{direct_debit} ? 1 : 0,
187     ordnumber      => $::form->{ordnumber},
188     notes          => $::form->{notes},
189
190     items          => \@items,
191   );
192
193   eval {
194     $template->save;
195     1;
196   } or do {
197     return $js
198       ->flash('error', $::locale->text("Saving the record template '#1' failed.", $new_name))
199       ->render;
200   };
201
202   return $js
203     ->flash('info', $::locale->text("The record template '#1' has been saved.", $new_name))
204     ->render;
205 }
206
207 sub add {
208   $main::lxdebug->enter_sub();
209
210   $main::auth->assert('ar_transactions');
211
212   my $form     = $main::form;
213   my %myconfig = %main::myconfig;
214
215   # saving the history
216   if(!exists $form->{addition} && ($form->{id} ne "")) {
217     $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
218     $form->{addition} = "ADDED";
219     $form->save_history;
220   }
221   # /saving the history
222
223   $form->{title}    = "Add";
224   $form->{callback} = "ar.pl?action=add" unless $form->{callback};
225
226   AR->get_transdate(\%myconfig, $form);
227   $form->{initial_transdate} = $form->{transdate};
228   create_links(dont_save => 1);
229   $form->{transdate} = $form->{initial_transdate};
230
231   if ($form->{customer_id}) {
232     my $last_used_ar_chart = SL::DB::Customer->load_cached($form->{customer_id})->last_used_ar_chart;
233     $form->{"AR_amount_chart_id_1"} = $last_used_ar_chart->id if $last_used_ar_chart;
234   }
235
236   &display_form;
237   $main::lxdebug->leave_sub();
238 }
239
240 sub edit {
241   $main::lxdebug->enter_sub();
242
243   $main::auth->assert('ar_transactions');
244
245   my $form     = $main::form;
246
247   # show history button
248   $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
249   #/show hhistory button
250   $form->{javascript} .= qq|<script type="text/javascript" src="js/common.js"></script>|;
251   $form->{title} = "Edit";
252
253   create_links();
254   &display_form;
255
256   $main::lxdebug->leave_sub();
257 }
258
259 sub display_form {
260   $main::lxdebug->enter_sub();
261
262   $main::auth->assert('ar_transactions');
263
264   my $form     = $main::form;
265
266   &form_header;
267   &form_footer;
268
269   $main::lxdebug->leave_sub();
270 }
271
272 sub _retrieve_invoice_object {
273   return undef if !$::form->{id};
274   return $::form->{invoice_obj} if $::form->{invoice_obj} && $::form->{invoice_obj}->id == $::form->{id};
275   return SL::DB::Invoice->new(id => $::form->{id})->load;
276 }
277
278 sub create_links {
279   $main::lxdebug->enter_sub();
280
281   $main::auth->assert('ar_transactions');
282
283   my %params   = @_;
284   my $form     = $main::form;
285   my %myconfig = %main::myconfig;
286
287   $form->create_links("AR", \%myconfig, "customer");
288   $form->{invoice_obj} = _retrieve_invoice_object();
289
290   my %saved;
291   if (!$params{dont_save}) {
292     %saved = map { ($_ => $form->{$_}) } qw(direct_debit id taxincluded);
293     $saved{duedate} = $form->{duedate} if $form->{duedate};
294     $saved{currency} = $form->{currency} if $form->{currency};
295   }
296
297   IS->get_customer(\%myconfig, \%$form);
298
299   $form->{$_}          = $saved{$_} for keys %saved;
300   $form->{rowcount}    = 1;
301   $form->{AR_chart_id} = $form->{acc_trans} && $form->{acc_trans}->{AR} ? $form->{acc_trans}->{AR}->[0]->{chart_id} : $form->{AR_links}->{AR}->[0]->{chart_id};
302
303   # currencies
304   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
305
306   $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all;
307
308   # build the popup menus
309   $form->{taxincluded} = ($form->{id}) ? $form->{taxincluded} : "checked";
310
311   AR->setup_form($form);
312
313   $form->{locked} =
314     ($form->datetonum($form->{transdate}, \%myconfig) <=
315      $form->datetonum($form->{closedto}, \%myconfig));
316
317   $main::lxdebug->leave_sub();
318 }
319
320 sub form_header {
321   $main::lxdebug->enter_sub();
322
323   $main::auth->assert('ar_transactions');
324
325   my $form     = $main::form;
326   my %myconfig = %main::myconfig;
327   my $locale   = $main::locale;
328   my $cgi      = $::request->{cgi};
329
330   $form->{invoice_obj} = _retrieve_invoice_object();
331
332   my ($title, $readonly, $exchangerate, $rows);
333   my ($notes, $amount, $project);
334
335   $form->{initial_focus} = !($form->{amount_1} * 1) ? 'customer_id' : 'row_' . $form->{rowcount};
336
337   $title = $form->{title};
338   # $locale->text('Add Accounts Receivables Transaction')
339   # $locale->text('Edit Accounts Receivables Transaction')
340   $form->{title} = $locale->text("$title Accounts Receivables Transaction");
341
342   $readonly = ($form->{id}) ? "readonly" : "";
343
344   $form->{radier} = ($::instance_conf->get_ar_changeable == 2)
345                       ? ($form->current_date(\%myconfig) eq $form->{gldate})
346                       : ($::instance_conf->get_ar_changeable == 1);
347   $readonly = ($form->{radier}) ? "" : $readonly;
348
349   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'buy');
350   $form->{exchangerate} = $form->{forex} if $form->{forex};
351
352   # format exchangerate
353   $form->{exchangerate}    = $form->{exchangerate} ? $form->format_amount(\%myconfig, $form->{exchangerate}) : '';
354
355   $rows = max 2, $form->numtextrows($form->{notes}, 50);
356
357   my @old_project_ids = grep { $_ } map { $form->{"project_id_$_"} } 1..$form->{rowcount};
358
359   $form->get_lists("projects"  => { "key"       => "ALL_PROJECTS",
360                                     "all"       => 0,
361                                     "old_id"    => \@old_project_ids },
362                    "charts"    => { "key"       => "ALL_CHARTS",
363                                     "transdate" => $form->{transdate} },
364                    "taxcharts" => { "key"       => "ALL_TAXCHARTS",
365                                     "module"    => "AR" },);
366
367   $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all;
368
369   $_->{link_split} = { map { $_ => 1 } split/:/, $_->{link} } for @{ $form->{ALL_CHARTS} };
370
371   my %project_labels = map { $_->{id} => $_->{projectnumber} } @{ $form->{"ALL_PROJECTS"} };
372
373   my (@AR_paid_values, %AR_paid_labels);
374   my $default_ar_amount_chart_id;
375
376   foreach my $item (@{ $form->{ALL_CHARTS} }) {
377     if ($item->{link_split}{AR_amount}) {
378       $default_ar_amount_chart_id //= $item->{id};
379
380     } elsif ($item->{link_split}{AR_paid}) {
381       push(@AR_paid_values, $item->{accno});
382       $AR_paid_labels{$item->{accno}} = "$item->{accno}--$item->{description}";
383     }
384   }
385
386   my $follow_up_vc         = $form->{customer_id} ? SL::DB::Customer->load_cached($form->{customer_id})->name : '';
387   my $follow_up_trans_info =  "$form->{invnumber} ($follow_up_vc)";
388
389   $::request->layout->add_javascripts("autocomplete_chart.js", "autocomplete_customer.js", "show_vc_details.js", "show_history.js", "follow_up.js", "kivi.Draft.js", "kivi.GL.js", "kivi.RecordTemplate.js");
390
391   my $transdate = $::form->{transdate} ? DateTime->from_kivitendo($::form->{transdate}) : DateTime->today_local;
392   my $first_taxchart;
393
394   my @transactions;
395   for my $i (1 .. $form->{rowcount}) {
396     my $transaction = {
397       amount     => $form->{"amount_$i"},
398       tax        => $form->{"tax_$i"},
399       project_id => ($i==$form->{rowcount}) ? $form->{globalproject_id} : $form->{"project_id_$i"},
400     };
401
402     my (%taxchart_labels, @taxchart_values, $default_taxchart, $taxchart_to_use);
403     my $amount_chart_id   = $form->{"AR_amount_chart_id_$i"} // $default_ar_amount_chart_id;
404     my $chart_has_changed = $::form->{"previous_AR_amount_chart_id_$i"} && ($amount_chart_id != $::form->{"previous_AR_amount_chart_id_$i"});
405
406     foreach my $item ( GL->get_active_taxes_for_chart($amount_chart_id, $transdate) ) {
407       my $key             = $item->id . "--" . $item->rate;
408       $first_taxchart   //= $item;
409       $default_taxchart   = $item if $item->{is_default};
410       $taxchart_to_use    = $item if $key eq $form->{"taxchart_$i"};
411
412       push(@taxchart_values, $key);
413       $taxchart_labels{$key} = $item->taxdescription . " " . $item->rate * 100 . ' %';
414     }
415
416     $taxchart_to_use      = $default_taxchart // $first_taxchart if $chart_has_changed || !$taxchart_to_use;
417     my $selected_taxchart = $taxchart_to_use->id . '--' . $taxchart_to_use->rate;
418
419     $transaction->{selectAR_amount} =
420         $::request->presenter->chart_picker("AR_amount_chart_id_$i", $amount_chart_id, style => "width: 400px", type => "AR_amount", class => ($form->{initial_focus} eq "row_$i" ? "initial_focus" : ""))
421       . $::request->presenter->hidden_tag("previous_AR_amount_chart_id_$i", $amount_chart_id);
422
423     $transaction->{taxchart} =
424       NTI($cgi->popup_menu('-name' => "taxchart_$i",
425                            '-id' => "taxchart_$i",
426                            '-style' => 'width:200px',
427                            '-values' => \@taxchart_values,
428                            '-labels' => \%taxchart_labels,
429                            '-default' => $selected_taxchart));
430
431     push @transactions, $transaction;
432   }
433
434   $form->{invtotal_unformatted} = $form->{invtotal};
435
436   $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
437
438   my $now = $form->current_date(\%myconfig);
439
440   my @payments;
441   for my $i (1 .. $form->{paidaccounts}) {
442     my $payment = {
443       paid             => $form->{"paid_$i"},
444       exchangerate     => $form->{"exchangerate_$i"} || '',
445       gldate           => $form->{"gldate_$i"},
446       acc_trans_id     => $form->{"acc_trans_id_$i"},
447       source           => $form->{"source_$i"},
448       memo             => $form->{"memo_$i"},
449       AR_paid          => $form->{"AR_paid_$i"},
450       forex            => $form->{"forex_$i"},
451       datepaid         => $form->{"datepaid_$i"},
452       paid_project_id  => $form->{"paid_project_id_$i"},
453       gldate           => $form->{"gldate_$i"},
454     };
455
456     # default account for current assets (i.e. 1801 - SKR04) if no account is selected
457     $form->{accno_arap} = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
458
459     $payment->{selectAR_paid} =
460       NTI($cgi->popup_menu('-name' => "AR_paid_$i",
461                            '-id' => "AR_paid_$i",
462                            '-values' => \@AR_paid_values,
463                            '-labels' => \%AR_paid_labels,
464                            '-default' => $payment->{AR_paid} || $form->{accno_arap}));
465
466
467
468     $payment->{changeable} =
469         SL::DB::Default->get->payments_changeable == 0 ? !$payment->{acc_trans_id} # never
470       : SL::DB::Default->get->payments_changeable == 2 ? $payment->{gldate} eq '' || $payment->{gldate} eq $now
471       :                                                           1;
472
473     #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
474     if ($form->date_closed($payment->{"gldate_$i"})) {
475         $payment->{changeable} = 0;
476     }
477
478     push @payments, $payment;
479   }
480
481   my @empty = grep { $_->{paid} eq '' } @payments;
482   @payments = (
483     (sort_by { DateTime->from_kivitendo($_->{datepaid}) } grep { $_->{paid} ne '' } @payments),
484     @empty,
485   );
486
487   $form->{totalpaid} = sum map { $_->{paid} } @payments;
488
489   my $employees = SL::DB::Manager::Employee->get_all_sorted(
490     where => [
491       or => [
492         (id     => $::form->{employee_id}) x !!$::form->{employee_id},
493         deleted => undef,
494         deleted => 0,
495       ],
496     ],
497   );
498
499   $form->header;
500   print $::form->parse_html_template('ar/form_header', {
501     paid_missing         => $::form->{invtotal} - $::form->{totalpaid},
502     show_exch            => ($::form->{defaultcurrency} && ($::form->{currency} ne $::form->{defaultcurrency})),
503     payments             => \@payments,
504     transactions         => \@transactions,
505     project_labels       => \%project_labels,
506     rows                 => $rows,
507     AR_chart_id          => $form->{AR_chart_id},
508     title_str            => $title,
509     follow_up_trans_info => $follow_up_trans_info,
510     today                => DateTime->today,
511     currencies           => scalar(SL::DB::Manager::Currency->get_all_sorted),
512     employees            => $employees,
513   });
514
515   $main::lxdebug->leave_sub();
516 }
517
518 sub form_footer {
519   $main::lxdebug->enter_sub();
520
521   $main::auth->assert('ar_transactions');
522
523   my $form     = $main::form;
524   my %myconfig = %main::myconfig;
525   my $locale   = $main::locale;
526   my $cgi      = $::request->{cgi};
527
528   if ( $form->{id} ) {
529     my $follow_ups = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1);
530     if ( @{ $follow_ups} ) {
531       $form->{follow_up_length} = scalar(@{$follow_ups});
532       $form->{follow_up_due_length} = sum(map({ $_->{due} * 1 } @{ $follow_ups }));
533     }
534   }
535
536   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
537   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
538
539   $form->{is_closed} = $transdate <= $closedto;
540
541   # ToDO: - insert a global check for stornos, so that a storno is only possible a limited time after saving it
542   $form->{show_storno_button} =
543     $form->{id} &&
544     !IS->has_storno(\%myconfig, $form, 'ar') &&
545     !IS->is_storno(\%myconfig, $form, 'ar') &&
546     ($form->{totalpaid} == 0 || $form->{totalpaid} eq "");
547
548   $form->{show_mark_as_paid_button} = $form->{id} && $::instance_conf->get_ar_show_mark_as_paid();
549
550   print $::form->parse_html_template('ar/form_footer');
551
552   $main::lxdebug->leave_sub();
553 }
554
555 sub mark_as_paid {
556   $::auth->assert('ar_transactions');
557
558   SL::DB::Invoice->new(id => $::form->{id})->load->mark_as_paid;
559
560   $::form->redirect($::locale->text("Marked as paid"));
561 }
562
563 sub show_draft {
564   $::form->{transdate} = DateTime->today_local->to_kivitendo if !$::form->{transdate};
565   $::form->{gldate}    = $::form->{transdate} if !$::form->{gldate};
566   update();
567 }
568
569 sub update {
570   $main::lxdebug->enter_sub();
571
572   $main::auth->assert('ar_transactions');
573
574   my $form     = $main::form;
575   my %myconfig = %main::myconfig;
576
577   my $display = shift;
578
579   my ($totaltax, $exchangerate);
580
581   $form->{invtotal} = 0;
582
583   delete @{ $form }{ grep { m/^tax_\d+$/ } keys %{ $form } };
584
585   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
586     qw(exchangerate creditlimit creditremaining);
587
588   my @flds  = qw(amount AR_amount projectnumber oldprojectnumber project_id);
589   my $count = 0;
590   my @a     = ();
591
592   for my $i (1 .. $form->{rowcount}) {
593     $form->{"amount_$i"} = $form->parse_amount(\%myconfig, $form->{"amount_$i"});
594     if ($form->{"amount_$i"}) {
595       push @a, {};
596       my $j = $#a;
597       my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
598
599       my $tmpnetamount;
600       ($tmpnetamount,$form->{"tax_$i"}) = $form->calculate_tax($form->{"amount_$i"},$rate,$form->{taxincluded},2);
601
602       $totaltax += $form->{"tax_$i"};
603       map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
604       $count++;
605     }
606   }
607
608   $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
609   $form->{rowcount} = $count + 1;
610   map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
611
612   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'buy');
613   $form->{exchangerate} = $form->{forex} if $form->{forex};
614
615   $form->{invdate} = $form->{transdate};
616
617   if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
618     IS->get_customer(\%myconfig, $form);
619   }
620
621   $form->{invtotal} =
622     ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
623
624   for my $i (1 .. $form->{paidaccounts}) {
625     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
626       map {
627         $form->{"${_}_$i"} =
628           $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
629       } qw(paid exchangerate);
630
631       $form->{totalpaid} += $form->{"paid_$i"};
632
633       $form->{"forex_$i"}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
634       $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
635     }
636   }
637
638   $form->{creditremaining} -=
639     ($form->{invtotal} - $form->{totalpaid} + $form->{oldtotalpaid} -
640      $form->{oldinvtotal});
641   $form->{oldinvtotal}  = $form->{invtotal};
642   $form->{oldtotalpaid} = $form->{totalpaid};
643
644   &display_form;
645
646   $main::lxdebug->leave_sub();
647 }
648
649 #
650 # ToDO: fix $closedto and $invdate
651 #
652 sub post_payment {
653   $main::lxdebug->enter_sub();
654
655   $main::auth->assert('ar_transactions');
656
657   my $form     = $main::form;
658   my %myconfig = %main::myconfig;
659   my $locale   = $main::locale;
660
661   $form->mtime_ischanged('ar');
662   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
663
664   my $invdate = $form->datetonum($form->{transdate}, \%myconfig);
665
666   for my $i (1 .. $form->{paidaccounts}) {
667
668     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
669       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
670
671       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
672
673       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
674         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
675
676       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
677       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
678       $form->error($locale->text('Cannot post payment for a closed period!'))
679         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
680
681       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
682 #        $form->{"exchangerate_$i"} = $form->{exchangerate} if ($invdate == $datepaid);
683         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
684       }
685     }
686   }
687
688   ($form->{AR})      = split /--/, $form->{AR};
689   ($form->{AR_paid}) = split /--/, $form->{AR_paid};
690   if (AR->post_payment(\%myconfig, \%$form)) {
691     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
692     $form->{what_done} = 'invoice';
693     $form->{addition}  = "PAYMENT POSTED";
694     $form->save_history;
695     $form->redirect($locale->text('Payment posted!'))
696   } else {
697     $form->error($locale->text('Cannot post payment!'));
698   };
699
700   $main::lxdebug->leave_sub();
701 }
702
703 sub _post {
704
705   $main::auth->assert('ar_transactions');
706
707   my $form     = $main::form;
708
709   # inline post
710   post(1);
711 }
712
713 sub post {
714   $main::lxdebug->enter_sub();
715
716   $main::auth->assert('ar_transactions');
717
718   my $form     = $main::form;
719   my %myconfig = %main::myconfig;
720   my $locale   = $main::locale;
721
722   my ($inline) = @_;
723
724   $form->mtime_ischanged('ar');
725
726   my ($datepaid);
727
728   # check if there is an invoice number, invoice and due date
729   $form->isblank("transdate", $locale->text('Invoice Date missing!'));
730   $form->isblank("duedate",   $locale->text('Due Date missing!'));
731   $form->isblank("customer_id", $locale->text('Customer missing!'));
732
733   if ($myconfig{mandatory_departments} && !$form->{department_id}) {
734     $form->{saved_message} = $::locale->text('You have to specify a department.');
735     update();
736     exit;
737   }
738
739   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
740   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
741
742   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
743     if ($form->date_max_future($transdate, \%myconfig));
744
745   $form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
746
747   $form->error($locale->text('Zero amount posting!'))
748     unless grep $_*1, map $form->parse_amount(\%myconfig, $form->{"amount_$_"}), 1..$form->{rowcount};
749
750   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
751     if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency}));
752
753   delete($form->{AR});
754
755   for my $i (1 .. $form->{paidaccounts}) {
756     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
757       $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
758
759       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
760
761       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
762         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
763
764       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
765       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
766       $form->error($locale->text('Cannot post payment for a closed period!'))
767         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
768
769       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
770         $form->{"exchangerate_$i"} = $form->{exchangerate} if ($transdate == $datepaid);
771         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
772       }
773     }
774   }
775
776   # if oldcustomer ne customer redo form
777   if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
778     update();
779     $::dispatcher->end_request;
780   }
781
782   $form->{AR}{receivables} = $form->{ARselected};
783   $form->{storno}          = 0;
784
785   $form->{id} = 0 if $form->{postasnew};
786   $form->error($locale->text('Cannot post transaction!')) unless AR->post_transaction(\%myconfig, \%$form);
787
788   # saving the history
789   if(!exists $form->{addition} && $form->{id} ne "") {
790     $form->{snumbers}  = "invnumber_$form->{invnumber}";
791     $form->{what_done} = "invoice";
792     $form->{addition}  = "POSTED";
793     $form->save_history;
794   }
795   # /saving the history
796
797   $form->redirect($locale->text("AR transaction posted.")) unless $inline;
798
799   $main::lxdebug->leave_sub();
800 }
801
802 sub post_as_new {
803   $main::lxdebug->enter_sub();
804
805   $main::auth->assert('ar_transactions');
806
807   my $form     = $main::form;
808   my %myconfig = %main::myconfig;
809
810   $form->{postasnew} = 1;
811   # saving the history
812   if(!exists $form->{addition} && $form->{id} ne "") {
813     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
814     $form->{what_done} = "invoice";
815     $form->{addition}  = "POSTED AS NEW";
816     $form->save_history;
817   }
818   # /saving the history
819   &post;
820
821   $main::lxdebug->leave_sub();
822 }
823
824 sub use_as_new {
825   $main::lxdebug->enter_sub();
826
827   $main::auth->assert('ar_transactions');
828
829   my $form     = $main::form;
830   my %myconfig = %main::myconfig;
831
832   map { delete $form->{$_} } qw(printed emailed queued invnumber invdate deliverydate id datepaid_1 gldate_1 acc_trans_id_1 source_1 memo_1 paid_1 exchangerate_1 AP_paid_1 storno);
833   $form->{paidaccounts} = 1;
834   $form->{rowcount}--;
835   $form->{invdate} = $form->current_date(\%myconfig);
836   &update;
837
838   $main::lxdebug->leave_sub();
839 }
840
841 sub delete {
842   $main::lxdebug->enter_sub();
843
844   $main::auth->assert('ar_transactions');
845
846   my $form     = $main::form;
847   my $locale   = $main::locale;
848
849   $form->{title} = $locale->text('Confirm!');
850
851   $form->header;
852
853   delete $form->{header};
854
855   print qq|
856 <form method=post action=$form->{script}>
857 |;
858
859   foreach my $key (keys %$form) {
860     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
861     $form->{$key} =~ s/\"/&quot;/g;
862     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
863   }
864
865   print qq|
866 <h2 class=confirm>$form->{title}</h2>
867
868 <h4>|
869     . $locale->text('Are you sure you want to delete Transaction')
870     . qq| $form->{invnumber}</h4>
871
872 <input name=action class=submit type=submit value="|
873     . $locale->text('Yes') . qq|">
874 </form>
875 |;
876
877   $main::lxdebug->leave_sub();
878 }
879
880 sub yes {
881   $main::lxdebug->enter_sub();
882
883   $main::auth->assert('ar_transactions');
884
885   my $form     = $main::form;
886   my %myconfig = %main::myconfig;
887   my $locale   = $main::locale;
888
889   if (AR->delete_transaction(\%myconfig, \%$form)) {
890     # saving the history
891     if(!exists $form->{addition}) {
892       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
893       $form->{what_done} = "invoice";
894       $form->{addition}  = "DELETED";
895       $form->save_history;
896     }
897     # /saving the history
898     $form->redirect($locale->text('Transaction deleted!'));
899   }
900   $form->error($locale->text('Cannot delete transaction!'));
901
902   $main::lxdebug->leave_sub();
903 }
904
905 sub search {
906   $main::lxdebug->enter_sub();
907
908   $main::auth->assert('invoice_edit');
909
910   my $form     = $main::form;
911   my %myconfig = %main::myconfig;
912   my $locale   = $main::locale;
913   my $cgi      = $::request->{cgi};
914
915   $form->{title}    = $locale->text('AR Transactions');
916
917   $form->{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]);
918   $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
919   $form->{ALL_BUSINESS_TYPES} = SL::DB::Manager::Business->get_all_sorted;
920
921   $form->{CT_CUSTOM_VARIABLES}                  = CVar->get_configs('module' => 'CT');
922   ($form->{CT_CUSTOM_VARIABLES_FILTER_CODE},
923    $form->{CT_CUSTOM_VARIABLES_INCLUSION_CODE}) = CVar->render_search_options('variables'      => $form->{CT_CUSTOM_VARIABLES},
924                                                                               'include_prefix' => 'l_',
925                                                                               'include_value'  => 'Y');
926
927   # constants and subs for template
928   $form->{vc_keys}   = sub { "$_[0]->{name}--$_[0]->{id}" };
929
930   $::request->layout->add_javascripts("autocomplete_project.js");
931
932   $form->header;
933   print $form->parse_html_template('ar/search', { %myconfig });
934
935   $main::lxdebug->leave_sub();
936 }
937
938 sub create_subtotal_row {
939   $main::lxdebug->enter_sub();
940
941   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
942
943   my $form     = $main::form;
944   my %myconfig = %main::myconfig;
945
946   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
947
948   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
949
950   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
951
952   map { $totals->{$_} = 0 } @{ $subtotal_columns };
953
954   $main::lxdebug->leave_sub();
955
956   return $row;
957 }
958
959 sub ar_transactions {
960   $main::lxdebug->enter_sub();
961
962   $main::auth->assert('invoice_edit');
963
964   my $form     = $main::form;
965   my %myconfig = %main::myconfig;
966   my $locale   = $main::locale;
967
968   my ($callback, $href, @columns);
969
970   report_generator_set_default_sort('transdate', 1);
971
972   AR->ar_transactions(\%myconfig, \%$form);
973
974   $form->{title} = $locale->text('AR Transactions');
975
976   my $report = SL::ReportGenerator->new(\%myconfig, $form);
977
978   @columns =
979     qw(ids transdate id type invnumber ordnumber cusordnumber name netamount tax amount paid
980        datepaid due duedate transaction_description notes salesman employee shippingpoint shipvia
981        marge_total marge_percent globalprojectnumber customernumber country ustid taxzone
982        payment_terms charts customertype direct_debit dunning_description department);
983
984   my $ct_cvar_configs                 = CVar->get_configs('module' => 'CT');
985   my @ct_includeable_custom_variables = grep { $_->{includeable} } @{ $ct_cvar_configs };
986   my @ct_searchable_custom_variables  = grep { $_->{searchable} }  @{ $ct_cvar_configs };
987
988   my %column_defs_cvars = map { +"cvar_$_->{name}" => { 'text' => $_->{description} } } @ct_includeable_custom_variables;
989   push @columns, map { "cvar_$_->{name}" } @ct_includeable_custom_variables;
990
991   my @hidden_variables = map { "l_${_}" } @columns;
992   push @hidden_variables, "l_subtotal", qw(open closed customer invnumber ordnumber cusordnumber transaction_description notes project_id transdatefrom transdateto duedatefrom duedateto
993                                            employee_id salesman_id business_id parts_partnumber parts_description department_id);
994   push @hidden_variables, map { "cvar_$_->{name}" } @ct_searchable_custom_variables;
995
996   $href = build_std_url('action=ar_transactions', grep { $form->{$_} } @hidden_variables);
997
998   my %column_defs = (
999     'ids'                     => { raw_header_data => $::request->presenter->checkbox_tag("", id => "check_all", checkall => "[data-checkall=1]"), align => 'center' },
1000     'transdate'               => { 'text' => $locale->text('Date'), },
1001     'id'                      => { 'text' => $locale->text('ID'), },
1002     'type'                    => { 'text' => $locale->text('Type'), },
1003     'invnumber'               => { 'text' => $locale->text('Invoice'), },
1004     'ordnumber'               => { 'text' => $locale->text('Order'), },
1005     'cusordnumber'            => { 'text' => $locale->text('Customer Order Number'), },
1006     'name'                    => { 'text' => $locale->text('Customer'), },
1007     'netamount'               => { 'text' => $locale->text('Amount'), },
1008     'tax'                     => { 'text' => $locale->text('Tax'), },
1009     'amount'                  => { 'text' => $locale->text('Total'), },
1010     'paid'                    => { 'text' => $locale->text('Paid'), },
1011     'datepaid'                => { 'text' => $locale->text('Date Paid'), },
1012     'due'                     => { 'text' => $locale->text('Amount Due'), },
1013     'duedate'                 => { 'text' => $locale->text('Due Date'), },
1014     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
1015     'notes'                   => { 'text' => $locale->text('Notes'), },
1016     'salesman'                => { 'text' => $locale->text('Salesperson'), },
1017     'employee'                => { 'text' => $locale->text('Employee'), },
1018     'shippingpoint'           => { 'text' => $locale->text('Shipping Point'), },
1019     'shipvia'                 => { 'text' => $locale->text('Ship via'), },
1020     'globalprojectnumber'     => { 'text' => $locale->text('Document Project Number'), },
1021     'marge_total'             => { 'text' => $locale->text('Ertrag'), },
1022     'marge_percent'           => { 'text' => $locale->text('Ertrag prozentual'), },
1023     'customernumber'          => { 'text' => $locale->text('Customer Number'), },
1024     'country'                 => { 'text' => $locale->text('Country'), },
1025     'ustid'                   => { 'text' => $locale->text('USt-IdNr.'), },
1026     'taxzone'                 => { 'text' => $locale->text('Steuersatz'), },
1027     'payment_terms'           => { 'text' => $locale->text('Payment Terms'), },
1028     'charts'                  => { 'text' => $locale->text('Buchungskonto'), },
1029     'customertype'            => { 'text' => $locale->text('Customer type'), },
1030     'direct_debit'            => { 'text' => $locale->text('direct debit'), },
1031     'department'              => { 'text' => $locale->text('Department'), },
1032     dunning_description       => { 'text' => $locale->text('Dunning level'), },
1033     %column_defs_cvars,
1034   );
1035
1036   foreach my $name (qw(id transdate duedate invnumber ordnumber cusordnumber name datepaid employee shippingpoint shipvia transaction_description direct_debit)) {
1037     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
1038     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
1039   }
1040
1041   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);
1042
1043   $form->{"l_type"} = "Y";
1044   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
1045
1046   $column_defs{ids}->{visible} = 'HTML';
1047
1048   $report->set_columns(%column_defs);
1049   $report->set_column_order(@columns);
1050
1051   $report->set_export_options('ar_transactions', @hidden_variables, qw(sort sortdir));
1052
1053   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
1054
1055   CVar->add_custom_variables_to_report('module'         => 'CT',
1056                                        'trans_id_field' => 'customer_id',
1057                                        'configs'        => $ct_cvar_configs,
1058                                        'column_defs'    => \%column_defs,
1059                                        'data'           => $form->{AR});
1060
1061   my @options;
1062   if ($form->{customer}) {
1063     push @options, $locale->text('Customer') . " : $form->{customer}";
1064   }
1065   if ($form->{cp_name}) {
1066     push @options, $locale->text('Contact Person') . " : $form->{cp_name}";
1067   }
1068
1069   if ($form->{department_id}) {
1070     my $department = SL::DB::Manager::Department->find_by( id => $form->{department_id} );
1071     push @options, $locale->text('Department') . " : " . $department->description;
1072   }
1073   if ($form->{invnumber}) {
1074     push @options, $locale->text('Invoice Number') . " : $form->{invnumber}";
1075   }
1076   if ($form->{ordnumber}) {
1077     push @options, $locale->text('Order Number') . " : $form->{ordnumber}";
1078   }
1079   if ($form->{cusordnumber}) {
1080     push @options, $locale->text('Customer Order Number') . " : $form->{cusordnumber}";
1081   }
1082   if ($form->{notes}) {
1083     push @options, $locale->text('Notes') . " : $form->{notes}";
1084   }
1085   if ($form->{transaction_description}) {
1086     push @options, $locale->text('Transaction description') . " : $form->{transaction_description}";
1087   }
1088   if ($form->{parts_partnumber}) {
1089     push @options, $locale->text('Part Number') . " : $form->{parts_partnumber}";
1090   }
1091   if ($form->{parts_description}) {
1092     push @options, $locale->text('Part Description') . " : $form->{parts_description}";
1093   }
1094   if ($form->{transdatefrom}) {
1095     push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1);
1096   }
1097   if ($form->{transdateto}) {
1098     push @options, $locale->text('Bis') . " " . $locale->date(\%myconfig, $form->{transdateto}, 1);
1099   }
1100   if ($form->{open}) {
1101     push @options, $locale->text('Open');
1102   }
1103   if ($form->{employee_id}) {
1104     my $employee = SL::DB::Employee->new(id => $form->{employee_id})->load;
1105     push @options, $locale->text('Employee') . ' : ' . $employee->name;
1106   }
1107   if ($form->{salesman_id}) {
1108     my $salesman = SL::DB::Employee->new(id => $form->{salesman_id})->load;
1109     push @options, $locale->text('Salesman') . ' : ' . $salesman->name;
1110   }
1111   if ($form->{closed}) {
1112     push @options, $locale->text('Closed');
1113   }
1114
1115   $form->{ALL_PRINTERS} = SL::DB::Manager::Printer->get_all_sorted;
1116
1117   $report->set_options('top_info_text'        => join("\n", @options),
1118                        'raw_top_info_text'    => $form->parse_html_template('ar/ar_transactions_header'),
1119                        'raw_bottom_info_text' => $form->parse_html_template('ar/ar_transactions_bottom'),
1120                        'output_format'        => 'HTML',
1121                        'title'                => $form->{title},
1122                        'attachment_basename'  => $locale->text('invoice_list') . strftime('_%Y%m%d', localtime time),
1123     );
1124   $report->set_options_from_form();
1125   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
1126
1127   # add sort and escape callback, this one we use for the add sub
1128   $form->{callback} = $href .= "&sort=$form->{sort}";
1129
1130   # escape callback for href
1131   $callback = $form->escape($href);
1132
1133   my @subtotal_columns = qw(netamount amount paid due marge_total marge_percent);
1134
1135   my %totals    = map { $_ => 0 } @subtotal_columns;
1136   my %subtotals = map { $_ => 0 } @subtotal_columns;
1137
1138   my $idx = 0;
1139
1140   foreach my $ar (@{ $form->{AR} }) {
1141     $ar->{tax} = $ar->{amount} - $ar->{netamount};
1142     $ar->{due} = $ar->{amount} - $ar->{paid};
1143
1144     map { $subtotals{$_} += $ar->{$_};
1145           $totals{$_}    += $ar->{$_} } @subtotal_columns;
1146
1147     $subtotals{marge_percent} = $subtotals{netamount} ? ($subtotals{marge_total} * 100 / $subtotals{netamount}) : 0;
1148     $totals{marge_percent}    = $totals{netamount}    ? ($totals{marge_total}    * 100 / $totals{netamount}   ) : 0;
1149
1150     my $is_storno  = $ar->{storno} &&  $ar->{storno_id};
1151     my $has_storno = $ar->{storno} && !$ar->{storno_id};
1152
1153     $ar->{type} =
1154       $has_storno       ? $locale->text("Invoice with Storno (abbreviation)") :
1155       $is_storno        ? $locale->text("Storno (one letter abbreviation)") :
1156       $ar->{amount} < 0 ? $locale->text("Credit note (one letter abbreviation)") :
1157       $ar->{invoice}    ? $locale->text("Invoice (one letter abbreviation)") :
1158                           $locale->text("AR Transaction (abbreviation)");
1159
1160     map { $ar->{$_} = $form->format_amount(\%myconfig, $ar->{$_}, 2) } qw(netamount tax amount paid due marge_total marge_percent);
1161
1162     $ar->{direct_debit} = $ar->{direct_debit} ? $::locale->text('yes') : $::locale->text('no');
1163
1164     my $row = { };
1165
1166     foreach my $column (@columns) {
1167       $row->{$column} = {
1168         'data'  => $ar->{$column},
1169         'align' => $column_alignment{$column},
1170       };
1171     }
1172
1173     $row->{invnumber}->{link} = build_std_url("script=" . ($ar->{invoice} ? 'is.pl' : 'ar.pl'), 'action=edit')
1174       . "&id=" . E($ar->{id}) . "&callback=${callback}";
1175
1176     $row->{ids} = {
1177       raw_data =>  $::request->presenter->checkbox_tag("id[]", value => $ar->{id}, "data-checkall" => 1),
1178       valign   => 'center',
1179       align    => 'center',
1180     };
1181
1182     my $row_set = [ $row ];
1183
1184     if (($form->{l_subtotal} eq 'Y')
1185         && (($idx == (scalar @{ $form->{AR} } - 1))
1186             || ($ar->{ $form->{sort} } ne $form->{AR}->[$idx + 1]->{ $form->{sort} }))) {
1187       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
1188     }
1189
1190     $report->add_data($row_set);
1191
1192     $idx++;
1193   }
1194
1195   $report->add_separator();
1196   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
1197
1198   $report->generate_with_headers();
1199
1200   $main::lxdebug->leave_sub();
1201 }
1202
1203 sub storno {
1204   $main::lxdebug->enter_sub();
1205
1206   $main::auth->assert('ar_transactions');
1207
1208   my $form     = $main::form;
1209   my %myconfig = %main::myconfig;
1210   my $locale   = $main::locale;
1211
1212   # don't cancel cancelled transactions
1213   if (IS->has_storno(\%myconfig, $form, 'ar')) {
1214     $form->{title} = $locale->text("Cancel Accounts Receivables Transaction");
1215     $form->error($locale->text("Transaction has already been cancelled!"));
1216   }
1217
1218   AR->storno($form, \%myconfig, $form->{id});
1219
1220   # saving the history
1221   if(!exists $form->{addition} && $form->{id} ne "") {
1222     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
1223     $form->{addition}  = "STORNO";
1224     $form->{what_done} = "invoice";
1225     $form->save_history;
1226   }
1227   # /saving the history
1228
1229   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
1230
1231   $main::lxdebug->leave_sub();
1232 }
1233
1234 1;