Manuelle ergänzungen zum vorherigen commit
[kivitendo-erp.git] / bin / mozilla / ir.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) 1998-2002
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., 675 Mass Ave, Cambridge, MA 02139, USA.
28 #======================================================================
29 #
30 # Inventory received module
31 #
32 #======================================================================
33
34 use SL::FU;
35 use SL::IR;
36 use SL::IS;
37 use SL::PE;
38 use List::Util qw(max sum);
39
40 require "bin/mozilla/io.pl";
41 require "bin/mozilla/invoice_io.pl";
42 require "bin/mozilla/arap.pl";
43 require "bin/mozilla/common.pl";
44 require "bin/mozilla/drafts.pl";
45
46 use strict;
47
48 1;
49
50 # end of main
51
52 sub add {
53   $main::lxdebug->enter_sub();
54
55   my $form     = $main::form;
56   my $locale   = $main::locale;
57
58   $main::auth->assert('vendor_invoice_edit');
59
60   return $main::lxdebug->leave_sub() if (load_draft_maybe());
61
62   $form->{title} = $locale->text('Record Vendor Invoice');
63
64   &invoice_links;
65   &prepare_invoice;
66   &display_form;
67
68   $main::lxdebug->leave_sub();
69 }
70
71 sub edit {
72   $main::lxdebug->enter_sub();
73
74   my $form     = $main::form;
75   my $locale   = $main::locale;
76
77   $main::auth->assert('vendor_invoice_edit');
78
79   # show history button
80   $form->{javascript} = qq|<script type=text/javascript src=js/show_history.js></script>|;
81   #/show hhistory button
82
83   $form->{title} = $locale->text('Edit Vendor Invoice');
84
85   &invoice_links;
86   &prepare_invoice;
87   &display_form;
88
89   $main::lxdebug->leave_sub();
90 }
91
92 sub invoice_links {
93   $main::lxdebug->enter_sub();
94
95   my $form     = $main::form;
96   my %myconfig = %main::myconfig;
97
98   $main::auth->assert('vendor_invoice_edit');
99
100   $form->{vc} = 'vendor';
101
102   # create links
103   $form->{webdav}   = $::lx_office_conf{features}->{webdav};
104   $form->{jsscript} = 1;
105
106   $form->create_links("AP", \%myconfig, "vendor");
107
108   #quote all_vendor Bug 133
109   foreach my $ref (@{ $form->{all_vendor} }) {
110     $ref->{name} = $form->quote($ref->{name});
111   }
112
113   if ($form->{all_vendor}) {
114     unless ($form->{vendor_id}) {
115       $form->{vendor_id} = $form->{all_vendor}->[0]->{id};
116     }
117   }
118
119   my ($payment_id, $language_id, $taxzone_id, $currency);
120   if ($form->{payment_id}) {
121     $payment_id = $form->{payment_id};
122   }
123   if ($form->{language_id}) {
124     $language_id = $form->{language_id};
125   }
126   if ($form->{taxzone_id}) {
127     $taxzone_id = $form->{taxzone_id};
128   }
129   if ($form->{currency}) {
130     $currency = $form->{currency};
131   }
132
133   my $cp_id = $form->{cp_id};
134   IR->get_vendor(\%myconfig, \%$form);
135   IR->retrieve_invoice(\%myconfig, \%$form);
136   $form->{cp_id} = $cp_id;
137
138   if ($payment_id) {
139     $form->{payment_id} = $payment_id;
140   }
141   if ($language_id) {
142     $form->{language_id} = $language_id;
143   }
144   if ($taxzone_id) {
145     $form->{taxzone_id} = $taxzone_id;
146   }
147   if ($currency) {
148     $form->{currency} = $currency;
149   }
150
151   my @curr = split(/:/, $form->{currencies}); #seems to be missing
152   map { $form->{selectcurrency} .= "<option>$_\n" } @curr;
153
154   $form->{oldvendor} = "$form->{vendor}--$form->{vendor_id}";
155
156   # build vendor/customer drop down comatibility... don't ask
157   if (@{ $form->{"all_vendor"} || [] }) {
158     $form->{"selectvendor"} = 1;
159     $form->{vendor}         = qq|$form->{vendor}--$form->{vendor_id}|;
160   }
161
162   # departments
163   if ($form->{all_departments}) {
164     $form->{selectdepartment} = "<option>\n";
165     $form->{department}       = "$form->{department}--$form->{department_id}";
166
167     map {
168       $form->{selectdepartment} .=
169         "<option>$_->{description}--$_->{id}\n"
170     } (@{ $form->{all_departments} || [] });
171   }
172
173   # forex
174   $form->{forex} = $form->{exchangerate};
175   my $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
176
177   foreach my $key (keys %{ $form->{AP_links} }) {
178
179     foreach my $ref (@{ $form->{AP_links}{$key} }) {
180       $form->{"select$key"} .= "<option>$ref->{accno}--$ref->{description}</option>";
181     }
182
183     next unless $form->{acc_trans}{$key};
184
185     if ($key eq "AP_paid") {
186       for my $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
187         $form->{"AP_paid_$i"} =
188           "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
189
190         $form->{"acc_trans_id_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
191         # reverse paid
192         $form->{"paid_$i"}     = $form->{acc_trans}{$key}->[$i - 1]->{amount};
193         $form->{"datepaid_$i"} =
194           $form->{acc_trans}{$key}->[$i - 1]->{transdate};
195         $form->{"gldate_$i"}   = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
196         $form->{"forex_$i"} = $form->{"exchangerate_$i"} =
197           $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
198         $form->{"source_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{source};
199         $form->{"memo_$i"}   = $form->{acc_trans}{$key}->[$i - 1]->{memo};
200
201         $form->{paidaccounts} = $i;
202       }
203     } else {
204       $form->{$key} =
205         "$form->{acc_trans}{$key}->[0]->{accno}--$form->{acc_trans}{$key}->[0]->{description}";
206     }
207
208   }
209
210   $form->{paidaccounts} = 1 unless (exists $form->{paidaccounts});
211
212   $form->{AP} = $form->{AP_1} unless $form->{id};
213
214   $form->{locked} =
215     ($form->datetonum($form->{invdate}, \%myconfig) <=
216      $form->datetonum($form->{closedto}, \%myconfig));
217
218   $main::lxdebug->leave_sub();
219 }
220
221 sub prepare_invoice {
222   $main::lxdebug->enter_sub();
223
224   my $form     = $main::form;
225   my %myconfig = %main::myconfig;
226
227   $main::auth->assert('vendor_invoice_edit');
228
229   if ($form->{id}) {
230
231     map { $form->{$_} =~ s/\"/&quot;/g } qw(invnumber ordnumber quonumber);
232
233     my $i = 0;
234     foreach my $ref (@{ $form->{invoice_details} }) {
235       $i++;
236       map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
237       # ĂĽbernommen aus is.pl Fix fĂĽr Bug 1642. Nebenwirkungen? jb 12.5.2011
238       # getestet: Lieferantenauftrag -> Rechnung i.O.
239       #           Lieferantenauftrag -> Lieferschein -> Rechnung i.O.
240       # Werte: 20% (Lieferantenrabatt), 12,4% individuell und 0,4 individuell s.a.
241       # Screenshot zu Bug 1642
242       $form->{"discount_$i"}   = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100);
243
244       my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
245       $dec           = length $dec;
246       my $decimalplaces = ($dec > 2) ? $dec : 2;
247
248       $form->{"sellprice_$i"} =
249         $form->format_amount(\%myconfig, $form->{"sellprice_$i"},
250                              $decimalplaces);
251
252       (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
253       $dec_qty = length $dec_qty;
254
255       $form->{"qty_$i"} =
256         $form->format_amount(\%myconfig, ($form->{"qty_$i"} * -1), $dec_qty);
257
258       $form->{rowcount} = $i;
259     }
260   }
261
262   $main::lxdebug->leave_sub();
263 }
264
265 sub form_header {
266   $main::lxdebug->enter_sub();
267
268   my $form     = $main::form;
269   my %myconfig = %main::myconfig;
270   my $locale   = $main::locale;
271   my $cgi      = $::request->{cgi};
272
273   $main::auth->assert('vendor_invoice_edit');
274
275   my %TMPL_VAR = ();
276   my @custom_hiddens;
277
278   $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
279   $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
280
281   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
282
283   my @old_project_ids = ($form->{"globalproject_id"});
284   map { push @old_project_ids, $form->{"project_id_$_"} if $form->{"project_id_$_"}; } 1..$form->{"rowcount"};
285
286   $form->get_lists("projects"      => { "key"    => "ALL_PROJECTS",
287                                         "all"    => 0,
288                                         "old_id" => \@old_project_ids },
289                    "taxzones"      => "ALL_TAXZONES",
290                    "currencies"    => "ALL_CURRENCIES",
291                    "vendors"       => "ALL_VENDORS",
292                    "departments"   => "all_departments",
293                    "price_factors" => "ALL_PRICE_FACTORS");
294
295   $TMPL_VAR{ALL_EMPLOYEES}         = SL::DB::Manager::Employee->get_all(query => [ or => [ id => $::form->{employee_id},  deleted => 0 ] ]);
296   $TMPL_VAR{ALL_CONTACTS}          = SL::DB::Manager::Contact->get_all(query => [
297     or => [
298       cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
299       and      => [
300         cp_cv_id => undef,
301         cp_id    => $::form->{cp_id} * 1
302       ]
303     ]
304   ]);
305   $TMPL_VAR{department_labels}     = sub { "$_[0]->{description}--$_[0]->{id}" };
306
307   # customer
308   $TMPL_VAR{vc_keys} = sub { "$_[0]->{name}--$_[0]->{id}" };
309   $TMPL_VAR{vclimit} = $myconfig{vclimit};
310   $TMPL_VAR{vc_select} = "customer_or_vendor_selection_window('vendor', '', 1, 0)";
311   push @custom_hiddens, "vendor_id";
312   push @custom_hiddens, "oldvendor";
313   push @custom_hiddens, "selectvendor";
314
315   # currencies and exchangerate
316   my @values = map { $_       } @{ $form->{ALL_CURRENCIES} };
317   my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
318   $form->{currency}            = $form->{defaultcurrency} unless $form->{currency};
319   # show_exchangerate is also later needed in another template
320   $form->{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
321   $TMPL_VAR{currencies}        = NTI($cgi->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
322                                                       '-values' => \@values, '-labels' => \%labels,
323                                                       '-onchange' => "document.getElementById('update_button').click();"
324                                      )) if scalar @values;
325   push @custom_hiddens, "forex";
326   push @custom_hiddens, "exchangerate" if $form->{forex};
327
328   $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
329   $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
330
331   $form->{fokus} = "invoice.vendor";
332
333   my $follow_up_vc         =  $form->{vendor};
334   $follow_up_vc            =~ s/--\d*\s*$//;
335   $TMPL_VAR{vendor_name} = $follow_up_vc;
336
337 # set option selected
338   foreach my $item (qw(AP)) {
339     $form->{"select$item"} =~ s/ selected//;
340     $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
341   }
342
343   $TMPL_VAR{is_type_credit_note} = $form->{type}   eq "credit_note";
344   $TMPL_VAR{is_format_html}      = $form->{format} eq 'html';
345   $TMPL_VAR{dateformat}          = $myconfig{dateformat};
346   $TMPL_VAR{numberformat}        = $myconfig{numberformat};
347
348   # hiddens
349   $TMPL_VAR{HIDDENS} = [qw(
350     id action type media format queued printed emailed title vc discount
351     title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
352     max_dunning_level dunning_amount
353     shiptoname shiptostreet shiptozipcode shiptocity shiptocountry  shiptocontact shiptophone shiptofax
354     shiptoemail shiptodepartment_1 shiptodepartment_2 message email subject cc bcc taxaccounts cursor_fokus
355     convert_from_do_ids convert_from_oe_ids
356   ), @custom_hiddens,
357   map { $_.'_rate', $_.'_description', $_.'_taxnumber' } split / /, $form->{taxaccounts}];
358
359   $form->{jsscript} = 1;
360   $form->header();
361
362   print $form->parse_html_template("ir/form_header", \%TMPL_VAR);
363
364   $main::lxdebug->leave_sub();
365 }
366
367 sub form_footer {
368   $main::lxdebug->enter_sub();
369
370   my $form     = $main::form;
371   my %myconfig = %main::myconfig;
372   my $locale   = $main::locale;
373
374   $main::auth->assert('vendor_invoice_edit');
375
376   $form->{invtotal}    = $form->{invsubtotal};
377   $form->{oldinvtotal} = $form->{invtotal};
378
379   # note rows
380   $form->{rows} = max 2,
381     $form->numtextrows($form->{notes},    26, 8),
382     $form->numtextrows($form->{intnotes}, 35, 8);
383
384
385   # tax, total and subtotal calculations
386   my ($tax, $subtotal);
387   $form->{taxaccounts_array} = [ split / /, $form->{taxaccounts} ];
388
389   foreach my $item (@{ $form->{taxaccounts_array} }) {
390     if ($form->{"${item}_base"}) {
391       if ($form->{taxincluded}) {
392         $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
393                                                                                  / (1 + $form->{"${item}_rate"})), 2);
394         $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
395       } else {
396         $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
397         $form->{invtotal} += $form->{"${item}_total"};
398       }
399     }
400   }
401
402   # follow ups
403   if ($form->{id}) {
404     $form->{follow_ups}            = FU->follow_ups('trans_id' => $form->{id}) || [];
405     $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
406   }
407
408   # payments
409   my $totalpaid = 0;
410   $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
411   $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
412
413   # Standard Konto fĂĽr Umlaufvermögen
414   my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
415
416   for my $i (1 .. $form->{paidaccounts}) {
417     $form->{"changeable_$i"} = 1;
418     if ($::lx_office_conf{features}->{payments_changeable} == 0) {
419       # never
420       $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
421     } elsif ($::lx_office_conf{features}->{payments_changeable} == 2) {
422       # on the same day
423       $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
424                                   ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
425     }
426
427     $form->{"selectAP_paid_$i"} = $form->{selectAP_paid};
428     if (!$form->{"AP_paid_$i"}) {
429       $form->{"selectAP_paid_$i"} =~ s/option>$accno_arap--(.*?)>/option selected>$accno_arap--$1>/;
430     } else {
431       $form->{"selectAP_paid_$i"} =~ s/option>\Q$form->{"AP_paid_$i"}\E/option selected>$form->{"AP_paid_$i"}/;
432     }
433
434     $totalpaid += $form->{"paid_$i"};
435   }
436
437   print $form->parse_html_template('ir/form_footer', {
438     is_type_credit_note => ($form->{type} eq "credit_note"),
439     totalpaid           => $totalpaid,
440     paid_missing        => $form->{invtotal} - $totalpaid,
441     show_storno         => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ap") && !$totalpaid,
442     show_delete         => ($form->current_date(\%myconfig) eq $form->{gldate}),
443   });
444 ##print $form->parse_html_template('ir/_payments'); # parser
445 ##print $form->parse_html_template('webdav/_list'); # parser
446
447   $main::lxdebug->leave_sub();
448 }
449
450 sub mark_as_paid {
451   $main::lxdebug->enter_sub();
452
453   my $form     = $main::form;
454   my %myconfig = %main::myconfig;
455
456   $main::auth->assert('vendor_invoice_edit');
457
458   &mark_as_paid_common(\%myconfig,"ap");
459
460   $main::lxdebug->leave_sub();
461 }
462
463 sub update {
464   $main::lxdebug->enter_sub();
465
466   my $form     = $main::form;
467   my %myconfig = %main::myconfig;
468
469   $main::auth->assert('vendor_invoice_edit');
470
471   &check_name('vendor');
472
473   if (!$form->{forex}) {        # read exchangerate from input field (not hidden)
474     $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate});
475   }
476   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'sell');
477   $form->{exchangerate} = $form->{forex} if $form->{forex};
478
479   for my $i (1 .. $form->{paidaccounts}) {
480     next unless $form->{"paid_$i"};
481     map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
482     $form->{"forex_$i"}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
483     $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
484   }
485
486   my $i            = $form->{rowcount};
487   my $exchangerate = ($form->{exchangerate} * 1) || 1;
488
489   if (   ($form->{"partnumber_$i"} eq "")
490       && ($form->{"description_$i"} eq "")
491       && ($form->{"partsgroup_$i"} eq "")) {
492     $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
493     &check_form;
494
495   } else {
496
497     IR->retrieve_item(\%myconfig, \%$form);
498
499     my $rows = scalar @{ $form->{item_list} };
500
501     if ($rows) {
502       $form->{"qty_$i"} = 1 unless $form->parse_amount(\%myconfig, $form->{"qty_$i"});
503
504       if ($rows > 1) {
505
506         select_item(mode => 'IR');
507         ::end_of_request();
508
509       } else {
510
511         # override sellprice if there is one entered
512         my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
513
514         # ergaenzung fuer bug 736 Lieferanten-Rabatt auch in Einkaufsrechnungen vorbelegen jb
515         $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{vendor_discount} * 100 );
516         map { $form->{item_list}[$i]{$_} =~ s/\"/&quot;/g } qw(partnumber description unit);
517         map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
518
519         $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
520
521         ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
522         my $dec_qty       = length $1;
523         my $decimalplaces = max 2, $dec_qty;
524
525         if ($sellprice) {
526           $form->{"sellprice_$i"} = $sellprice;
527         } else {
528           # if there is an exchange rate adjust sellprice
529           $form->{"sellprice_$i"} /= $exchangerate;
530         }
531
532         my $amount                   = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"} / 100);
533         $form->{creditremaining} -= $amount;
534         $form->{"sellprice_$i"}   = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
535         $form->{"qty_$i"}         = $form->format_amount(\%myconfig, $form->{"qty_$i"},       $dec_qty);
536       }
537
538       &display_form;
539
540     } else {
541
542       # ok, so this is a new part
543       # ask if it is a part or service item
544
545       if (   $form->{"partsgroup_$i"}
546           && ($form->{"partsnumber_$i"} eq "")
547           && ($form->{"description_$i"} eq "")) {
548         $form->{rowcount}--;
549         $form->{"discount_$i"} = "";
550         display_form();
551
552       } else {
553         $form->{"id_$i"}   = 0;
554         new_item();
555       }
556     }
557   }
558   $main::lxdebug->leave_sub();
559 }
560
561 sub storno {
562   $main::lxdebug->enter_sub();
563
564   my $form     = $main::form;
565   my %myconfig = %main::myconfig;
566   my $locale   = $main::locale;
567
568   $main::auth->assert('vendor_invoice_edit');
569
570   if ($form->{storno}) {
571     $form->error($locale->text('Cannot storno storno invoice!'));
572   }
573
574   if (IS->has_storno(\%myconfig, $form, "ap")) {
575     $form->error($locale->text("Invoice has already been storno'd!"));
576   }
577
578   $form->error($locale->text('Cannot post storno for a closed period!'))
579     if ( $form->date_closed($form->{invdate}, \%myconfig));
580
581   my $employee_id = $form->{employee_id};
582   invoice_links();
583   prepare_invoice();
584   relink_accounts();
585
586   # Payments must not be recorded for the new storno invoice.
587   $form->{paidaccounts} = 0;
588   map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
589
590   # saving the history
591   if(!exists $form->{addition} && $form->{id} ne "") {
592     $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
593     $form->{addition} = "CANCELED";
594     $form->save_history;
595   }
596   # /saving the history
597
598   $form->{storno_id} = $form->{id};
599   $form->{storno} = 1;
600   $form->{id} = "";
601   $form->{invnumber} = "Storno zu " . $form->{invnumber};
602   $form->{rowcount}++;
603   $form->{employee_id} = $employee_id;
604   post();
605   $main::lxdebug->leave_sub();
606
607 }
608
609 sub use_as_template {
610   $main::lxdebug->enter_sub();
611
612   my $form     = $main::form;
613   my %myconfig = %main::myconfig;
614
615   $main::auth->assert('vendor_invoice_edit');
616
617   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);
618   $form->{paidaccounts} = 1;
619   $form->{rowcount}--;
620   $form->{invdate} = $form->current_date(\%myconfig);
621   &display_form;
622
623   $main::lxdebug->leave_sub();
624 }
625
626 sub post_payment {
627   $main::lxdebug->enter_sub();
628
629   my $form     = $main::form;
630   my %myconfig = %main::myconfig;
631   my $locale   = $main::locale;
632
633   $main::auth->assert('vendor_invoice_edit');
634
635   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
636   for my $i (1 .. $form->{paidaccounts}) {
637     if ($form->{"paid_$i"}) {
638       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
639
640       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
641
642       $form->error($locale->text('Cannot post payment for a closed period!'))
643         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
644
645       if ($form->{currency} ne $form->{defaultcurrency}) {
646 #        $form->{"exchangerate_$i"} = $form->{exchangerate} if ($invdate == $datepaid); # invdate isn't set here
647         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
648       }
649     }
650   }
651
652   ($form->{AP})      = split /--/, $form->{AP};
653   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
654   if (IR->post_payment(\%myconfig, \%$form)){
655     if (!exists $form->{addition} && $form->{id} ne "") {
656       # saving the history
657       $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
658       $form->{addition} = "PAYMENT POSTED";
659       $form->{what_done} = $form->{currency} . qq| | . $form->{paid} . qq| | . $locale->text("POSTED");
660       $form->save_history;
661       # /saving the history
662     }
663
664     $form->redirect($locale->text('Payment posted!'));
665   }
666
667   $form->error($locale->text('Cannot post payment!'));
668
669   $main::lxdebug->leave_sub();
670 }
671
672 sub _max_datepaid {
673   my $form  =  $main::form;
674
675   my @dates = sort { $b->[1] cmp $a->[1] }
676               map  { [ $_, $main::locale->reformat_date(\%main::myconfig, $_, 'yyyy-mm-dd') ] }
677               grep { $_ }
678               map  { $form->{"datepaid_${_}"} }
679               (1..$form->{rowcount});
680
681   return @dates ? $dates[0]->[0] : undef;
682 }
683
684
685 sub post {
686   $main::lxdebug->enter_sub();
687
688   my $form     = $main::form;
689   my %myconfig = %main::myconfig;
690   my $locale   = $main::locale;
691
692   $main::auth->assert('vendor_invoice_edit');
693
694   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
695
696   $form->isblank("invdate",   $locale->text('Invoice Date missing!'));
697   $form->isblank("vendor",    $locale->text('Vendor missing!'));
698   $form->isblank("invnumber", $locale->text('Invnumber missing!'));
699
700   $form->{invnumber} =~ s/^\s*//g;
701   $form->{invnumber} =~ s/\s*$//g;
702
703   # if the vendor changed get new values
704   if (&check_name('vendor')) {
705     &update;
706     ::end_of_request();
707   }
708
709   if ($myconfig{mandatory_departments} && !$form->{department_id}) {
710     $form->{saved_message} = $::locale->text('You have to specify a department.');
711     update();
712     exit;
713   }
714
715   remove_emptied_rows();
716   &validate_items;
717
718   my $closedto     = $form->datetonum($form->{closedto}, \%myconfig);
719   my $invdate      = $form->datetonum($form->{invdate},  \%myconfig);
720   my $max_datepaid = _max_datepaid();
721
722   $form->error($locale->text('Cannot post invoice for a closed period!')) if $max_datepaid && $form->date_closed($max_datepaid, \%myconfig);
723
724   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
725     if ($form->{currency} ne $form->{defaultcurrency});
726
727   my $i;
728   for $i (1 .. $form->{paidaccounts}) {
729     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
730       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
731
732       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
733
734       $form->error($locale->text('Cannot post payment for a closed period!'))
735         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
736
737       if ($form->{currency} ne $form->{defaultcurrency}) {
738         $form->{"exchangerate_$i"} = $form->{exchangerate}
739           if ($invdate == $datepaid);
740         $form->isblank("exchangerate_$i",
741                        $locale->text('Exchangerate for payment missing!'));
742       }
743     }
744   }
745
746   ($form->{AP})      = split /--/, $form->{AP};
747   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
748   $form->{storno}  ||= 0;
749
750   $form->{id} = 0 if $form->{postasnew};
751
752
753   relink_accounts();
754   if (IR->post_invoice(\%myconfig, \%$form)){
755     # saving the history
756     if(!exists $form->{addition} && $form->{id} ne "") {
757       $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
758       $form->{addition} = "POSTED";
759       #$form->{what_done} = $locale->text("Rechnungsnummer") . qq| | . $form->{invnumber};
760       $form->save_history;
761     }
762     # /saving the history
763     remove_draft() if $form->{remove_draft};
764     $form->redirect(  $locale->text('Invoice')
765                   . " $form->{invnumber} "
766                   . $locale->text('posted!'));
767   }
768   $form->error($locale->text('Cannot post invoice!'));
769
770   $main::lxdebug->leave_sub();
771 }
772
773 sub delete {
774   $main::lxdebug->enter_sub();
775
776   my $form     = $main::form;
777   my $locale   = $main::locale;
778
779   $main::auth->assert('vendor_invoice_edit');
780
781   $form->header;
782   print qq|
783 <form method=post action=$form->{script}>
784 |;
785
786   # delete action variable
787   map { delete $form->{$_} } qw(action header);
788
789   foreach my $key (keys %$form) {
790     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
791     $form->{$key} =~ s/\"/&quot;/g;
792     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
793   }
794
795   print qq|
796 <h2 class=confirm>| . $locale->text('Confirm!') . qq|</h2>
797
798 <h4>|
799     . $locale->text('Are you sure you want to delete Invoice Number')
800     . qq| $form->{invnumber}</h4>
801 <p>
802 <input name=action class=submit type=submit value="|
803     . $locale->text('Yes') . qq|">
804 </form>
805 |;
806
807   $main::lxdebug->leave_sub();
808 }
809
810 sub yes {
811   $main::lxdebug->enter_sub();
812
813   my $form     = $main::form;
814   my %myconfig = %main::myconfig;
815   my $locale   = $main::locale;
816
817   $main::auth->assert('vendor_invoice_edit');
818
819   if (IR->delete_invoice(\%myconfig, \%$form)) {
820     # saving the history
821     if(!exists $form->{addition}) {
822       $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
823       $form->{addition} = "DELETED";
824       $form->save_history;
825     }
826     # /saving the history
827     $form->redirect($locale->text('Invoice deleted!'));
828   }
829   $form->error($locale->text('Cannot delete invoice!'));
830
831   $main::lxdebug->leave_sub();
832 }
833
834 sub get_duedate_vendor {
835   $::lxdebug->enter_sub;
836
837   my $result = IR->get_duedate(
838     vendor_id => $::form->{vendor_id},
839     invdate   => $::form->{invdate},
840     default   => $::form->{old_duedate},
841   );
842
843   print $::form->ajax_response_header, $result;
844   $::lxdebug->leave_sub;
845 }