Nutzung der Tabelle currencies
[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   $::request->layout->use_stylesheet('presenter/record/record_list.css');
362   $form->header();
363
364   print $form->parse_html_template("ir/form_header", \%TMPL_VAR);
365
366   $main::lxdebug->leave_sub();
367 }
368
369 sub form_footer {
370   $main::lxdebug->enter_sub();
371
372   my $form     = $main::form;
373   my %myconfig = %main::myconfig;
374   my $locale   = $main::locale;
375
376   $main::auth->assert('vendor_invoice_edit');
377
378   $form->{invtotal}    = $form->{invsubtotal};
379   $form->{oldinvtotal} = $form->{invtotal};
380
381   # note rows
382   $form->{rows} = max 2,
383     $form->numtextrows($form->{notes},    26, 8),
384     $form->numtextrows($form->{intnotes}, 35, 8);
385
386
387   # tax, total and subtotal calculations
388   my ($tax, $subtotal);
389   $form->{taxaccounts_array} = [ split / /, $form->{taxaccounts} ];
390
391   foreach my $item (@{ $form->{taxaccounts_array} }) {
392     if ($form->{"${item}_base"}) {
393       if ($form->{taxincluded}) {
394         $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
395                                                                                  / (1 + $form->{"${item}_rate"})), 2);
396         $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
397       } else {
398         $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
399         $form->{invtotal} += $form->{"${item}_total"};
400       }
401     }
402   }
403
404   # follow ups
405   if ($form->{id}) {
406     $form->{follow_ups}            = FU->follow_ups('trans_id' => $form->{id}) || [];
407     $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
408   }
409
410   # payments
411   my $totalpaid = 0;
412   $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
413   $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
414
415   # Standard Konto für Umlaufvermögen
416   my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
417
418   for my $i (1 .. $form->{paidaccounts}) {
419     $form->{"changeable_$i"} = 1;
420     if (SL::DB::Default->get->payments_changeable == 0) {
421       # never
422       $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
423     } elsif (SL::DB::Default->get->payments_changeable == 2) {
424       # on the same day
425       $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
426                                   ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
427     }
428
429     $form->{"selectAP_paid_$i"} = $form->{selectAP_paid};
430     if (!$form->{"AP_paid_$i"}) {
431       $form->{"selectAP_paid_$i"} =~ s/option>$accno_arap--(.*?)>/option selected>$accno_arap--$1>/;
432     } else {
433       $form->{"selectAP_paid_$i"} =~ s/option>\Q$form->{"AP_paid_$i"}\E/option selected>$form->{"AP_paid_$i"}/;
434     }
435
436     $totalpaid += $form->{"paid_$i"};
437   }
438
439   print $form->parse_html_template('ir/form_footer', {
440     is_type_credit_note => ($form->{type} eq "credit_note"),
441     totalpaid           => $totalpaid,
442     paid_missing        => $form->{invtotal} - $totalpaid,
443     show_storno         => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ap") && !$totalpaid,
444     show_delete         => ($::instance_conf->get_ir_changeable == 2)
445                              ? ($form->current_date(\%myconfig) eq $form->{gldate})
446                              : ($::instance_conf->get_ir_changeable == 1),
447   });
448 ##print $form->parse_html_template('ir/_payments'); # parser
449 ##print $form->parse_html_template('webdav/_list'); # parser
450
451   $main::lxdebug->leave_sub();
452 }
453
454 sub mark_as_paid {
455   $main::lxdebug->enter_sub();
456
457   my $form     = $main::form;
458   my %myconfig = %main::myconfig;
459
460   $main::auth->assert('vendor_invoice_edit');
461
462   &mark_as_paid_common(\%myconfig,"ap");
463
464   $main::lxdebug->leave_sub();
465 }
466
467 sub update {
468   $main::lxdebug->enter_sub();
469
470   my $form     = $main::form;
471   my %myconfig = %main::myconfig;
472
473   $main::auth->assert('vendor_invoice_edit');
474
475   &check_name('vendor');
476
477   if (!$form->{forex}) {        # read exchangerate from input field (not hidden)
478     $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate});
479   }
480   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'sell');
481   $form->{exchangerate} = $form->{forex} if $form->{forex};
482
483   for my $i (1 .. $form->{paidaccounts}) {
484     next unless $form->{"paid_$i"};
485     map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
486     $form->{"forex_$i"}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
487     $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
488   }
489
490   my $i            = $form->{rowcount};
491   my $exchangerate = ($form->{exchangerate} * 1) || 1;
492
493   if (   ($form->{"partnumber_$i"} eq "")
494       && ($form->{"description_$i"} eq "")
495       && ($form->{"partsgroup_$i"} eq "")) {
496     $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
497     &check_form;
498
499   } else {
500
501     IR->retrieve_item(\%myconfig, \%$form);
502
503     my $rows = scalar @{ $form->{item_list} };
504
505     if ($rows) {
506       $form->{"qty_$i"} = 1 unless $form->parse_amount(\%myconfig, $form->{"qty_$i"});
507
508       if ($rows > 1) {
509
510         select_item(mode => 'IR');
511         ::end_of_request();
512
513       } else {
514
515         # override sellprice if there is one entered
516         my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
517
518         # ergaenzung fuer bug 736 Lieferanten-Rabatt auch in Einkaufsrechnungen vorbelegen jb
519         $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{vendor_discount} * 100 );
520         map { $form->{item_list}[$i]{$_} =~ s/\"/&quot;/g } qw(partnumber description unit);
521         map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
522
523         $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
524
525         ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
526         my $dec_qty       = length $1;
527         my $decimalplaces = max 2, $dec_qty;
528
529         if ($sellprice) {
530           $form->{"sellprice_$i"} = $sellprice;
531         } else {
532           # if there is an exchange rate adjust sellprice
533           $form->{"sellprice_$i"} /= $exchangerate;
534         }
535
536         my $amount                   = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"} / 100);
537         $form->{creditremaining} -= $amount;
538         $form->{"sellprice_$i"}   = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
539         $form->{"qty_$i"}         = $form->format_amount(\%myconfig, $form->{"qty_$i"},       $dec_qty);
540       }
541
542       &display_form;
543
544     } else {
545
546       # ok, so this is a new part
547       # ask if it is a part or service item
548
549       if (   $form->{"partsgroup_$i"}
550           && ($form->{"partsnumber_$i"} eq "")
551           && ($form->{"description_$i"} eq "")) {
552         $form->{rowcount}--;
553         $form->{"discount_$i"} = "";
554         display_form();
555
556       } else {
557         $form->{"id_$i"}   = 0;
558         new_item();
559       }
560     }
561   }
562   $main::lxdebug->leave_sub();
563 }
564
565 sub storno {
566   $main::lxdebug->enter_sub();
567
568   my $form     = $main::form;
569   my %myconfig = %main::myconfig;
570   my $locale   = $main::locale;
571
572   $main::auth->assert('vendor_invoice_edit');
573
574   if ($form->{storno}) {
575     $form->error($locale->text('Cannot storno storno invoice!'));
576   }
577
578   if (IS->has_storno(\%myconfig, $form, "ap")) {
579     $form->error($locale->text("Invoice has already been storno'd!"));
580   }
581
582   $form->error($locale->text('Cannot post storno for a closed period!'))
583     if ( $form->date_closed($form->{invdate}, \%myconfig));
584
585   my $employee_id = $form->{employee_id};
586   invoice_links();
587   prepare_invoice();
588   relink_accounts();
589
590   # Payments must not be recorded for the new storno invoice.
591   $form->{paidaccounts} = 0;
592   map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
593
594   # saving the history
595   if(!exists $form->{addition} && $form->{id} ne "") {
596     $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
597     $form->{addition} = "CANCELED";
598     $form->save_history;
599   }
600   # /saving the history
601
602   $form->{storno_id} = $form->{id};
603   $form->{storno} = 1;
604   $form->{id} = "";
605   $form->{invnumber} = "Storno zu " . $form->{invnumber};
606   $form->{rowcount}++;
607   $form->{employee_id} = $employee_id;
608   post();
609   $main::lxdebug->leave_sub();
610
611 }
612
613 sub use_as_new {
614   $main::lxdebug->enter_sub();
615
616   my $form     = $main::form;
617   my %myconfig = %main::myconfig;
618
619   $main::auth->assert('vendor_invoice_edit');
620
621   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);
622   $form->{paidaccounts} = 1;
623   $form->{rowcount}--;
624   $form->{invdate} = $form->current_date(\%myconfig);
625   &display_form;
626
627   $main::lxdebug->leave_sub();
628 }
629
630 sub post_payment {
631   $main::lxdebug->enter_sub();
632
633   my $form     = $main::form;
634   my %myconfig = %main::myconfig;
635   my $locale   = $main::locale;
636
637   $main::auth->assert('vendor_invoice_edit');
638
639   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
640   for my $i (1 .. $form->{paidaccounts}) {
641     if ($form->{"paid_$i"}) {
642       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
643
644       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
645
646       $form->error($locale->text('Cannot post payment for a closed period!'))
647         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
648
649       if ($form->{currency} ne $form->{defaultcurrency}) {
650 #        $form->{"exchangerate_$i"} = $form->{exchangerate} if ($invdate == $datepaid); # invdate isn't set here
651         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
652       }
653     }
654   }
655
656   ($form->{AP})      = split /--/, $form->{AP};
657   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
658   if (IR->post_payment(\%myconfig, \%$form)){
659     if (!exists $form->{addition} && $form->{id} ne "") {
660       # saving the history
661       $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
662       $form->{addition} = "PAYMENT POSTED";
663       $form->{what_done} = $form->{currency} . qq| | . $form->{paid} . qq| | . $locale->text("POSTED");
664       $form->save_history;
665       # /saving the history
666     }
667
668     $form->redirect($locale->text('Payment posted!'));
669   }
670
671   $form->error($locale->text('Cannot post payment!'));
672
673   $main::lxdebug->leave_sub();
674 }
675
676 sub _max_datepaid {
677   my $form  =  $main::form;
678
679   my @dates = sort { $b->[1] cmp $a->[1] }
680               map  { [ $_, $main::locale->reformat_date(\%main::myconfig, $_, 'yyyy-mm-dd') ] }
681               grep { $_ }
682               map  { $form->{"datepaid_${_}"} }
683               (1..$form->{rowcount});
684
685   return @dates ? $dates[0]->[0] : undef;
686 }
687
688
689 sub post {
690   $main::lxdebug->enter_sub();
691
692   my $form     = $main::form;
693   my %myconfig = %main::myconfig;
694   my $locale   = $main::locale;
695
696   $main::auth->assert('vendor_invoice_edit');
697
698   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
699
700   $form->isblank("invdate",   $locale->text('Invoice Date missing!'));
701   $form->isblank("vendor",    $locale->text('Vendor missing!'));
702   $form->isblank("invnumber", $locale->text('Invnumber missing!'));
703
704   $form->{invnumber} =~ s/^\s*//g;
705   $form->{invnumber} =~ s/\s*$//g;
706
707   # if the vendor changed get new values
708   if (&check_name('vendor')) {
709     &update;
710     ::end_of_request();
711   }
712
713   if ($myconfig{mandatory_departments} && !$form->{department_id}) {
714     $form->{saved_message} = $::locale->text('You have to specify a department.');
715     update();
716     exit;
717   }
718
719   remove_emptied_rows();
720   &validate_items;
721
722   my $closedto     = $form->datetonum($form->{closedto}, \%myconfig);
723   my $invdate      = $form->datetonum($form->{invdate},  \%myconfig);
724   my $max_datepaid = _max_datepaid();
725
726   $form->error($locale->text('Cannot post invoice for a closed period!')) if $max_datepaid && $form->date_closed($max_datepaid, \%myconfig);
727
728   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
729     if ($form->{currency} ne $form->{defaultcurrency});
730
731   my $i;
732   for $i (1 .. $form->{paidaccounts}) {
733     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
734       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
735
736       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
737
738       $form->error($locale->text('Cannot post payment for a closed period!'))
739         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
740
741       if ($form->{currency} ne $form->{defaultcurrency}) {
742         $form->{"exchangerate_$i"} = $form->{exchangerate}
743           if ($invdate == $datepaid);
744         $form->isblank("exchangerate_$i",
745                        $locale->text('Exchangerate for payment missing!'));
746       }
747     }
748   }
749
750   ($form->{AP})      = split /--/, $form->{AP};
751   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
752   $form->{storno}  ||= 0;
753
754   $form->{id} = 0 if $form->{postasnew};
755
756
757   relink_accounts();
758   if (IR->post_invoice(\%myconfig, \%$form)){
759     # saving the history
760     if(!exists $form->{addition} && $form->{id} ne "") {
761       $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
762       $form->{addition} = "POSTED";
763       #$form->{what_done} = $locale->text("Rechnungsnummer") . qq| | . $form->{invnumber};
764       $form->save_history;
765     }
766     # /saving the history
767     remove_draft() if $form->{remove_draft};
768     $form->redirect(  $locale->text('Invoice')
769                   . " $form->{invnumber} "
770                   . $locale->text('posted!'));
771   }
772   $form->error($locale->text('Cannot post invoice!'));
773
774   $main::lxdebug->leave_sub();
775 }
776
777 sub delete {
778   $main::lxdebug->enter_sub();
779
780   my $form     = $main::form;
781   my $locale   = $main::locale;
782
783   $main::auth->assert('vendor_invoice_edit');
784
785   $form->header;
786   print qq|
787 <form method=post action=$form->{script}>
788 |;
789
790   # delete action variable
791   map { delete $form->{$_} } qw(action header);
792
793   foreach my $key (keys %$form) {
794     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
795     $form->{$key} =~ s/\"/&quot;/g;
796     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
797   }
798
799   print qq|
800 <h2 class=confirm>| . $locale->text('Confirm!') . qq|</h2>
801
802 <h4>|
803     . $locale->text('Are you sure you want to delete Invoice Number')
804     . qq| $form->{invnumber}</h4>
805 <p>
806 <input name=action class=submit type=submit value="|
807     . $locale->text('Yes') . qq|">
808 </form>
809 |;
810
811   $main::lxdebug->leave_sub();
812 }
813
814 sub yes {
815   $main::lxdebug->enter_sub();
816
817   my $form     = $main::form;
818   my %myconfig = %main::myconfig;
819   my $locale   = $main::locale;
820
821   $main::auth->assert('vendor_invoice_edit');
822
823   if (IR->delete_invoice(\%myconfig, \%$form)) {
824     # saving the history
825     if(!exists $form->{addition}) {
826       $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
827       $form->{addition} = "DELETED";
828       $form->save_history;
829     }
830     # /saving the history
831     $form->redirect($locale->text('Invoice deleted!'));
832   }
833   $form->error($locale->text('Cannot delete invoice!'));
834
835   $main::lxdebug->leave_sub();
836 }
837
838 sub get_duedate_vendor {
839   $::lxdebug->enter_sub;
840
841   my $result = IR->get_duedate(
842     vendor_id => $::form->{vendor_id},
843     invdate   => $::form->{invdate},
844     default   => $::form->{old_duedate},
845   );
846
847   print $::form->ajax_response_header, $result;
848   $::lxdebug->leave_sub;
849 }