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