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