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