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