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