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