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