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