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