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