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