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