Alle Rechnungen: »als bezahlt markieren« auf neue Funktionen in SL::DB::(Purchase...
[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., 51 Franklin Street, Fifth Floor, Boston,
28 # MA 02110-1335, USA.
29 #======================================================================
30 #
31 # Inventory received module
32 #
33 #======================================================================
34
35 use SL::FU;
36 use SL::IR;
37 use SL::IS;
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
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   $form->{show_details} = $::myconfig{show_form_details};
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   $form->{show_details} = $::myconfig{show_form_details};
85
86   # show history button
87   $form->{javascript} = qq|<script type=text/javascript src=js/show_history.js></script>|;
88   #/show hhistory button
89
90   $form->{title} = $locale->text('Edit Vendor Invoice');
91
92   &invoice_links;
93   &prepare_invoice;
94   &display_form;
95
96   $main::lxdebug->leave_sub();
97 }
98
99 sub invoice_links {
100   $main::lxdebug->enter_sub();
101
102   my $form     = $main::form;
103   my %myconfig = %main::myconfig;
104
105   $main::auth->assert('vendor_invoice_edit');
106
107   $form->{vc} = 'vendor';
108
109   # create links
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   $TMPL_VAR{invoice_obj} = SL::DB::PurchaseInvoice->new(id => $form->{id})->load if $form->{id};
262   $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
263   $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
264
265   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
266
267   my @old_project_ids = ($form->{"globalproject_id"});
268   map { push @old_project_ids, $form->{"project_id_$_"} if $form->{"project_id_$_"}; } 1..$form->{"rowcount"};
269
270   $form->get_lists("projects"      => { "key"    => "ALL_PROJECTS",
271                                         "all"    => 0,
272                                         "old_id" => \@old_project_ids },
273                    "taxzones"      => "ALL_TAXZONES",
274                    "currencies"    => "ALL_CURRENCIES",
275                    "vendors"       => "ALL_VENDORS",
276                    "departments"   => "all_departments",
277                    "price_factors" => "ALL_PRICE_FACTORS");
278
279   $TMPL_VAR{ALL_EMPLOYEES}         = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{employee_id},  deleted => 0 ] ]);
280   $TMPL_VAR{ALL_CONTACTS}          = SL::DB::Manager::Contact->get_all_sorted(query => [
281     or => [
282       cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
283       and      => [
284         cp_cv_id => undef,
285         cp_id    => $::form->{cp_id} * 1
286       ]
287     ]
288   ]);
289   $TMPL_VAR{department_labels}     = sub { "$_[0]->{description}--$_[0]->{id}" };
290
291   # customer
292   $TMPL_VAR{vc_keys} = sub { "$_[0]->{name}--$_[0]->{id}" };
293   $TMPL_VAR{vclimit} = $myconfig{vclimit};
294   $TMPL_VAR{vc_select} = "customer_or_vendor_selection_window('vendor', '', 1, 0)";
295   push @custom_hiddens, "vendor_id";
296   push @custom_hiddens, "oldvendor";
297   push @custom_hiddens, "selectvendor";
298
299   # currencies and exchangerate
300   my @values = map { $_       } @{ $form->{ALL_CURRENCIES} };
301   my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
302   $form->{currency}            = $form->{defaultcurrency} unless $form->{currency};
303   # show_exchangerate is also later needed in another template
304   $form->{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
305   $TMPL_VAR{currencies}        = NTI($cgi->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
306                                                       '-values' => \@values, '-labels' => \%labels,
307                                                       '-onchange' => "document.getElementById('update_button').click();"
308                                      )) if scalar @values;
309   push @custom_hiddens, "forex";
310   push @custom_hiddens, "exchangerate" if $form->{forex};
311
312   $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
313   $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
314
315   my $follow_up_vc         =  $form->{vendor};
316   $follow_up_vc            =~ s/--\d*\s*$//;
317   $TMPL_VAR{vendor_name} = $follow_up_vc;
318
319 # set option selected
320   foreach my $item (qw(AP)) {
321     $form->{"select$item"} =~ s/ selected//;
322     $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
323   }
324
325   $TMPL_VAR{is_type_credit_note} = $form->{type}   eq "credit_note";
326   $TMPL_VAR{is_format_html}      = $form->{format} eq 'html';
327   $TMPL_VAR{dateformat}          = $myconfig{dateformat};
328   $TMPL_VAR{numberformat}        = $myconfig{numberformat};
329
330   # hiddens
331   $TMPL_VAR{HIDDENS} = [qw(
332     id action type media format queued printed emailed title vc discount
333     title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
334     max_dunning_level dunning_amount
335     shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptogln shiptocontact shiptophone shiptofax
336     shiptoemail shiptodepartment_1 shiptodepartment_2 message email subject cc bcc taxaccounts cursor_fokus
337     convert_from_do_ids convert_from_oe_ids convert_from_ap_ids show_details gldate useasnew
338   ), @custom_hiddens,
339   map { $_.'_rate', $_.'_description', $_.'_taxnumber' } split / /, $form->{taxaccounts}];
340
341   $TMPL_VAR{payment_terms_obj} = get_payment_terms_for_invoice();
342   $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};
343
344   $::request->{layout}->use_javascript(map { "${_}.js" } qw(kivi.Draft kivi.SalesPurchase ckeditor/ckeditor ckeditor/adapters/jquery kivi.io autocomplete_customer autocomplete_part client_js));
345
346   $form->header();
347
348   print $form->parse_html_template("ir/form_header", \%TMPL_VAR);
349
350   $main::lxdebug->leave_sub();
351 }
352
353 sub _sort_payments {
354   my @fields   = qw(acc_trans_id gldate datepaid source memo paid AP_paid);
355   my @payments =
356     grep { $_->{paid} != 0 }
357     map  {
358       my $idx = $_;
359       +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
360     } (1..$::form->{paidaccounts});
361
362   @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
363
364   $::form->{paidaccounts} = max scalar(@payments), 1;
365
366   foreach my $idx (1 .. scalar(@payments)) {
367     my $payment = $payments[$idx - 1];
368     $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
369   }
370 }
371
372 sub form_footer {
373   $main::lxdebug->enter_sub();
374
375   my $form     = $main::form;
376   my %myconfig = %main::myconfig;
377   my $locale   = $main::locale;
378
379   $main::auth->assert('vendor_invoice_edit');
380
381   $form->{invtotal}    = $form->{invsubtotal};
382   $form->{oldinvtotal} = $form->{invtotal};
383
384   # note rows
385   $form->{rows} = max 2,
386     $form->numtextrows($form->{notes},    26, 8),
387     $form->numtextrows($form->{intnotes}, 35, 8);
388
389
390   # tax, total and subtotal calculations
391   my ($tax, $subtotal);
392   $form->{taxaccounts_array} = [ split / /, $form->{taxaccounts} ];
393
394   foreach my $item (@{ $form->{taxaccounts_array} }) {
395     if ($form->{"${item}_base"}) {
396       if ($form->{taxincluded}) {
397         $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
398                                                                                  / (1 + $form->{"${item}_rate"})), 2);
399         $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
400       } else {
401         $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
402         $form->{invtotal} += $form->{"${item}_total"};
403       }
404     }
405   }
406
407   # follow ups
408   if ($form->{id}) {
409     $form->{follow_ups}            = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1) || [];
410     $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
411   }
412
413   # payments
414   _sort_payments();
415
416   my $totalpaid = 0;
417   $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
418   $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
419
420   # Standard Konto für Umlaufvermögen
421   my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
422
423   for my $i (1 .. $form->{paidaccounts}) {
424     $form->{"changeable_$i"} = 1;
425     if (SL::DB::Default->get->payments_changeable == 0) {
426       # never
427       $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
428     } elsif (SL::DB::Default->get->payments_changeable == 2) {
429       # on the same day
430       $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
431                                   ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
432     }
433
434     $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
435       if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
436
437     #deaktivieren von Zahlungen ausserhalb der Bücherkontrolle
438     if ($form->date_closed($form->{"gldate_$i"})) {
439       $form->{"changeable_$i"} = 0;
440     }
441
442     $form->{"selectAP_paid_$i"} = $form->{selectAP_paid};
443     if (!$form->{"AP_paid_$i"}) {
444       $form->{"selectAP_paid_$i"} =~ s/option>$accno_arap--(.*?)>/option selected>$accno_arap--$1>/;
445     } else {
446       $form->{"selectAP_paid_$i"} =~ s/option>\Q$form->{"AP_paid_$i"}\E/option selected>$form->{"AP_paid_$i"}/;
447     }
448
449     $totalpaid += $form->{"paid_$i"};
450   }
451
452   $form->{ALL_DELIVERY_TERMS} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
453
454   print $form->parse_html_template('ir/form_footer', {
455     is_type_credit_note => ($form->{type} eq "credit_note"),
456     totalpaid           => $totalpaid,
457     paid_missing        => $form->{invtotal} - $totalpaid,
458     show_storno         => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ap") && !$totalpaid,
459     show_delete         => ($::instance_conf->get_ir_changeable == 2)
460                              ? ($form->current_date(\%myconfig) eq $form->{gldate})
461                              : ($::instance_conf->get_ir_changeable == 1),
462     today               => DateTime->today,
463   });
464 ##print $form->parse_html_template('ir/_payments'); # parser
465 ##print $form->parse_html_template('webdav/_list'); # parser
466
467   $main::lxdebug->leave_sub();
468 }
469
470 sub mark_as_paid {
471   $::auth->assert('vendor_invoice_edit');
472
473   SL::DB::PurchaseInvoice->new(id => $::form->{id})->load->mark_as_paid;
474
475   $::form->redirect($::locale->text("Marked as paid"));
476 }
477
478 sub show_draft {
479   update();
480 }
481
482 sub update {
483   $main::lxdebug->enter_sub();
484
485   my $form     = $main::form;
486   my %myconfig = %main::myconfig;
487
488   $main::auth->assert('vendor_invoice_edit');
489
490   &check_name('vendor');
491
492   if (!$form->{forex}) {        # read exchangerate from input field (not hidden)
493     $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate});
494   }
495   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'sell');
496   $form->{exchangerate} = $form->{forex} if $form->{forex};
497
498   for my $i (1 .. $form->{paidaccounts}) {
499     next unless $form->{"paid_$i"};
500     map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
501     $form->{"forex_$i"}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
502     $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
503   }
504
505   my $i            = $form->{rowcount};
506   my $exchangerate = ($form->{exchangerate} * 1) || 1;
507
508   if (   ($form->{"partnumber_$i"} eq "")
509       && ($form->{"description_$i"} eq "")
510       && ($form->{"partsgroup_$i"} eq "")) {
511     $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
512     &check_form;
513
514   } else {
515
516     IR->retrieve_item(\%myconfig, \%$form);
517
518     my $rows = scalar @{ $form->{item_list} };
519
520     $form->{"discount_$i"}   = $form->parse_amount(\%myconfig, $form->{"discount_$i"}) / 100.0;
521     $form->{"discount_$i"} ||= $form->{vendor_discount};
522
523     if ($rows) {
524       $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
525       if( !$form->{"qty_$i"} ) {
526         $form->{"qty_$i"} = 1;
527       }
528
529       if ($rows > 1) {
530
531         select_item(mode => 'IR', pre_entered_qty => $form->{"qty_$i"});
532         $::dispatcher->end_request;
533
534       } else {
535
536         # override sellprice if there is one entered
537         my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
538
539         map { $form->{item_list}[$i]{$_} =~ s/\"/&quot;/g } qw(partnumber description unit);
540         map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
541
542         $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
543
544         ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
545         my $dec_qty       = length $1;
546         my $decimalplaces = max 2, $dec_qty;
547
548         if ($sellprice) {
549           $form->{"sellprice_$i"} = $sellprice;
550         } else {
551           my $record        = _make_record();
552           my $price_source  = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
553           my $best_price    = $price_source->best_price;
554           my $best_discount = $price_source->best_discount;
555
556           if ($best_price) {
557             $::form->{"sellprice_$i"}           = $best_price->price;
558             $::form->{"active_price_source_$i"} = $best_price->source;
559           }
560           if ($best_discount) {
561             $::form->{"discount_$i"}               = $best_discount->discount;
562             $::form->{"active_discount_source_$i"} = $best_discount->source;
563           }
564
565           # if there is an exchange rate adjust sellprice
566           $form->{"sellprice_$i"} /= $exchangerate;
567         }
568
569         my $amount                = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"});
570         $form->{creditremaining} -= $amount;
571         $form->{"sellprice_$i"}   = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
572         $form->{"qty_$i"}         = $form->format_amount(\%myconfig, $form->{"qty_$i"},       $dec_qty);
573         $form->{"discount_$i"}    = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
574       }
575
576       &display_form;
577
578     } else {
579
580       # ok, so this is a new part
581       # ask if it is a part or service item
582
583       if (   $form->{"partsgroup_$i"}
584           && ($form->{"partsnumber_$i"} eq "")
585           && ($form->{"description_$i"} eq "")) {
586         $form->{rowcount}--;
587         $form->{"discount_$i"} = "";
588         display_form();
589
590       } else {
591         $form->{"id_$i"}   = 0;
592         new_item();
593       }
594     }
595   }
596   $main::lxdebug->leave_sub();
597 }
598
599 sub storno {
600   $main::lxdebug->enter_sub();
601
602   my $form     = $main::form;
603   my %myconfig = %main::myconfig;
604   my $locale   = $main::locale;
605
606   $main::auth->assert('vendor_invoice_edit');
607
608   if ($form->{storno}) {
609     $form->error($locale->text('Cannot storno storno invoice!'));
610   }
611
612   if (IS->has_storno(\%myconfig, $form, "ap")) {
613     $form->error($locale->text("Invoice has already been storno'd!"));
614   }
615
616   $form->error($locale->text('Cannot post storno for a closed period!'))
617     if ( $form->date_closed($form->{invdate}, \%myconfig));
618
619   my $employee_id = $form->{employee_id};
620   invoice_links();
621   prepare_invoice();
622   relink_accounts();
623
624   # Payments must not be recorded for the new storno invoice.
625   $form->{paidaccounts} = 0;
626   map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
627   # set new ids for storno invoice
628   # set new persistent ids for storno invoice items
629   $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
630
631   # saving the history
632   if(!exists $form->{addition} && $form->{id} ne "") {
633     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
634     $form->{what_done} = "invoice";
635     $form->{addition}  = "CANCELED";
636     $form->save_history;
637   }
638   # /saving the history
639
640   # record link invoice to storno
641   $form->{convert_from_ap_ids} = $form->{id};
642   $form->{storno_id} = $form->{id};
643   $form->{storno} = 1;
644   $form->{id} = "";
645   $form->{invnumber} = "Storno zu " . $form->{invnumber};
646   $form->{rowcount}++;
647   $form->{employee_id} = $employee_id;
648   post();
649   $main::lxdebug->leave_sub();
650
651 }
652
653 sub use_as_new {
654   $main::lxdebug->enter_sub();
655
656   my $form     = $main::form;
657   my %myconfig = %main::myconfig;
658
659   $main::auth->assert('vendor_invoice_edit');
660
661   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);
662   $form->{paidaccounts} = 1;
663   $form->{rowcount}--;
664   $form->{invdate} = $form->current_date(\%myconfig);
665
666   $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
667
668   $form->{useasnew} = 1;
669   &display_form;
670
671   $main::lxdebug->leave_sub();
672 }
673
674 sub post_payment {
675   $main::lxdebug->enter_sub();
676
677   my $form     = $main::form;
678   my %myconfig = %main::myconfig;
679   my $locale   = $main::locale;
680
681   $main::auth->assert('vendor_invoice_edit');
682
683   $form->mtime_ischanged('ap') ;
684   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
685   for my $i (1 .. $form->{paidaccounts}) {
686     if ($form->{"paid_$i"}) {
687       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
688
689       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
690
691       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
692         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
693
694       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
695       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
696       $form->error($locale->text('Cannot post payment for a closed period!'))
697         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
698
699       if ($form->{currency} ne $form->{defaultcurrency}) {
700 #        $form->{"exchangerate_$i"} = $form->{exchangerate} if ($invdate == $datepaid); # invdate isn't set here
701         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
702       }
703     }
704   }
705
706   ($form->{AP})      = split /--/, $form->{AP};
707   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
708   if (IR->post_payment(\%myconfig, \%$form)){
709     if (!exists $form->{addition} && $form->{id} ne "") {
710       # saving the history
711       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
712       $form->{addition}  = "PAYMENT POSTED";
713       $form->{what_done} = "invoice";
714       $form->save_history;
715       # /saving the history
716     }
717
718     $form->redirect($locale->text('Payment posted!'));
719   }
720
721   $form->error($locale->text('Cannot post payment!'));
722
723   $main::lxdebug->leave_sub();
724 }
725
726 sub _max_datepaid {
727   my $form  =  $main::form;
728
729   my @dates = sort { $b->[1] cmp $a->[1] }
730               map  { [ $_, $main::locale->reformat_date(\%main::myconfig, $_, 'yyyy-mm-dd') ] }
731               grep { $_ }
732               map  { $form->{"datepaid_${_}"} }
733               (1..$form->{rowcount});
734
735   return @dates ? $dates[0]->[0] : undef;
736 }
737
738
739 sub post {
740   $main::lxdebug->enter_sub();
741
742   my $form     = $main::form;
743   my %myconfig = %main::myconfig;
744   my $locale   = $main::locale;
745
746   $main::auth->assert('vendor_invoice_edit');
747
748   $form->mtime_ischanged('ap');
749   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
750
751   $form->isblank("invdate",   $locale->text('Invoice Date missing!'));
752   $form->isblank("vendor",    $locale->text('Vendor missing!'));
753   $form->isblank("invnumber", $locale->text('Invnumber missing!'));
754
755   $form->{invnumber} =~ s/^\s*//g;
756   $form->{invnumber} =~ s/\s*$//g;
757
758   # if the vendor changed get new values
759   if (&check_name('vendor')) {
760     &update;
761     $::dispatcher->end_request;
762   }
763
764   if ($myconfig{mandatory_departments} && !$form->{department_id}) {
765     $form->{saved_message} = $::locale->text('You have to specify a department.');
766     update();
767     exit;
768   }
769
770   remove_emptied_rows();
771   &validate_items;
772
773   my $closedto     = $form->datetonum($form->{closedto}, \%myconfig);
774   my $invdate      = $form->datetonum($form->{invdate},  \%myconfig);
775   my $max_datepaid = _max_datepaid();
776
777   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
778     if ($form->date_max_future($invdate, \%myconfig));
779   $form->error($locale->text('Cannot post invoice for a closed period!'))
780     if ($invdate <= $closedto);
781
782   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
783     if ($form->{currency} ne $form->{defaultcurrency});
784
785   my $i;
786   for $i (1 .. $form->{paidaccounts}) {
787     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
788       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
789
790       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
791
792       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
793         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
794
795       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
796       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
797       $form->error($locale->text('Cannot post payment for a closed period!'))
798         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
799
800       if ($form->{currency} ne $form->{defaultcurrency}) {
801         $form->{"exchangerate_$i"} = $form->{exchangerate}
802           if ($invdate == $datepaid);
803         $form->isblank("exchangerate_$i",
804                        $locale->text('Exchangerate for payment missing!'));
805       }
806     }
807   }
808
809   ($form->{AP})      = split /--/, $form->{AP};
810   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
811   $form->{storno}  ||= 0;
812
813   $form->{id} = 0 if $form->{postasnew};
814
815
816   relink_accounts();
817   if (IR->post_invoice(\%myconfig, \%$form)){
818     # saving the history
819     if(!exists $form->{addition} && $form->{id} ne "") {
820       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
821       $form->{addition}  = "POSTED";
822       $form->{what_done} = 'invoice';
823       $form->save_history;
824     }
825     # /saving the history
826     $form->redirect(  $locale->text('Invoice')
827                   . " $form->{invnumber} "
828                   . $locale->text('posted!'));
829   }
830   $form->error($locale->text('Cannot post invoice!'));
831
832   $main::lxdebug->leave_sub();
833 }
834
835 sub delete {
836   $main::lxdebug->enter_sub();
837
838   my $form     = $main::form;
839   my $locale   = $main::locale;
840
841   $main::auth->assert('vendor_invoice_edit');
842
843   $form->header;
844   print qq|
845 <form method=post action=$form->{script}>
846 |;
847
848   # delete action variable
849   map { delete $form->{$_} } qw(action header);
850
851   foreach my $key (keys %$form) {
852     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
853     $form->{$key} =~ s/\"/&quot;/g;
854     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
855   }
856
857   print qq|
858 <h2 class=confirm>| . $locale->text('Confirm!') . qq|</h2>
859
860 <h4>|
861     . $locale->text('Are you sure you want to delete Invoice Number')
862     . qq| $form->{invnumber}</h4>
863 <p>
864 <input name=action class=submit type=submit value="|
865     . $locale->text('Yes') . qq|">
866 </form>
867 |;
868
869   $main::lxdebug->leave_sub();
870 }
871
872 sub display_form {
873   $::lxdebug->enter_sub;
874
875   $::auth->assert('vendor_invoice_edit');
876
877   relink_accounts();
878
879   my $new_rowcount = $::form->{"rowcount"} * 1 + 1;
880   $::form->{"project_id_${new_rowcount}"} = $::form->{"globalproject_id"};
881
882   $::form->language_payment(\%::myconfig);
883
884   Common::webdav_folder($::form);
885
886   form_header();
887   display_row(++$::form->{rowcount});
888   form_footer();
889
890   $::lxdebug->leave_sub;
891 }
892
893 sub yes {
894   $main::lxdebug->enter_sub();
895
896   my $form     = $main::form;
897   my %myconfig = %main::myconfig;
898   my $locale   = $main::locale;
899
900   $main::auth->assert('vendor_invoice_edit');
901
902   if (IR->delete_invoice(\%myconfig, \%$form)) {
903     # saving the history
904     if(!exists $form->{addition}) {
905       $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
906       $form->{addition} = "DELETED";
907       $form->save_history;
908     }
909     # /saving the history
910     $form->redirect($locale->text('Invoice deleted!'));
911   }
912   $form->error($locale->text('Cannot delete invoice!'));
913
914   $main::lxdebug->leave_sub();
915 }
916
917 sub get_duedate_vendor {
918   $::lxdebug->enter_sub;
919
920   my $result = IR->get_duedate(
921     vendor_id => $::form->{vendor_id},
922     invdate   => $::form->{invdate},
923     default   => $::form->{old_duedate},
924   );
925
926   print $::form->ajax_response_header, $result;
927   $::lxdebug->leave_sub;
928 }