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