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