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