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