Alle Rechnungen: »als bezahlt markieren« auf neue Funktionen in SL::DB::(Purchase...
[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   $::auth->assert('ar_transactions');
447
448   SL::DB::Invoice->new(id => $::form->{id})->load->mark_as_paid;
449
450   $::form->redirect($::locale->text("Marked as paid"));
451 }
452
453 sub show_draft {
454   $::form->{transdate} = DateTime->today_local->to_kivitendo if !$::form->{transdate};
455   $::form->{gldate}    = $::form->{transdate} if !$::form->{gldate};
456   update();
457 }
458
459 sub update {
460   $main::lxdebug->enter_sub();
461
462   $main::auth->assert('ar_transactions');
463
464   my $form     = $main::form;
465   my %myconfig = %main::myconfig;
466
467   my $display = shift;
468
469   my ($totaltax, $exchangerate);
470
471   $form->{invtotal} = 0;
472
473   delete @{ $form }{ grep { m/^tax_\d+$/ } keys %{ $form } };
474
475   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
476     qw(exchangerate creditlimit creditremaining);
477
478   my @flds  = qw(amount AR_amount projectnumber oldprojectnumber project_id);
479   my $count = 0;
480   my @a     = ();
481
482   for my $i (1 .. $form->{rowcount}) {
483     $form->{"amount_$i"} = $form->parse_amount(\%myconfig, $form->{"amount_$i"});
484     if ($form->{"amount_$i"}) {
485       push @a, {};
486       my $j = $#a;
487       my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
488
489       my $tmpnetamount;
490       ($tmpnetamount,$form->{"tax_$i"}) = $form->calculate_tax($form->{"amount_$i"},$rate,$form->{taxincluded},2);
491
492       $totaltax += $form->{"tax_$i"};
493       map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
494       $count++;
495     }
496   }
497
498   $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
499   $form->{rowcount} = $count + 1;
500   map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
501
502   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'buy');
503   $form->{exchangerate} = $form->{forex} if $form->{forex};
504
505   $form->{invdate} = $form->{transdate};
506
507   &check_name("customer");
508
509   $form->{invtotal} =
510     ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
511
512   for my $i (1 .. $form->{paidaccounts}) {
513     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
514       map {
515         $form->{"${_}_$i"} =
516           $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
517       } qw(paid exchangerate);
518
519       $form->{totalpaid} += $form->{"paid_$i"};
520
521       $form->{"forex_$i"}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
522       $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
523     }
524   }
525
526   $form->{creditremaining} -=
527     ($form->{invtotal} - $form->{totalpaid} + $form->{oldtotalpaid} -
528      $form->{oldinvtotal});
529   $form->{oldinvtotal}  = $form->{invtotal};
530   $form->{oldtotalpaid} = $form->{totalpaid};
531
532   &display_form;
533
534   $main::lxdebug->leave_sub();
535 }
536
537 #
538 # ToDO: fix $closedto and $invdate
539 #
540 sub post_payment {
541   $main::lxdebug->enter_sub();
542
543   $main::auth->assert('ar_transactions');
544
545   my $form     = $main::form;
546   my %myconfig = %main::myconfig;
547   my $locale   = $main::locale;
548
549   $form->mtime_ischanged('ar');
550   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
551
552   my $invdate = $form->datetonum($form->{transdate}, \%myconfig);
553
554   for my $i (1 .. $form->{paidaccounts}) {
555
556     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
557       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
558
559       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
560
561       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
562         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
563
564       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
565       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
566       $form->error($locale->text('Cannot post payment for a closed period!'))
567         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
568
569       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
570 #        $form->{"exchangerate_$i"} = $form->{exchangerate} if ($invdate == $datepaid);
571         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
572       }
573     }
574   }
575
576   ($form->{AR})      = split /--/, $form->{AR};
577   ($form->{AR_paid}) = split /--/, $form->{AR_paid};
578   if (AR->post_payment(\%myconfig, \%$form)) {
579     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
580     $form->{what_done} = 'invoice';
581     $form->{addition}  = "PAYMENT POSTED";
582     $form->save_history;
583     $form->redirect($locale->text('Payment posted!'))
584   } else {
585     $form->error($locale->text('Cannot post payment!'));
586   };
587
588   $main::lxdebug->leave_sub();
589 }
590
591 sub _post {
592
593   $main::auth->assert('ar_transactions');
594
595   my $form     = $main::form;
596
597   # inline post
598   post(1);
599 }
600
601 sub post {
602   $main::lxdebug->enter_sub();
603
604   $main::auth->assert('ar_transactions');
605
606   my $form     = $main::form;
607   my %myconfig = %main::myconfig;
608   my $locale   = $main::locale;
609
610   my ($inline) = @_;
611
612   $form->mtime_ischanged('ar');
613
614   my ($datepaid);
615
616   # check if there is an invoice number, invoice and due date
617   $form->isblank("transdate", $locale->text('Invoice Date missing!'));
618   $form->isblank("duedate",   $locale->text('Due Date missing!'));
619   $form->isblank("customer",  $locale->text('Customer missing!'));
620
621   if ($myconfig{mandatory_departments} && !$form->{department_id}) {
622     $form->{saved_message} = $::locale->text('You have to specify a department.');
623     update();
624     exit;
625   }
626
627   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
628   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
629
630   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
631     if ($form->date_max_future($transdate, \%myconfig));
632
633   $form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
634
635   $form->error($locale->text('Zero amount posting!'))
636     unless grep $_*1, map $form->parse_amount(\%myconfig, $form->{"amount_$_"}), 1..$form->{rowcount};
637
638   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
639     if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency}));
640
641   delete($form->{AR});
642
643   for my $i (1 .. $form->{paidaccounts}) {
644     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
645       $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
646
647       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
648
649       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
650         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
651
652       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
653       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
654       $form->error($locale->text('Cannot post payment for a closed period!'))
655         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
656
657       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
658         $form->{"exchangerate_$i"} = $form->{exchangerate} if ($transdate == $datepaid);
659         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
660       }
661     }
662   }
663
664   # if oldcustomer ne customer redo form
665   my ($customer) = split /--/, $form->{customer};
666   if ($form->{oldcustomer} ne "$customer--$form->{customer_id}") {
667     update();
668     $::dispatcher->end_request;
669   }
670
671   $form->{AR}{receivables} = $form->{ARselected};
672   $form->{storno}          = 0;
673
674   $form->{id} = 0 if $form->{postasnew};
675   $form->error($locale->text('Cannot post transaction!')) unless AR->post_transaction(\%myconfig, \%$form);
676
677   # saving the history
678   if(!exists $form->{addition} && $form->{id} ne "") {
679     $form->{snumbers}  = "invnumber_$form->{invnumber}";
680     $form->{what_done} = "invoice";
681     $form->{addition}  = "POSTED";
682     $form->save_history;
683   }
684   # /saving the history
685
686   $form->redirect($locale->text('Transaction posted!')) unless $inline;
687
688   $main::lxdebug->leave_sub();
689 }
690
691 sub post_as_new {
692   $main::lxdebug->enter_sub();
693
694   $main::auth->assert('ar_transactions');
695
696   my $form     = $main::form;
697   my %myconfig = %main::myconfig;
698
699   $form->{postasnew} = 1;
700   # saving the history
701   if(!exists $form->{addition} && $form->{id} ne "") {
702     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
703     $form->{what_done} = "invoice";
704     $form->{addition}  = "POSTED AS NEW";
705     $form->save_history;
706   }
707   # /saving the history
708   &post;
709
710   $main::lxdebug->leave_sub();
711 }
712
713 sub use_as_new {
714   $main::lxdebug->enter_sub();
715
716   $main::auth->assert('ar_transactions');
717
718   my $form     = $main::form;
719   my %myconfig = %main::myconfig;
720
721   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);
722   $form->{paidaccounts} = 1;
723   $form->{rowcount}--;
724   $form->{invdate} = $form->current_date(\%myconfig);
725   &update;
726
727   $main::lxdebug->leave_sub();
728 }
729
730 sub delete {
731   $main::lxdebug->enter_sub();
732
733   $main::auth->assert('ar_transactions');
734
735   my $form     = $main::form;
736   my $locale   = $main::locale;
737
738   $form->{title} = $locale->text('Confirm!');
739
740   $form->header;
741
742   delete $form->{header};
743
744   print qq|
745 <form method=post action=$form->{script}>
746 |;
747
748   foreach my $key (keys %$form) {
749     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
750     $form->{$key} =~ s/\"/&quot;/g;
751     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
752   }
753
754   print qq|
755 <h2 class=confirm>$form->{title}</h2>
756
757 <h4>|
758     . $locale->text('Are you sure you want to delete Transaction')
759     . qq| $form->{invnumber}</h4>
760
761 <input name=action class=submit type=submit value="|
762     . $locale->text('Yes') . qq|">
763 </form>
764 |;
765
766   $main::lxdebug->leave_sub();
767 }
768
769 sub yes {
770   $main::lxdebug->enter_sub();
771
772   $main::auth->assert('ar_transactions');
773
774   my $form     = $main::form;
775   my %myconfig = %main::myconfig;
776   my $locale   = $main::locale;
777
778   if (AR->delete_transaction(\%myconfig, \%$form)) {
779     # saving the history
780     if(!exists $form->{addition}) {
781       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
782       $form->{what_done} = "invoice";
783       $form->{addition}  = "DELETED";
784       $form->save_history;
785     }
786     # /saving the history
787     $form->redirect($locale->text('Transaction deleted!'));
788   }
789   $form->error($locale->text('Cannot delete transaction!'));
790
791   $main::lxdebug->leave_sub();
792 }
793
794 sub search {
795   $main::lxdebug->enter_sub();
796
797   $main::auth->assert('invoice_edit');
798
799   my $form     = $main::form;
800   my %myconfig = %main::myconfig;
801   my $locale   = $main::locale;
802   my $cgi      = $::request->{cgi};
803
804   # setup customer selection
805   $form->all_vc(\%myconfig, "customer", "AR");
806
807   $form->{title}    = $locale->text('AR Transactions');
808
809   # Auch in Rechnungsübersicht nach Kundentyp filtern - jan
810   $form->get_lists("projects"       => { "key" => "ALL_PROJECTS", "all" => 1 },
811                    "customers"      => "ALL_VC",
812                    "business_types" => "ALL_BUSINESS_TYPES");
813   $form->{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]);
814   $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all;
815   $form->{SHOW_BUSINESS_TYPES} = scalar @{ $form->{ALL_BUSINESS_TYPES} } > 0;
816
817   $form->{CT_CUSTOM_VARIABLES}                  = CVar->get_configs('module' => 'CT');
818   ($form->{CT_CUSTOM_VARIABLES_FILTER_CODE},
819    $form->{CT_CUSTOM_VARIABLES_INCLUSION_CODE}) = CVar->render_search_options('variables'      => $form->{CT_CUSTOM_VARIABLES},
820                                                                               'include_prefix' => 'l_',
821                                                                               'include_value'  => 'Y');
822
823   # constants and subs for template
824   $form->{vc_keys}   = sub { "$_[0]->{name}--$_[0]->{id}" };
825
826   $form->header;
827   print $form->parse_html_template('ar/search', { %myconfig });
828
829   $main::lxdebug->leave_sub();
830 }
831
832 sub create_subtotal_row {
833   $main::lxdebug->enter_sub();
834
835   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
836
837   my $form     = $main::form;
838   my %myconfig = %main::myconfig;
839
840   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
841
842   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
843
844   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
845
846   map { $totals->{$_} = 0 } @{ $subtotal_columns };
847
848   $main::lxdebug->leave_sub();
849
850   return $row;
851 }
852
853 sub ar_transactions {
854   $main::lxdebug->enter_sub();
855
856   $main::auth->assert('invoice_edit');
857
858   my $form     = $main::form;
859   my %myconfig = %main::myconfig;
860   my $locale   = $main::locale;
861
862   my ($callback, $href, @columns);
863
864   ($form->{customer}, $form->{customer_id}) = split(/--/, $form->{customer});
865
866   report_generator_set_default_sort('transdate', 1);
867
868   AR->ar_transactions(\%myconfig, \%$form);
869
870   $form->{title} = $locale->text('AR Transactions');
871
872   my $report = SL::ReportGenerator->new(\%myconfig, $form);
873
874   @columns =
875     qw(ids transdate id type invnumber ordnumber cusordnumber name netamount tax amount paid
876        datepaid due duedate transaction_description notes salesman employee shippingpoint shipvia
877        marge_total marge_percent globalprojectnumber customernumber country ustid taxzone
878        payment_terms charts customertype direct_debit dunning_description department);
879
880   my $ct_cvar_configs                 = CVar->get_configs('module' => 'CT');
881   my @ct_includeable_custom_variables = grep { $_->{includeable} } @{ $ct_cvar_configs };
882   my @ct_searchable_custom_variables  = grep { $_->{searchable} }  @{ $ct_cvar_configs };
883
884   my %column_defs_cvars = map { +"cvar_$_->{name}" => { 'text' => $_->{description} } } @ct_includeable_custom_variables;
885   push @columns, map { "cvar_$_->{name}" } @ct_includeable_custom_variables;
886
887   my @hidden_variables = map { "l_${_}" } @columns;
888   push @hidden_variables, "l_subtotal", qw(open closed customer invnumber ordnumber cusordnumber transaction_description notes project_id transdatefrom transdateto duedatefrom duedateto
889                                            employee_id salesman_id business_id parts_partnumber parts_description department_id);
890   push @hidden_variables, map { "cvar_$_->{name}" } @ct_searchable_custom_variables;
891
892   $href = build_std_url('action=ar_transactions', grep { $form->{$_} } @hidden_variables);
893
894   my %column_defs = (
895     'ids'                     => { raw_header_data => $::request->presenter->checkbox_tag("", id => "check_all", checkall => "[data-checkall=1]"), align => 'center' },
896     'transdate'               => { 'text' => $locale->text('Date'), },
897     'id'                      => { 'text' => $locale->text('ID'), },
898     'type'                    => { 'text' => $locale->text('Type'), },
899     'invnumber'               => { 'text' => $locale->text('Invoice'), },
900     'ordnumber'               => { 'text' => $locale->text('Order'), },
901     'cusordnumber'            => { 'text' => $locale->text('Customer Order Number'), },
902     'name'                    => { 'text' => $locale->text('Customer'), },
903     'netamount'               => { 'text' => $locale->text('Amount'), },
904     'tax'                     => { 'text' => $locale->text('Tax'), },
905     'amount'                  => { 'text' => $locale->text('Total'), },
906     'paid'                    => { 'text' => $locale->text('Paid'), },
907     'datepaid'                => { 'text' => $locale->text('Date Paid'), },
908     'due'                     => { 'text' => $locale->text('Amount Due'), },
909     'duedate'                 => { 'text' => $locale->text('Due Date'), },
910     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
911     'notes'                   => { 'text' => $locale->text('Notes'), },
912     'salesman'                => { 'text' => $locale->text('Salesperson'), },
913     'employee'                => { 'text' => $locale->text('Employee'), },
914     'shippingpoint'           => { 'text' => $locale->text('Shipping Point'), },
915     'shipvia'                 => { 'text' => $locale->text('Ship via'), },
916     'globalprojectnumber'     => { 'text' => $locale->text('Document Project Number'), },
917     'marge_total'             => { 'text' => $locale->text('Ertrag'), },
918     'marge_percent'           => { 'text' => $locale->text('Ertrag prozentual'), },
919     'customernumber'          => { 'text' => $locale->text('Customer Number'), },
920     'country'                 => { 'text' => $locale->text('Country'), },
921     'ustid'                   => { 'text' => $locale->text('USt-IdNr.'), },
922     'taxzone'                 => { 'text' => $locale->text('Steuersatz'), },
923     'payment_terms'           => { 'text' => $locale->text('Payment Terms'), },
924     'charts'                  => { 'text' => $locale->text('Buchungskonto'), },
925     'customertype'            => { 'text' => $locale->text('Customer type'), },
926     'direct_debit'            => { 'text' => $locale->text('direct debit'), },
927     'department'              => { 'text' => $locale->text('Department'), },
928     dunning_description       => { 'text' => $locale->text('Dunning level'), },
929     %column_defs_cvars,
930   );
931
932   foreach my $name (qw(id transdate duedate invnumber ordnumber cusordnumber name datepaid employee shippingpoint shipvia transaction_description direct_debit)) {
933     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
934     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
935   }
936
937   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);
938
939   $form->{"l_type"} = "Y";
940   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
941
942   $column_defs{ids}->{visible} = 'HTML';
943
944   $report->set_columns(%column_defs);
945   $report->set_column_order(@columns);
946
947   $report->set_export_options('ar_transactions', @hidden_variables, qw(sort sortdir));
948
949   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
950
951   CVar->add_custom_variables_to_report('module'         => 'CT',
952                                        'trans_id_field' => 'customer_id',
953                                        'configs'        => $ct_cvar_configs,
954                                        'column_defs'    => \%column_defs,
955                                        'data'           => $form->{AR});
956
957   my @options;
958   if ($form->{customer}) {
959     push @options, $locale->text('Customer') . " : $form->{customer}";
960   }
961   if ($form->{cp_name}) {
962     push @options, $locale->text('Contact Person') . " : $form->{cp_name}";
963   }
964
965   if ($form->{department_id}) {
966     my $department = SL::DB::Manager::Department->find_by( id => $form->{department_id} );
967     push @options, $locale->text('Department') . " : " . $department->description;
968   }
969   if ($form->{invnumber}) {
970     push @options, $locale->text('Invoice Number') . " : $form->{invnumber}";
971   }
972   if ($form->{ordnumber}) {
973     push @options, $locale->text('Order Number') . " : $form->{ordnumber}";
974   }
975   if ($form->{cusordnumber}) {
976     push @options, $locale->text('Customer Order Number') . " : $form->{cusordnumber}";
977   }
978   if ($form->{notes}) {
979     push @options, $locale->text('Notes') . " : $form->{notes}";
980   }
981   if ($form->{transaction_description}) {
982     push @options, $locale->text('Transaction description') . " : $form->{transaction_description}";
983   }
984   if ($form->{parts_partnumber}) {
985     push @options, $locale->text('Part Number') . " : $form->{parts_partnumber}";
986   }
987   if ($form->{parts_description}) {
988     push @options, $locale->text('Part Description') . " : $form->{parts_description}";
989   }
990   if ($form->{transdatefrom}) {
991     push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1);
992   }
993   if ($form->{transdateto}) {
994     push @options, $locale->text('Bis') . " " . $locale->date(\%myconfig, $form->{transdateto}, 1);
995   }
996   if ($form->{open}) {
997     push @options, $locale->text('Open');
998   }
999   if ($form->{employee_id}) {
1000     my $employee = SL::DB::Employee->new(id => $form->{employee_id})->load;
1001     push @options, $locale->text('Employee') . ' : ' . $employee->name;
1002   }
1003   if ($form->{salesman_id}) {
1004     my $salesman = SL::DB::Employee->new(id => $form->{salesman_id})->load;
1005     push @options, $locale->text('Salesman') . ' : ' . $salesman->name;
1006   }
1007   if ($form->{closed}) {
1008     push @options, $locale->text('Closed');
1009   }
1010
1011   $form->{ALL_PRINTERS} = SL::DB::Manager::Printer->get_all_sorted;
1012
1013   $report->set_options('top_info_text'        => join("\n", @options),
1014                        'raw_top_info_text'    => $form->parse_html_template('ar/ar_transactions_header'),
1015                        'raw_bottom_info_text' => $form->parse_html_template('ar/ar_transactions_bottom'),
1016                        'output_format'        => 'HTML',
1017                        'title'                => $form->{title},
1018                        'attachment_basename'  => $locale->text('invoice_list') . strftime('_%Y%m%d', localtime time),
1019     );
1020   $report->set_options_from_form();
1021   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
1022
1023   # add sort and escape callback, this one we use for the add sub
1024   $form->{callback} = $href .= "&sort=$form->{sort}";
1025
1026   # escape callback for href
1027   $callback = $form->escape($href);
1028
1029   my @subtotal_columns = qw(netamount amount paid due marge_total marge_percent);
1030
1031   my %totals    = map { $_ => 0 } @subtotal_columns;
1032   my %subtotals = map { $_ => 0 } @subtotal_columns;
1033
1034   my $idx = 0;
1035
1036   foreach my $ar (@{ $form->{AR} }) {
1037     $ar->{tax} = $ar->{amount} - $ar->{netamount};
1038     $ar->{due} = $ar->{amount} - $ar->{paid};
1039
1040     map { $subtotals{$_} += $ar->{$_};
1041           $totals{$_}    += $ar->{$_} } @subtotal_columns;
1042
1043     $subtotals{marge_percent} = $subtotals{netamount} ? ($subtotals{marge_total} * 100 / $subtotals{netamount}) : 0;
1044     $totals{marge_percent}    = $totals{netamount}    ? ($totals{marge_total}    * 100 / $totals{netamount}   ) : 0;
1045
1046     my $is_storno  = $ar->{storno} &&  $ar->{storno_id};
1047     my $has_storno = $ar->{storno} && !$ar->{storno_id};
1048
1049     $ar->{type} =
1050       $has_storno       ? $locale->text("Invoice with Storno (abbreviation)") :
1051       $is_storno        ? $locale->text("Storno (one letter abbreviation)") :
1052       $ar->{amount} < 0 ? $locale->text("Credit note (one letter abbreviation)") :
1053       $ar->{invoice}    ? $locale->text("Invoice (one letter abbreviation)") :
1054                           $locale->text("AR Transaction (abbreviation)");
1055
1056     map { $ar->{$_} = $form->format_amount(\%myconfig, $ar->{$_}, 2) } qw(netamount tax amount paid due marge_total marge_percent);
1057
1058     $ar->{direct_debit} = $ar->{direct_debit} ? $::locale->text('yes') : $::locale->text('no');
1059
1060     my $row = { };
1061
1062     foreach my $column (@columns) {
1063       $row->{$column} = {
1064         'data'  => $ar->{$column},
1065         'align' => $column_alignment{$column},
1066       };
1067     }
1068
1069     $row->{invnumber}->{link} = build_std_url("script=" . ($ar->{invoice} ? 'is.pl' : 'ar.pl'), 'action=edit')
1070       . "&id=" . E($ar->{id}) . "&callback=${callback}";
1071
1072     $row->{ids} = {
1073       raw_data =>  $::request->presenter->checkbox_tag("id[]", value => $ar->{id}, "data-checkall" => 1),
1074       valign   => 'center',
1075       align    => 'center',
1076     };
1077
1078     my $row_set = [ $row ];
1079
1080     if (($form->{l_subtotal} eq 'Y')
1081         && (($idx == (scalar @{ $form->{AR} } - 1))
1082             || ($ar->{ $form->{sort} } ne $form->{AR}->[$idx + 1]->{ $form->{sort} }))) {
1083       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
1084     }
1085
1086     $report->add_data($row_set);
1087
1088     $idx++;
1089   }
1090
1091   $report->add_separator();
1092   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
1093
1094   $report->generate_with_headers();
1095
1096   $main::lxdebug->leave_sub();
1097 }
1098
1099 sub storno {
1100   $main::lxdebug->enter_sub();
1101
1102   $main::auth->assert('ar_transactions');
1103
1104   my $form     = $main::form;
1105   my %myconfig = %main::myconfig;
1106   my $locale   = $main::locale;
1107
1108   # don't cancel cancelled transactions
1109   if (IS->has_storno(\%myconfig, $form, 'ar')) {
1110     $form->{title} = $locale->text("Cancel Accounts Receivables Transaction");
1111     $form->error($locale->text("Transaction has already been cancelled!"));
1112   }
1113
1114   AR->storno($form, \%myconfig, $form->{id});
1115
1116   # saving the history
1117   if(!exists $form->{addition} && $form->{id} ne "") {
1118     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
1119     $form->{addition}  = "STORNO";
1120     $form->{what_done} = "invoice";
1121     $form->save_history;
1122   }
1123   # /saving the history
1124
1125   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
1126
1127   $main::lxdebug->leave_sub();
1128 }
1129
1130 1;