EK-Rechnung Stornos verbieten solange Zahlungen nicht ausgeglichen sind
[kivitendo-erp.git] / bin / mozilla / ir.pl
1 #=====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 # SQL-Ledger, Accounting
9 # Copyright (c) 1998-2002
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 #
16 # This program is free software; you can redistribute it and/or modify
17 # it under the terms of the GNU General Public License as published by
18 # the Free Software Foundation; either version 2 of the License, or
19 # (at your option) any later version.
20 #
21 # This program is distributed in the hope that it will be useful,
22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 # GNU General Public License for more details.
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
28 # MA 02110-1335, USA.
29 #======================================================================
30 #
31 # Inventory received module
32 #
33 #======================================================================
34
35 use SL::FU;
36 use SL::IR;
37 use SL::IS;
38 use SL::DB::Default;
39 use SL::DB::Department;
40 use SL::DB::PurchaseInvoice;
41 use SL::DB::Vendor;
42 use List::Util qw(max sum);
43 use List::UtilsBy qw(sort_by);
44
45 require "bin/mozilla/io.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   $form->backup_vars(qw(payment_id language_id taxzone_id
114                         currency delivery_term_id intnotes cp_id));
115
116   IR->get_vendor(\%myconfig, \%$form);
117   IR->retrieve_invoice(\%myconfig, \%$form);
118
119   $form->restore_vars(qw(payment_id language_id taxzone_id
120                          currency delivery_term_id intnotes cp_id));
121
122   my @curr = $form->get_all_currencies();
123   map { $form->{selectcurrency} .= "<option>$_\n" } @curr;
124
125   # forex
126   $form->{forex} = $form->{exchangerate};
127   my $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
128
129   foreach my $key (keys %{ $form->{AP_links} }) {
130
131     foreach my $ref (@{ $form->{AP_links}{$key} }) {
132       $form->{"select$key"} .= "<option>$ref->{accno}--$ref->{description}</option>";
133     }
134
135     next unless $form->{acc_trans}{$key};
136
137     if ($key eq "AP_paid") {
138       for my $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
139         $form->{"AP_paid_$i"} =
140           "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
141
142         $form->{"acc_trans_id_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
143         # reverse paid
144         $form->{"paid_$i"}     = $form->{acc_trans}{$key}->[$i - 1]->{amount};
145         $form->{"datepaid_$i"} =
146           $form->{acc_trans}{$key}->[$i - 1]->{transdate};
147         $form->{"gldate_$i"}   = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
148         $form->{"forex_$i"} = $form->{"exchangerate_$i"} =
149           $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
150         $form->{"source_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{source};
151         $form->{"memo_$i"}   = $form->{acc_trans}{$key}->[$i - 1]->{memo};
152
153         $form->{paidaccounts} = $i;
154       }
155     } else {
156       $form->{$key} =
157         "$form->{acc_trans}{$key}->[0]->{accno}--$form->{acc_trans}{$key}->[0]->{description}";
158     }
159
160   }
161
162   $form->{paidaccounts} = 1 unless (exists $form->{paidaccounts});
163
164   $form->{AP} = $form->{AP_1} unless $form->{id};
165
166   $form->{locked} =
167     ($form->datetonum($form->{invdate}, \%myconfig) <=
168      $form->datetonum($form->{closedto}, \%myconfig));
169
170   $main::lxdebug->leave_sub();
171 }
172
173 sub prepare_invoice {
174   $main::lxdebug->enter_sub();
175
176   my $form     = $main::form;
177   my %myconfig = %main::myconfig;
178
179   $main::auth->assert('vendor_invoice_edit');
180
181   $form->{type}     = "purchase_invoice";
182
183   if ($form->{id}) {
184
185     map { $form->{$_} =~ s/\"/&quot;/g } qw(invnumber ordnumber quonumber);
186
187     my $i = 0;
188     foreach my $ref (@{ $form->{invoice_details} }) {
189       $i++;
190       map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
191       # übernommen aus is.pl Fix für Bug 1642. Nebenwirkungen? jb 12.5.2011
192       # getestet: Lieferantenauftrag -> Rechnung i.O.
193       #           Lieferantenauftrag -> Lieferschein -> Rechnung i.O.
194       # Werte: 20% (Lieferantenrabatt), 12,4% individuell und 0,4 individuell s.a.
195       # Screenshot zu Bug 1642
196       $form->{"discount_$i"}   = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100);
197
198       my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
199       $dec           = length $dec;
200       my $decimalplaces = ($dec > 2) ? $dec : 2;
201
202       $form->{"sellprice_$i"} =
203         $form->format_amount(\%myconfig, $form->{"sellprice_$i"},
204                              $decimalplaces);
205
206       (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
207       $dec_qty = length $dec_qty;
208
209       $form->{"qty_$i"} =
210         $form->format_amount(\%myconfig, ($form->{"qty_$i"} * -1), $dec_qty);
211
212       $form->{rowcount} = $i;
213     }
214   }
215
216   $main::lxdebug->leave_sub();
217 }
218
219 sub setup_ir_action_bar {
220   my $form                    = $::form;
221   my $change_never            = $::instance_conf->get_ir_changeable == 0;
222   my $change_on_same_day_only = $::instance_conf->get_ir_changeable == 2 && ($form->current_date(\%::myconfig) ne $form->{gldate});
223   my $has_storno              = ($::form->{storno} && !$::form->{storno_id});
224   my $payments_balanced       = ($::form->{oldtotalpaid} == 0);
225
226   my $has_sepa_exports;
227
228   if ($form->{id}) {
229     my $invoice = SL::DB::Manager::PurchaseInvoice->find_by(id => $form->{id});
230     $has_sepa_exports = 1 if ($invoice->find_sepa_export_items()->[0]);
231   }
232
233   for my $bar ($::request->layout->get('actionbar')) {
234     $bar->add(
235       action => [
236         t8('Update'),
237         submit    => [ '#form', { action => "update" } ],
238         checks    => [ 'kivi.validate_form' ],
239         id        => 'update_button',
240         accesskey => 'enter',
241       ],
242
243       combobox => [
244         action => [
245           t8('Post'),
246           submit   => [ '#form', { action => "post" } ],
247           checks   => [ 'kivi.validate_form' ],
248           disabled => $form->{locked}                           ? t8('The billing period has already been locked.')
249                     : $form->{storno}                           ? t8('A canceled invoice cannot be posted.')
250                     : ($form->{id} && $change_never)            ? t8('Changing invoices has been disabled in the configuration.')
251                     : ($form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
252                     :                                             undef,
253         ],
254         action => [
255           t8('Post Payment'),
256           submit   => [ '#form', { action => "post_payment" } ],
257           checks   => [ 'kivi.validate_form' ],
258           disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
259         ],
260         action => [
261           t8('Mark as paid'),
262           submit   => [ '#form', { action => "mark_as_paid" } ],
263           checks   => [ 'kivi.validate_form' ],
264           confirm  => t8('This will remove the invoice from showing as unpaid even if the unpaid amount does not match the amount. Proceed?'),
265           disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
266           only_if  => $::instance_conf->get_ir_show_mark_as_paid,
267         ],
268       ], # end of combobox "Post"
269
270       combobox => [
271         action => [ t8('Storno'),
272           submit   => [ '#form', { action => "storno" } ],
273           checks   => [ 'kivi.validate_form' ],
274           confirm  => t8('Do you really want to cancel this invoice?'),
275           disabled => !$form->{id}          ? t8('This invoice has not been posted yet.')
276                       : $has_sepa_exports   ? t8('This invoice has been linked with a sepa export, undo this first.')
277                       : !$payments_balanced ? t8('Cancelling is disallowed. Either undo or balance the current payments until the open amount matches the invoice amount')
278                       : undef,
279         ],
280         action => [ t8('Delete'),
281           submit   => [ '#form', { action => "delete" } ],
282           checks   => [ 'kivi.validate_form' ],
283           confirm  => t8('Do you really want to delete this object?'),
284           disabled => !$form->{id}             ? t8('This invoice has not been posted yet.')
285                     : $form->{locked}          ? t8('The billing period has already been locked.')
286                     : $change_never            ? t8('Changing invoices has been disabled in the configuration.')
287                     : $change_on_same_day_only ? t8('Invoices can only be changed on the day they are posted.')
288                     : $has_sepa_exports        ? t8('This invoice has been linked with a sepa export, undo this first.')
289                     : $has_storno              ? t8('Can only delete the "Storno zu" part of the cancellation pair.')
290                     :                            undef,
291         ],
292       ], # end of combobox "Storno"
293
294       'separator',
295
296       combobox => [
297         action => [ t8('Workflow') ],
298         action => [
299           t8('Use As New'),
300           submit   => [ '#form', { action => "use_as_new" } ],
301           checks   => [ 'kivi.validate_form' ],
302           disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
303         ],
304        ], # end of combobox "Workflow"
305
306       combobox => [
307         action => [ t8('more') ],
308         action => [
309           t8('History'),
310           call     => [ 'set_history_window', $::form->{id} * 1, 'id', 'glid' ],
311           disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
312         ],
313         action => [
314           t8('Follow-Up'),
315           call     => [ 'follow_up_window' ],
316           disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
317         ],
318         action => [
319           t8('Drafts'),
320           call     => [ 'kivi.Draft.popup', 'ir', 'invoice', $::form->{draft_id}, $::form->{draft_description} ],
321           disabled => $form->{id}     ? t8('This invoice has already been posted.')
322                     : $form->{locked} ? t8('The billing period has already been locked.')
323                     :                   undef,
324         ],
325       ], # end of combobox "more"
326     );
327   }
328   $::request->layout->add_javascripts('kivi.Validator.js');
329 }
330
331 sub form_header {
332   $main::lxdebug->enter_sub();
333
334   my $form     = $main::form;
335   my %myconfig = %main::myconfig;
336   my $locale   = $main::locale;
337   my $cgi      = $::request->{cgi};
338
339   $main::auth->assert('vendor_invoice_edit');
340
341   my %TMPL_VAR = ();
342   my @custom_hiddens;
343
344   $TMPL_VAR{invoice_obj} = SL::DB::PurchaseInvoice->load_cached($form->{id}) if $form->{id};
345   $TMPL_VAR{vendor_obj}  = SL::DB::Vendor->load_cached($form->{vendor_id})   if $form->{vendor_id};
346   my $current_employee   = SL::DB::Manager::Employee->current;
347   $form->{employee_id}   = $form->{old_employee_id} if $form->{old_employee_id};
348   $form->{salesman_id}   = $form->{old_salesman_id} if $form->{old_salesman_id};
349   $form->{employee_id} ||= $current_employee->id;
350   $form->{salesman_id} ||= $current_employee->id;
351
352   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
353
354   my @old_project_ids = ($form->{"globalproject_id"});
355   map { push @old_project_ids, $form->{"project_id_$_"} if $form->{"project_id_$_"}; } 1..$form->{"rowcount"};
356
357   $form->get_lists("taxzones"      => ($form->{id} ? "ALL_TAXZONES" : "ALL_ACTIVE_TAXZONES"),
358                    "currencies"    => "ALL_CURRENCIES",
359                    "price_factors" => "ALL_PRICE_FACTORS");
360
361   $TMPL_VAR{ALL_DEPARTMENTS}       = SL::DB::Manager::Department->get_all_sorted;
362   $TMPL_VAR{ALL_EMPLOYEES}         = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{employee_id},  deleted => 0 ] ]);
363   $TMPL_VAR{ALL_CONTACTS}          = SL::DB::Manager::Contact->get_all_sorted(query => [
364     or => [
365       cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
366       and      => [
367         cp_cv_id => undef,
368         cp_id    => $::form->{cp_id} * 1
369       ]
370     ]
371   ]);
372
373   # currencies and exchangerate
374   my @values = map { $_       } @{ $form->{ALL_CURRENCIES} };
375   my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
376   $form->{currency}            = $form->{defaultcurrency} unless $form->{currency};
377   # show_exchangerate is also later needed in another template
378   $form->{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
379   $TMPL_VAR{currencies}        = NTI($cgi->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
380                                                       '-values' => \@values, '-labels' => \%labels,
381                                                       '-onchange' => "document.getElementById('update_button').click();"
382                                      )) if scalar @values;
383   push @custom_hiddens, "forex";
384   push @custom_hiddens, "exchangerate" if $form->{forex};
385
386   $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
387   $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
388
389 # set option selected
390   foreach my $item (qw(AP)) {
391     $form->{"select$item"} =~ s/ selected//;
392     $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
393   }
394
395   $TMPL_VAR{is_type_credit_note} = $form->{type}   eq "credit_note";
396   $TMPL_VAR{is_format_html}      = $form->{format} eq 'html';
397   $TMPL_VAR{dateformat}          = $myconfig{dateformat};
398   $TMPL_VAR{numberformat}        = $myconfig{numberformat};
399
400   # hiddens
401   $TMPL_VAR{HIDDENS} = [qw(
402     id type queued printed emailed title vc discount
403     title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
404     max_dunning_level dunning_amount
405     shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptogln shiptocontact shiptophone shiptofax
406     shiptoemail shiptodepartment_1 shiptodepartment_2 message email subject cc bcc taxaccounts cursor_fokus
407     convert_from_do_ids convert_from_oe_ids convert_from_ap_ids show_details gldate useasnew
408   ), @custom_hiddens,
409   map { $_.'_rate', $_.'_description', $_.'_taxnumber' } split / /, $form->{taxaccounts}];
410
411   $TMPL_VAR{payment_terms_obj} = get_payment_terms_for_invoice();
412   $form->{duedate}             = $TMPL_VAR{payment_terms_obj}->calc_date(reference_date => $form->{invdate}, due_date => $form->{duedate})->to_kivitendo if $TMPL_VAR{payment_terms_obj};
413
414   $::request->{layout}->use_javascript(map { "${_}.js" } qw(kivi.Draft kivi.File kivi.SalesPurchase kivi.Part kivi.CustomerVendor kivi.Validator ckeditor/ckeditor ckeditor/adapters/jquery kivi.io autocomplete_project client_js));
415
416   setup_ir_action_bar();
417
418   $form->header();
419
420   print $form->parse_html_template("ir/form_header", \%TMPL_VAR);
421
422   $main::lxdebug->leave_sub();
423 }
424
425 sub _sort_payments {
426   my @fields   = qw(acc_trans_id gldate datepaid source memo paid AP_paid);
427   my @payments =
428     grep { $_->{paid} != 0 }
429     map  {
430       my $idx = $_;
431       +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
432     } (1..$::form->{paidaccounts});
433
434   @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
435
436   $::form->{paidaccounts} = max scalar(@payments), 1;
437
438   foreach my $idx (1 .. scalar(@payments)) {
439     my $payment = $payments[$idx - 1];
440     $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
441   }
442 }
443
444 sub form_footer {
445   $main::lxdebug->enter_sub();
446
447   my $form     = $main::form;
448   my %myconfig = %main::myconfig;
449   my $locale   = $main::locale;
450
451   $main::auth->assert('vendor_invoice_edit');
452
453   $form->{invtotal}    = $form->{invsubtotal};
454   $form->{oldinvtotal} = $form->{invtotal};
455
456   # note rows
457   $form->{rows} = max 2,
458     $form->numtextrows($form->{notes},    26, 8),
459     $form->numtextrows($form->{intnotes}, 35, 8);
460
461
462   # tax, total and subtotal calculations
463   my ($tax, $subtotal);
464   $form->{taxaccounts_array} = [ split / /, $form->{taxaccounts} ];
465
466   foreach my $item (@{ $form->{taxaccounts_array} }) {
467     if ($form->{"${item}_base"}) {
468       if ($form->{taxincluded}) {
469         $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
470                                                                                  / (1 + $form->{"${item}_rate"})), 2);
471         $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
472       } else {
473         $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
474         $form->{invtotal} += $form->{"${item}_total"};
475       }
476     }
477   }
478
479   # follow ups
480   if ($form->{id}) {
481     $form->{follow_ups}            = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1) || [];
482     $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
483   }
484
485   # payments
486   _sort_payments();
487
488   my $totalpaid = 0;
489   $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
490   $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
491
492   # Standard Konto für Umlaufvermögen
493   my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
494
495   for my $i (1 .. $form->{paidaccounts}) {
496     $form->{"changeable_$i"} = 1;
497     if (SL::DB::Default->get->payments_changeable == 0) {
498       # never
499       $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
500     } elsif (SL::DB::Default->get->payments_changeable == 2) {
501       # on the same day
502       $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
503                                   ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
504     }
505
506     $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
507       if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
508
509     #deaktivieren von Zahlungen ausserhalb der Bücherkontrolle
510     if ($form->date_closed($form->{"gldate_$i"})) {
511       $form->{"changeable_$i"} = 0;
512     }
513
514     $form->{"selectAP_paid_$i"} = $form->{selectAP_paid};
515     if (!$form->{"AP_paid_$i"}) {
516       $form->{"selectAP_paid_$i"} =~ s/option>$accno_arap--(.*?)>/option selected>$accno_arap--$1>/;
517     } else {
518       $form->{"selectAP_paid_$i"} =~ s/option>\Q$form->{"AP_paid_$i"}\E/option selected>$form->{"AP_paid_$i"}/;
519     }
520
521     $totalpaid += $form->{"paid_$i"};
522   }
523
524   $form->{ALL_DELIVERY_TERMS} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
525
526   print $form->parse_html_template('ir/form_footer', {
527     is_type_credit_note => ($form->{type} eq "credit_note"),
528     totalpaid           => $totalpaid,
529     paid_missing        => $form->{invtotal} - $totalpaid,
530     show_storno         => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ap") && !$totalpaid,
531     show_delete         => ($::instance_conf->get_ir_changeable == 2)
532                              ? ($form->current_date(\%myconfig) eq $form->{gldate})
533                              : ($::instance_conf->get_ir_changeable == 1),
534     today               => DateTime->today,
535   });
536 ##print $form->parse_html_template('ir/_payments'); # parser
537 ##print $form->parse_html_template('webdav/_list'); # parser
538
539   $main::lxdebug->leave_sub();
540 }
541
542 sub mark_as_paid {
543   $::auth->assert('vendor_invoice_edit');
544
545   SL::DB::PurchaseInvoice->new(id => $::form->{id})->load->mark_as_paid;
546
547   $::form->redirect($::locale->text("Marked as paid"));
548 }
549
550 sub show_draft {
551   update();
552 }
553
554 sub update {
555   $main::lxdebug->enter_sub();
556
557   my $form     = $main::form;
558   my %myconfig = %main::myconfig;
559
560   $main::auth->assert('vendor_invoice_edit');
561
562   if (($form->{previous_vendor_id} || $form->{vendor_id}) != $form->{vendor_id}) {
563     IR->get_vendor(\%myconfig, $form);
564   }
565
566   if (!$form->{forex}) {        # read exchangerate from input field (not hidden)
567     $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate});
568   }
569   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'sell');
570   $form->{exchangerate} = $form->{forex} if $form->{forex};
571
572   for my $i (1 .. $form->{paidaccounts}) {
573     next unless $form->{"paid_$i"};
574     map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
575     $form->{"forex_$i"}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
576     $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
577   }
578
579   my $i            = $form->{rowcount};
580   my $exchangerate = ($form->{exchangerate} * 1) || 1;
581
582   if (   ($form->{"partnumber_$i"} eq "")
583       && ($form->{"description_$i"} eq "")
584       && ($form->{"partsgroup_$i"} eq "")) {
585     $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
586     &check_form;
587
588   } else {
589
590     IR->retrieve_item(\%myconfig, \%$form);
591
592     my $rows = scalar @{ $form->{item_list} };
593
594     $form->{"discount_$i"}   = $form->parse_amount(\%myconfig, $form->{"discount_$i"}) / 100.0;
595     $form->{"discount_$i"} ||= $form->{vendor_discount};
596
597     if ($rows) {
598       $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
599       if( !$form->{"qty_$i"} ) {
600         $form->{"qty_$i"} = 1;
601       }
602
603       if ($rows > 1) {
604
605         select_item(mode => 'IR', pre_entered_qty => $form->{"qty_$i"});
606         $::dispatcher->end_request;
607
608       } else {
609
610         # override sellprice if there is one entered
611         my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
612
613         map { $form->{item_list}[$i]{$_} =~ s/\"/&quot;/g } qw(partnumber description unit);
614         map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
615
616         $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
617
618         ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
619         my $dec_qty       = length $1;
620         my $decimalplaces = max 2, $dec_qty;
621
622         if ($sellprice) {
623           $form->{"sellprice_$i"} = $sellprice;
624         } else {
625           my $record        = _make_record();
626           my $price_source  = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
627           my $best_price    = $price_source->best_price;
628           my $best_discount = $price_source->best_discount;
629
630           if ($best_price) {
631             $::form->{"sellprice_$i"}           = $best_price->price;
632             $::form->{"active_price_source_$i"} = $best_price->source;
633           }
634           if ($best_discount) {
635             $::form->{"discount_$i"}               = $best_discount->discount;
636             $::form->{"active_discount_source_$i"} = $best_discount->source;
637           }
638
639           # if there is an exchange rate adjust sellprice
640           $form->{"sellprice_$i"} /= $exchangerate;
641         }
642
643         my $amount                = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"});
644         $form->{creditremaining} -= $amount;
645         $form->{"sellprice_$i"}   = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
646         $form->{"qty_$i"}         = $form->format_amount(\%myconfig, $form->{"qty_$i"},       $dec_qty);
647         $form->{"discount_$i"}    = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
648       }
649
650       &display_form;
651
652     } else {
653
654       # ok, so this is a new part
655       # ask if it is a part or service item
656
657       if (   $form->{"partsgroup_$i"}
658           && ($form->{"partsnumber_$i"} eq "")
659           && ($form->{"description_$i"} eq "")) {
660         $form->{rowcount}--;
661         $form->{"discount_$i"} = "";
662         display_form();
663
664       } else {
665         $form->{"id_$i"}   = 0;
666         new_item();
667       }
668     }
669   }
670   $main::lxdebug->leave_sub();
671 }
672
673 sub storno {
674   $main::lxdebug->enter_sub();
675
676   my $form     = $main::form;
677   my %myconfig = %main::myconfig;
678   my $locale   = $main::locale;
679
680   $main::auth->assert('vendor_invoice_edit');
681
682   if ($form->{storno}) {
683     $form->error($locale->text('Cannot storno storno invoice!'));
684   }
685
686   if (IS->has_storno(\%myconfig, $form, "ap")) {
687     $form->error($locale->text("Invoice has already been storno'd!"));
688   }
689
690   $form->error($locale->text('Cannot post storno for a closed period!'))
691     if ( $form->date_closed($form->{invdate}, \%myconfig));
692
693   my $employee_id = $form->{employee_id};
694   invoice_links();
695   prepare_invoice();
696   relink_accounts();
697
698   # Payments must not be recorded for the new storno invoice.
699   $form->{paidaccounts} = 0;
700   map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
701   # set new ids for storno invoice
702   # set new persistent ids for storno invoice items
703   $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
704
705   # saving the history
706   if(!exists $form->{addition} && $form->{id} ne "") {
707     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
708     $form->{what_done} = "invoice";
709     $form->{addition}  = "CANCELED";
710     $form->save_history;
711   }
712   # /saving the history
713
714   # record link invoice to storno
715   $form->{convert_from_ap_ids} = $form->{id};
716   $form->{storno_id} = $form->{id};
717   $form->{storno} = 1;
718   $form->{id} = "";
719   $form->{invnumber} = "Storno zu " . $form->{invnumber};
720   $form->{rowcount}++;
721   $form->{employee_id} = $employee_id;
722   post();
723   $main::lxdebug->leave_sub();
724
725 }
726
727 sub use_as_new {
728   $main::lxdebug->enter_sub();
729
730   my $form     = $main::form;
731   my %myconfig = %main::myconfig;
732
733   $main::auth->assert('vendor_invoice_edit');
734
735   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);
736   $form->{paidaccounts} = 1;
737   $form->{rowcount}--;
738   $form->{invdate} = $form->current_date(\%myconfig);
739
740   $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
741
742   $form->{useasnew} = 1;
743   &display_form;
744
745   $main::lxdebug->leave_sub();
746 }
747
748 sub post_payment {
749   $main::lxdebug->enter_sub();
750
751   my $form     = $main::form;
752   my %myconfig = %main::myconfig;
753   my $locale   = $main::locale;
754
755   $main::auth->assert('vendor_invoice_edit');
756
757   $form->mtime_ischanged('ap') ;
758   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
759   for my $i (1 .. $form->{paidaccounts}) {
760     if ($form->{"paid_$i"}) {
761       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
762
763       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
764
765       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
766         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
767
768       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
769       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
770       $form->error($locale->text('Cannot post payment for a closed period!'))
771         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
772
773       if ($form->{currency} ne $form->{defaultcurrency}) {
774 #        $form->{"exchangerate_$i"} = $form->{exchangerate} if ($invdate == $datepaid); # invdate isn't set here
775         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
776       }
777     }
778   }
779
780   ($form->{AP})      = split /--/, $form->{AP};
781   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
782   if (IR->post_payment(\%myconfig, \%$form)){
783     if (!exists $form->{addition} && $form->{id} ne "") {
784       # saving the history
785       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
786       $form->{addition}  = "PAYMENT POSTED";
787       $form->{what_done} = "invoice";
788       $form->save_history;
789       # /saving the history
790     }
791
792     $form->redirect($locale->text('Payment posted!'));
793   }
794
795   $form->error($locale->text('Cannot post payment!'));
796
797   $main::lxdebug->leave_sub();
798 }
799
800 sub _max_datepaid {
801   my $form  =  $main::form;
802
803   my @dates = sort { $b->[1] cmp $a->[1] }
804               map  { [ $_, $main::locale->reformat_date(\%main::myconfig, $_, 'yyyy-mm-dd') ] }
805               grep { $_ }
806               map  { $form->{"datepaid_${_}"} }
807               (1..$form->{rowcount});
808
809   return @dates ? $dates[0]->[0] : undef;
810 }
811
812
813 sub post {
814   $main::lxdebug->enter_sub();
815
816   my $form     = $main::form;
817   my %myconfig = %main::myconfig;
818   my $locale   = $main::locale;
819
820   $main::auth->assert('vendor_invoice_edit');
821
822   $form->mtime_ischanged('ap');
823   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
824
825   $form->isblank("invdate",   $locale->text('Invoice Date missing!'));
826   $form->isblank("vendor_id", $locale->text('Vendor missing!'));
827   $form->isblank("invnumber", $locale->text('Invnumber missing!'));
828
829   $form->{invnumber} =~ s/^\s*//g;
830   $form->{invnumber} =~ s/\s*$//g;
831
832   # if the vendor changed get new values
833   if (($form->{previous_vendor_id} || $form->{vendor_id}) != $form->{vendor_id}) {
834     &update;
835     $::dispatcher->end_request;
836   }
837
838   if ($myconfig{mandatory_departments} && !$form->{department_id}) {
839     $form->{saved_message} = $::locale->text('You have to specify a department.');
840     update();
841     exit;
842   }
843
844   remove_emptied_rows();
845   &validate_items;
846
847   my $closedto     = $form->datetonum($form->{closedto}, \%myconfig);
848   my $invdate      = $form->datetonum($form->{invdate},  \%myconfig);
849   my $max_datepaid = _max_datepaid();
850
851   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
852     if ($form->date_max_future($invdate, \%myconfig));
853   $form->error($locale->text('Cannot post invoice for a closed period!'))
854     if ($invdate <= $closedto);
855
856   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
857     if ($form->{currency} ne $form->{defaultcurrency});
858
859   my $i;
860   for $i (1 .. $form->{paidaccounts}) {
861     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
862       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
863
864       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
865
866       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
867         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
868
869       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
870       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
871       $form->error($locale->text('Cannot post payment for a closed period!'))
872         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
873
874       if ($form->{currency} ne $form->{defaultcurrency}) {
875         $form->{"exchangerate_$i"} = $form->{exchangerate}
876           if ($invdate == $datepaid);
877         $form->isblank("exchangerate_$i",
878                        $locale->text('Exchangerate for payment missing!'));
879       }
880     }
881   }
882
883   ($form->{AP})      = split /--/, $form->{AP};
884   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
885   $form->{storno}  ||= 0;
886
887   $form->{id} = 0 if $form->{postasnew};
888
889
890   relink_accounts();
891   if (IR->post_invoice(\%myconfig, \%$form)){
892     # saving the history
893     if(!exists $form->{addition} && $form->{id} ne "") {
894       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
895       $form->{addition}  = "POSTED";
896       $form->{what_done} = 'invoice';
897       $form->save_history;
898     }
899     # /saving the history
900     $form->{callback} = 'ir.pl?action=add';
901     $form->redirect(  $locale->text('Invoice')
902                   . " $form->{invnumber} "
903                   . ", " . $locale->text('ID')
904                   . ': ' . $form->{id} . ' '
905                   . $locale->text('posted!'));
906   }
907   $form->error($locale->text('Cannot post invoice!'));
908
909   $main::lxdebug->leave_sub();
910 }
911
912 sub delete {
913   $main::lxdebug->enter_sub();
914
915   my $form     = $main::form;
916   my $locale   = $main::locale;
917
918   $main::auth->assert('vendor_invoice_edit');
919
920   $form->header;
921   print qq|
922 <form method=post action=$form->{script}>
923 |;
924
925   # delete action variable
926   map { delete $form->{$_} } qw(action header);
927
928   foreach my $key (keys %$form) {
929     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
930     $form->{$key} =~ s/\"/&quot;/g;
931     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
932   }
933
934   print qq|
935 <h2 class=confirm>| . $locale->text('Confirm!') . qq|</h2>
936
937 <h4>|
938     . $locale->text('Are you sure you want to delete Invoice Number')
939     . qq| $form->{invnumber}</h4>
940 <p>
941 <input name=action class=submit type=submit value="|
942     . $locale->text('Yes') . qq|">
943 </form>
944 |;
945
946   $main::lxdebug->leave_sub();
947 }
948
949 sub display_form {
950   $::lxdebug->enter_sub;
951
952   $::auth->assert('vendor_invoice_edit');
953
954   relink_accounts();
955
956   my $new_rowcount = $::form->{"rowcount"} * 1 + 1;
957   $::form->{"project_id_${new_rowcount}"} = $::form->{"globalproject_id"};
958
959   $::form->language_payment(\%::myconfig);
960
961   Common::webdav_folder($::form);
962
963   form_header();
964   display_row(++$::form->{rowcount});
965   form_footer();
966
967   $::lxdebug->leave_sub;
968 }
969
970 sub yes {
971   $main::lxdebug->enter_sub();
972
973   my $form     = $main::form;
974   my %myconfig = %main::myconfig;
975   my $locale   = $main::locale;
976
977   $main::auth->assert('vendor_invoice_edit');
978
979   if (IR->delete_invoice(\%myconfig, \%$form)) {
980     # saving the history
981     if(!exists $form->{addition}) {
982       $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
983       $form->{addition} = "DELETED";
984       $form->save_history;
985     }
986     # /saving the history
987     $form->redirect($locale->text('Invoice deleted!'));
988   }
989   $form->error($locale->text('Cannot delete invoice!'));
990
991   $main::lxdebug->leave_sub();
992 }
993
994 sub get_duedate_vendor {
995   $::lxdebug->enter_sub;
996
997   my $result = IR->get_duedate(
998     vendor_id => $::form->{vendor_id},
999     invdate   => $::form->{invdate},
1000     default   => $::form->{old_duedate},
1001   );
1002
1003   print $::form->ajax_response_header, $result;
1004   $::lxdebug->leave_sub;
1005 }