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