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