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