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