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