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