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