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