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