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