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