Merge branch 'master' of github.com:kivitendo/kivitendo-erp
[kivitendo-erp.git] / bin / mozilla / ir.pl
1 #=====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 # SQL-Ledger, Accounting
9 # Copyright (c) 1998-2002
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 #
16 # This program is free software; you can redistribute it and/or modify
17 # it under the terms of the GNU General Public License as published by
18 # the Free Software Foundation; either version 2 of the License, or
19 # (at your option) any later version.
20 #
21 # This program is distributed in the hope that it will be useful,
22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 # GNU General Public License for more details.
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28 #======================================================================
29 #
30 # Inventory received module
31 #
32 #======================================================================
33
34 use SL::FU;
35 use SL::IR;
36 use SL::IS;
37 use SL::PE;
38 use SL::DB::Default;
39 use List::Util qw(max sum);
40
41 require "bin/mozilla/io.pl";
42 require "bin/mozilla/invoice_io.pl";
43 require "bin/mozilla/arap.pl";
44 require "bin/mozilla/common.pl";
45 require "bin/mozilla/drafts.pl";
46
47 use strict;
48
49 1;
50
51 # end of main
52
53 sub add {
54   $main::lxdebug->enter_sub();
55
56   my $form     = $main::form;
57   my $locale   = $main::locale;
58
59   $main::auth->assert('vendor_invoice_edit');
60
61   return $main::lxdebug->leave_sub() if (load_draft_maybe());
62
63   $form->{title} = $locale->text('Record Vendor Invoice');
64
65   &invoice_links;
66   &prepare_invoice;
67   &display_form;
68
69   $main::lxdebug->leave_sub();
70 }
71
72 sub edit {
73   $main::lxdebug->enter_sub();
74
75   my $form     = $main::form;
76   my $locale   = $main::locale;
77
78   $main::auth->assert('vendor_invoice_edit');
79
80   # show history button
81   $form->{javascript} = qq|<script type=text/javascript src=js/show_history.js></script>|;
82   #/show hhistory button
83
84   $form->{title} = $locale->text('Edit Vendor Invoice');
85
86   &invoice_links;
87   &prepare_invoice;
88   &display_form;
89
90   $main::lxdebug->leave_sub();
91 }
92
93 sub invoice_links {
94   $main::lxdebug->enter_sub();
95
96   my $form     = $main::form;
97   my %myconfig = %main::myconfig;
98
99   $main::auth->assert('vendor_invoice_edit');
100
101   $form->{vc} = 'vendor';
102
103   # create links
104   $form->{webdav}   = $::instance_conf->get_webdav;
105
106   $form->create_links("AP", \%myconfig, "vendor");
107
108   #quote all_vendor Bug 133
109   foreach my $ref (@{ $form->{all_vendor} }) {
110     $ref->{name} = $form->quote($ref->{name});
111   }
112
113   if ($form->{all_vendor}) {
114     unless ($form->{vendor_id}) {
115       $form->{vendor_id} = $form->{all_vendor}->[0]->{id};
116     }
117   }
118
119   my ($payment_id, $language_id, $taxzone_id, $currency);
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 = $form->get_all_currencies();
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   # show_exchangerate is also later needed in another template
320   $form->{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
321   $TMPL_VAR{currencies}        = NTI($cgi->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
322                                                       '-values' => \@values, '-labels' => \%labels,
323                                                       '-onchange' => "document.getElementById('update_button').click();"
324                                      )) if scalar @values;
325   push @custom_hiddens, "forex";
326   push @custom_hiddens, "exchangerate" if $form->{forex};
327
328   $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
329   $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
330
331   my $follow_up_vc         =  $form->{vendor};
332   $follow_up_vc            =~ s/--\d*\s*$//;
333   $TMPL_VAR{vendor_name} = $follow_up_vc;
334
335 # set option selected
336   foreach my $item (qw(AP)) {
337     $form->{"select$item"} =~ s/ selected//;
338     $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
339   }
340
341   $TMPL_VAR{is_type_credit_note} = $form->{type}   eq "credit_note";
342   $TMPL_VAR{is_format_html}      = $form->{format} eq 'html';
343   $TMPL_VAR{dateformat}          = $myconfig{dateformat};
344   $TMPL_VAR{numberformat}        = $myconfig{numberformat};
345
346   # hiddens
347   $TMPL_VAR{HIDDENS} = [qw(
348     id action type media format queued printed emailed title vc discount
349     title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
350     max_dunning_level dunning_amount
351     shiptoname shiptostreet shiptozipcode shiptocity shiptocountry  shiptocontact shiptophone shiptofax
352     shiptoemail shiptodepartment_1 shiptodepartment_2 message email subject cc bcc taxaccounts cursor_fokus
353     convert_from_do_ids convert_from_oe_ids
354   ), @custom_hiddens,
355   map { $_.'_rate', $_.'_description', $_.'_taxnumber' } split / /, $form->{taxaccounts}];
356
357   $form->header();
358
359   print $form->parse_html_template("ir/form_header", \%TMPL_VAR);
360
361   $main::lxdebug->leave_sub();
362 }
363
364 sub form_footer {
365   $main::lxdebug->enter_sub();
366
367   my $form     = $main::form;
368   my %myconfig = %main::myconfig;
369   my $locale   = $main::locale;
370
371   $main::auth->assert('vendor_invoice_edit');
372
373   $form->{invtotal}    = $form->{invsubtotal};
374   $form->{oldinvtotal} = $form->{invtotal};
375
376   # note rows
377   $form->{rows} = max 2,
378     $form->numtextrows($form->{notes},    26, 8),
379     $form->numtextrows($form->{intnotes}, 35, 8);
380
381
382   # tax, total and subtotal calculations
383   my ($tax, $subtotal);
384   $form->{taxaccounts_array} = [ split / /, $form->{taxaccounts} ];
385
386   foreach my $item (@{ $form->{taxaccounts_array} }) {
387     if ($form->{"${item}_base"}) {
388       if ($form->{taxincluded}) {
389         $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
390                                                                                  / (1 + $form->{"${item}_rate"})), 2);
391         $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
392       } else {
393         $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
394         $form->{invtotal} += $form->{"${item}_total"};
395       }
396     }
397   }
398
399   # follow ups
400   if ($form->{id}) {
401     $form->{follow_ups}            = FU->follow_ups('trans_id' => $form->{id}) || [];
402     $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
403   }
404
405   # payments
406   my $totalpaid = 0;
407   $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
408   $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
409
410   # Standard Konto für Umlaufvermögen
411   my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
412
413   for my $i (1 .. $form->{paidaccounts}) {
414     $form->{"changeable_$i"} = 1;
415     if (SL::DB::Default->get->payments_changeable == 0) {
416       # never
417       $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
418     } elsif (SL::DB::Default->get->payments_changeable == 2) {
419       # on the same day
420       $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
421                                   ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
422     }
423
424     $form->{"selectAP_paid_$i"} = $form->{selectAP_paid};
425     if (!$form->{"AP_paid_$i"}) {
426       $form->{"selectAP_paid_$i"} =~ s/option>$accno_arap--(.*?)>/option selected>$accno_arap--$1>/;
427     } else {
428       $form->{"selectAP_paid_$i"} =~ s/option>\Q$form->{"AP_paid_$i"}\E/option selected>$form->{"AP_paid_$i"}/;
429     }
430
431     $totalpaid += $form->{"paid_$i"};
432   }
433
434   print $form->parse_html_template('ir/form_footer', {
435     is_type_credit_note => ($form->{type} eq "credit_note"),
436     totalpaid           => $totalpaid,
437     paid_missing        => $form->{invtotal} - $totalpaid,
438     show_storno         => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ap") && !$totalpaid,
439     show_delete         => ($::instance_conf->get_ir_changeable == 2)
440                              ? ($form->current_date(\%myconfig) eq $form->{gldate})
441                              : ($::instance_conf->get_ir_changeable == 1),
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   $form->error($locale->text('Cannot post storno for a closed period!'))
578     if ( $form->date_closed($form->{invdate}, \%myconfig));
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_new {
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 transaction above the maximum future booking date!'))
722     if ($form->date_max_future($invdate, \%myconfig));
723   $form->error($locale->text('Cannot post invoice for a closed period!')) if $max_datepaid && $form->date_closed($max_datepaid, \%myconfig);
724
725   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
726     if ($form->{currency} ne $form->{defaultcurrency});
727
728   my $i;
729   for $i (1 .. $form->{paidaccounts}) {
730     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
731       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
732
733       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
734
735       $form->error($locale->text('Cannot post payment for a closed period!'))
736         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
737
738       if ($form->{currency} ne $form->{defaultcurrency}) {
739         $form->{"exchangerate_$i"} = $form->{exchangerate}
740           if ($invdate == $datepaid);
741         $form->isblank("exchangerate_$i",
742                        $locale->text('Exchangerate for payment missing!'));
743       }
744     }
745   }
746
747   ($form->{AP})      = split /--/, $form->{AP};
748   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
749   $form->{storno}  ||= 0;
750
751   $form->{id} = 0 if $form->{postasnew};
752
753
754   relink_accounts();
755   if (IR->post_invoice(\%myconfig, \%$form)){
756     # saving the history
757     if(!exists $form->{addition} && $form->{id} ne "") {
758       $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
759       $form->{addition} = "POSTED";
760       #$form->{what_done} = $locale->text("Rechnungsnummer") . qq| | . $form->{invnumber};
761       $form->save_history;
762     }
763     # /saving the history
764     remove_draft() if $form->{remove_draft};
765     $form->redirect(  $locale->text('Invoice')
766                   . " $form->{invnumber} "
767                   . $locale->text('posted!'));
768   }
769   $form->error($locale->text('Cannot post invoice!'));
770
771   $main::lxdebug->leave_sub();
772 }
773
774 sub delete {
775   $main::lxdebug->enter_sub();
776
777   my $form     = $main::form;
778   my $locale   = $main::locale;
779
780   $main::auth->assert('vendor_invoice_edit');
781
782   $form->header;
783   print qq|
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 }