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