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