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