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