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