ActionBar: Auslassen von Actions über Parameter »only_if«/»not_if« steuern können
[kivitendo-erp.git] / bin / mozilla / ir.pl
1 #=====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 # SQL-Ledger, Accounting
9 # Copyright (c) 1998-2002
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 #
16 # This program is free software; you can redistribute it and/or modify
17 # it under the terms of the GNU General Public License as published by
18 # the Free Software Foundation; either version 2 of the License, or
19 # (at your option) any later version.
20 #
21 # This program is distributed in the hope that it will be useful,
22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 # GNU General Public License for more details.
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
28 # MA 02110-1335, USA.
29 #======================================================================
30 #
31 # Inventory received module
32 #
33 #======================================================================
34
35 use SL::FU;
36 use SL::IR;
37 use SL::IS;
38 use SL::DB::Default;
39 use SL::DB::Department;
40 use SL::DB::PurchaseInvoice;
41 use SL::DB::Vendor;
42 use List::Util qw(max sum);
43 use List::UtilsBy qw(sort_by);
44
45 require "bin/mozilla/io.pl";
46 require "bin/mozilla/common.pl";
47
48 use strict;
49
50 1;
51
52 # end of main
53
54 sub add {
55   $main::lxdebug->enter_sub();
56
57   my $form     = $main::form;
58   my $locale   = $main::locale;
59
60   $main::auth->assert('vendor_invoice_edit');
61
62   if (!$::instance_conf->get_allow_new_purchase_invoice) {
63     $::form->show_generic_error($::locale->text("You do not have the permissions to access this function."));
64   }
65
66   $form->{show_details} = $::myconfig{show_form_details};
67
68   $form->{title} = $locale->text('Record Vendor Invoice');
69
70   &invoice_links;
71   &prepare_invoice;
72   &display_form;
73
74   $main::lxdebug->leave_sub();
75 }
76
77 sub edit {
78   $main::lxdebug->enter_sub();
79
80   my $form     = $main::form;
81   my $locale   = $main::locale;
82
83   $main::auth->assert('vendor_invoice_edit');
84
85   $form->{show_details} = $::myconfig{show_form_details};
86
87   # show history button
88   $form->{javascript} = qq|<script type=text/javascript src=js/show_history.js></script>|;
89   #/show hhistory button
90
91   $form->{title} = $locale->text('Edit Vendor Invoice');
92
93   &invoice_links;
94   &prepare_invoice;
95   &display_form;
96
97   $main::lxdebug->leave_sub();
98 }
99
100 sub invoice_links {
101   $main::lxdebug->enter_sub();
102
103   my $form     = $main::form;
104   my %myconfig = %main::myconfig;
105
106   $main::auth->assert('vendor_invoice_edit');
107
108   $form->{vc} = 'vendor';
109
110   # create links
111   $form->create_links("AP", \%myconfig, "vendor");
112
113   $form->backup_vars(qw(payment_id language_id taxzone_id
114                         currency delivery_term_id intnotes cp_id));
115
116   IR->get_vendor(\%myconfig, \%$form);
117   IR->retrieve_invoice(\%myconfig, \%$form);
118
119   $form->restore_vars(qw(payment_id language_id taxzone_id
120                          currency delivery_term_id intnotes cp_id));
121
122   my @curr = $form->get_all_currencies();
123   map { $form->{selectcurrency} .= "<option>$_\n" } @curr;
124
125   # forex
126   $form->{forex} = $form->{exchangerate};
127   my $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
128
129   foreach my $key (keys %{ $form->{AP_links} }) {
130
131     foreach my $ref (@{ $form->{AP_links}{$key} }) {
132       $form->{"select$key"} .= "<option>$ref->{accno}--$ref->{description}</option>";
133     }
134
135     next unless $form->{acc_trans}{$key};
136
137     if ($key eq "AP_paid") {
138       for my $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
139         $form->{"AP_paid_$i"} =
140           "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
141
142         $form->{"acc_trans_id_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
143         # reverse paid
144         $form->{"paid_$i"}     = $form->{acc_trans}{$key}->[$i - 1]->{amount};
145         $form->{"datepaid_$i"} =
146           $form->{acc_trans}{$key}->[$i - 1]->{transdate};
147         $form->{"gldate_$i"}   = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
148         $form->{"forex_$i"} = $form->{"exchangerate_$i"} =
149           $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
150         $form->{"source_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{source};
151         $form->{"memo_$i"}   = $form->{acc_trans}{$key}->[$i - 1]->{memo};
152
153         $form->{paidaccounts} = $i;
154       }
155     } else {
156       $form->{$key} =
157         "$form->{acc_trans}{$key}->[0]->{accno}--$form->{acc_trans}{$key}->[0]->{description}";
158     }
159
160   }
161
162   $form->{paidaccounts} = 1 unless (exists $form->{paidaccounts});
163
164   $form->{AP} = $form->{AP_1} unless $form->{id};
165
166   $form->{locked} =
167     ($form->datetonum($form->{invdate}, \%myconfig) <=
168      $form->datetonum($form->{closedto}, \%myconfig));
169
170   $main::lxdebug->leave_sub();
171 }
172
173 sub prepare_invoice {
174   $main::lxdebug->enter_sub();
175
176   my $form     = $main::form;
177   my %myconfig = %main::myconfig;
178
179   $main::auth->assert('vendor_invoice_edit');
180
181   $form->{type}     = "purchase_invoice";
182
183   if ($form->{id}) {
184
185     map { $form->{$_} =~ s/\"/&quot;/g } qw(invnumber ordnumber quonumber);
186
187     my $i = 0;
188     foreach my $ref (@{ $form->{invoice_details} }) {
189       $i++;
190       map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
191       # übernommen aus is.pl Fix für Bug 1642. Nebenwirkungen? jb 12.5.2011
192       # getestet: Lieferantenauftrag -> Rechnung i.O.
193       #           Lieferantenauftrag -> Lieferschein -> Rechnung i.O.
194       # Werte: 20% (Lieferantenrabatt), 12,4% individuell und 0,4 individuell s.a.
195       # Screenshot zu Bug 1642
196       $form->{"discount_$i"}   = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100);
197
198       my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
199       $dec           = length $dec;
200       my $decimalplaces = ($dec > 2) ? $dec : 2;
201
202       $form->{"sellprice_$i"} =
203         $form->format_amount(\%myconfig, $form->{"sellprice_$i"},
204                              $decimalplaces);
205
206       (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
207       $dec_qty = length $dec_qty;
208
209       $form->{"qty_$i"} =
210         $form->format_amount(\%myconfig, ($form->{"qty_$i"} * -1), $dec_qty);
211
212       $form->{rowcount} = $i;
213     }
214   }
215
216   $main::lxdebug->leave_sub();
217 }
218
219 sub setup_ir_action_bar {
220   my $form                    = $::form;
221   my $change_never            = $::instance_conf->get_ir_changeable == 0;
222   my $change_on_same_day_only = $::instance_conf->get_ir_changeable == 2 && ($form->current_date(\%::myconfig) ne $form->{gldate});
223
224   for my $bar ($::request->layout->get('actionbar')) {
225     $bar->add(
226       action => [
227         t8('Update'),
228         submit    => [ '#form', { action => "update" } ],
229         id        => 'update_button',
230         accesskey => 'enter',
231       ],
232
233       combobox => [
234         action => [
235           t8('Post'),
236           submit   => [ '#form', { action => "post" } ],
237           disabled => $form->{locked}                           ? t8('The billing period has already been locked.')
238                     : $form->{storno}                           ? t8('A canceled invoice cannot be posted.')
239                     : ($form->{id} && $change_never)            ? t8('Changing invoices has been disabled in the configuration.')
240                     : ($form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
241                     :                                             undef,
242         ],
243         action => [
244           t8('Post Payment'),
245           submit   => [ '#form', { action => "post_payment" } ],
246           disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
247         ],
248         action => [
249           t8('Mark as paid'),
250           submit   => [ '#form', { action => "mark_as_paid" } ],
251           confirm  => t8('This will remove the invoice from showing as unpaid even if the unpaid amount does not match the amount. Proceed?'),
252           disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
253           only_if  => $::instance_conf->get_ir_show_mark_as_paid,
254         ],
255       ], # end of combobox "Post"
256
257       combobox => [
258         action => [ t8('Storno'),
259           submit   => [ '#form', { action => "storno" } ],
260           confirm  => t8('Do you really want to cancel this invoice?'),
261           disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
262         ],
263         action => [ t8('Delete'),
264           submit   => [ '#form', { action => "delete" } ],
265           confirm  => t8('Do you really want to delete this object?'),
266           disabled => !$form->{id}             ? t8('This invoice has not been posted yet.')
267                     : $form->{locked}          ? t8('The billing period has already been locked.')
268                     : $change_never            ? t8('Changing invoices has been disabled in the configuration.')
269                     : $change_on_same_day_only ? t8('Invoices can only be changed on the day they are posted.')
270                     :                            undef,
271         ],
272       ], # end of combobox "Storno"
273
274       'separator',
275
276       combobox => [
277         action => [ t8('more') ],
278         action => [
279           t8('History'),
280           call     => [ 'set_history_window', $::form->{id} * 1, 'id', 'glid' ],
281           disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
282         ],
283         action => [
284           t8('Follow-Up'),
285           call     => [ 'follow_up_window' ],
286           disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
287         ],
288         action => [
289           t8('Drafts'),
290           call     => [ 'kivi.Draft.popup', 'ir', 'invoice', $::form->{draft_id}, $::form->{draft_description} ],
291           disabled => $form->{id}     ? t8('This invoice has already been posted.')
292                     : $form->{locked} ? t8('The billing period has already been locked.')
293                     :                   undef,
294         ],
295       ], # end of combobox "more"
296     );
297   }
298 }
299
300 sub form_header {
301   $main::lxdebug->enter_sub();
302
303   my $form     = $main::form;
304   my %myconfig = %main::myconfig;
305   my $locale   = $main::locale;
306   my $cgi      = $::request->{cgi};
307
308   $main::auth->assert('vendor_invoice_edit');
309
310   my %TMPL_VAR = ();
311   my @custom_hiddens;
312
313   $TMPL_VAR{invoice_obj} = SL::DB::PurchaseInvoice->load_cached($form->{id}) if $form->{id};
314   $TMPL_VAR{vendor_obj}  = SL::DB::Vendor->load_cached($form->{vendor_id})   if $form->{vendor_id};
315   $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
316   $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
317
318   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
319
320   my @old_project_ids = ($form->{"globalproject_id"});
321   map { push @old_project_ids, $form->{"project_id_$_"} if $form->{"project_id_$_"}; } 1..$form->{"rowcount"};
322
323   $form->get_lists("taxzones"      => ($form->{id} ? "ALL_TAXZONES" : "ALL_ACTIVE_TAXZONES"),
324                    "currencies"    => "ALL_CURRENCIES",
325                    "price_factors" => "ALL_PRICE_FACTORS");
326
327   $TMPL_VAR{ALL_DEPARTMENTS}       = SL::DB::Manager::Department->get_all_sorted;
328   $TMPL_VAR{ALL_EMPLOYEES}         = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{employee_id},  deleted => 0 ] ]);
329   $TMPL_VAR{ALL_CONTACTS}          = SL::DB::Manager::Contact->get_all_sorted(query => [
330     or => [
331       cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
332       and      => [
333         cp_cv_id => undef,
334         cp_id    => $::form->{cp_id} * 1
335       ]
336     ]
337   ]);
338
339   # currencies and exchangerate
340   my @values = map { $_       } @{ $form->{ALL_CURRENCIES} };
341   my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
342   $form->{currency}            = $form->{defaultcurrency} unless $form->{currency};
343   # show_exchangerate is also later needed in another template
344   $form->{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
345   $TMPL_VAR{currencies}        = NTI($cgi->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
346                                                       '-values' => \@values, '-labels' => \%labels,
347                                                       '-onchange' => "document.getElementById('update_button').click();"
348                                      )) if scalar @values;
349   push @custom_hiddens, "forex";
350   push @custom_hiddens, "exchangerate" if $form->{forex};
351
352   $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
353   $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
354
355 # set option selected
356   foreach my $item (qw(AP)) {
357     $form->{"select$item"} =~ s/ selected//;
358     $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
359   }
360
361   $TMPL_VAR{is_type_credit_note} = $form->{type}   eq "credit_note";
362   $TMPL_VAR{is_format_html}      = $form->{format} eq 'html';
363   $TMPL_VAR{dateformat}          = $myconfig{dateformat};
364   $TMPL_VAR{numberformat}        = $myconfig{numberformat};
365
366   # hiddens
367   $TMPL_VAR{HIDDENS} = [qw(
368     id type queued printed emailed title vc discount
369     title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
370     max_dunning_level dunning_amount
371     shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptogln shiptocontact shiptophone shiptofax
372     shiptoemail shiptodepartment_1 shiptodepartment_2 message email subject cc bcc taxaccounts cursor_fokus
373     convert_from_do_ids convert_from_oe_ids convert_from_ap_ids show_details gldate useasnew
374   ), @custom_hiddens,
375   map { $_.'_rate', $_.'_description', $_.'_taxnumber' } split / /, $form->{taxaccounts}];
376
377   $TMPL_VAR{payment_terms_obj} = get_payment_terms_for_invoice();
378   $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};
379
380   $::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));
381
382   setup_ir_action_bar();
383
384   $form->header();
385
386   print $form->parse_html_template("ir/form_header", \%TMPL_VAR);
387
388   $main::lxdebug->leave_sub();
389 }
390
391 sub _sort_payments {
392   my @fields   = qw(acc_trans_id gldate datepaid source memo paid AP_paid);
393   my @payments =
394     grep { $_->{paid} != 0 }
395     map  {
396       my $idx = $_;
397       +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
398     } (1..$::form->{paidaccounts});
399
400   @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
401
402   $::form->{paidaccounts} = max scalar(@payments), 1;
403
404   foreach my $idx (1 .. scalar(@payments)) {
405     my $payment = $payments[$idx - 1];
406     $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
407   }
408 }
409
410 sub form_footer {
411   $main::lxdebug->enter_sub();
412
413   my $form     = $main::form;
414   my %myconfig = %main::myconfig;
415   my $locale   = $main::locale;
416
417   $main::auth->assert('vendor_invoice_edit');
418
419   $form->{invtotal}    = $form->{invsubtotal};
420   $form->{oldinvtotal} = $form->{invtotal};
421
422   # note rows
423   $form->{rows} = max 2,
424     $form->numtextrows($form->{notes},    26, 8),
425     $form->numtextrows($form->{intnotes}, 35, 8);
426
427
428   # tax, total and subtotal calculations
429   my ($tax, $subtotal);
430   $form->{taxaccounts_array} = [ split / /, $form->{taxaccounts} ];
431
432   foreach my $item (@{ $form->{taxaccounts_array} }) {
433     if ($form->{"${item}_base"}) {
434       if ($form->{taxincluded}) {
435         $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
436                                                                                  / (1 + $form->{"${item}_rate"})), 2);
437         $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
438       } else {
439         $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
440         $form->{invtotal} += $form->{"${item}_total"};
441       }
442     }
443   }
444
445   # follow ups
446   if ($form->{id}) {
447     $form->{follow_ups}            = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1) || [];
448     $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
449   }
450
451   # payments
452   _sort_payments();
453
454   my $totalpaid = 0;
455   $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
456   $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
457
458   # Standard Konto für Umlaufvermögen
459   my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
460
461   for my $i (1 .. $form->{paidaccounts}) {
462     $form->{"changeable_$i"} = 1;
463     if (SL::DB::Default->get->payments_changeable == 0) {
464       # never
465       $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
466     } elsif (SL::DB::Default->get->payments_changeable == 2) {
467       # on the same day
468       $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
469                                   ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
470     }
471
472     $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
473       if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
474
475     #deaktivieren von Zahlungen ausserhalb der Bücherkontrolle
476     if ($form->date_closed($form->{"gldate_$i"})) {
477       $form->{"changeable_$i"} = 0;
478     }
479
480     $form->{"selectAP_paid_$i"} = $form->{selectAP_paid};
481     if (!$form->{"AP_paid_$i"}) {
482       $form->{"selectAP_paid_$i"} =~ s/option>$accno_arap--(.*?)>/option selected>$accno_arap--$1>/;
483     } else {
484       $form->{"selectAP_paid_$i"} =~ s/option>\Q$form->{"AP_paid_$i"}\E/option selected>$form->{"AP_paid_$i"}/;
485     }
486
487     $totalpaid += $form->{"paid_$i"};
488   }
489
490   $form->{ALL_DELIVERY_TERMS} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
491
492   print $form->parse_html_template('ir/form_footer', {
493     is_type_credit_note => ($form->{type} eq "credit_note"),
494     totalpaid           => $totalpaid,
495     paid_missing        => $form->{invtotal} - $totalpaid,
496     show_storno         => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ap") && !$totalpaid,
497     show_delete         => ($::instance_conf->get_ir_changeable == 2)
498                              ? ($form->current_date(\%myconfig) eq $form->{gldate})
499                              : ($::instance_conf->get_ir_changeable == 1),
500     today               => DateTime->today,
501   });
502 ##print $form->parse_html_template('ir/_payments'); # parser
503 ##print $form->parse_html_template('webdav/_list'); # parser
504
505   $main::lxdebug->leave_sub();
506 }
507
508 sub mark_as_paid {
509   $::auth->assert('vendor_invoice_edit');
510
511   SL::DB::PurchaseInvoice->new(id => $::form->{id})->load->mark_as_paid;
512
513   $::form->redirect($::locale->text("Marked as paid"));
514 }
515
516 sub show_draft {
517   update();
518 }
519
520 sub update {
521   $main::lxdebug->enter_sub();
522
523   my $form     = $main::form;
524   my %myconfig = %main::myconfig;
525
526   $main::auth->assert('vendor_invoice_edit');
527
528   if (($form->{previous_vendor_id} || $form->{vendor_id}) != $form->{vendor_id}) {
529     IR->get_vendor(\%myconfig, $form);
530   }
531
532   if (!$form->{forex}) {        # read exchangerate from input field (not hidden)
533     $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate});
534   }
535   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'sell');
536   $form->{exchangerate} = $form->{forex} if $form->{forex};
537
538   for my $i (1 .. $form->{paidaccounts}) {
539     next unless $form->{"paid_$i"};
540     map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
541     $form->{"forex_$i"}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
542     $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
543   }
544
545   my $i            = $form->{rowcount};
546   my $exchangerate = ($form->{exchangerate} * 1) || 1;
547
548   if (   ($form->{"partnumber_$i"} eq "")
549       && ($form->{"description_$i"} eq "")
550       && ($form->{"partsgroup_$i"} eq "")) {
551     $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
552     &check_form;
553
554   } else {
555
556     IR->retrieve_item(\%myconfig, \%$form);
557
558     my $rows = scalar @{ $form->{item_list} };
559
560     $form->{"discount_$i"}   = $form->parse_amount(\%myconfig, $form->{"discount_$i"}) / 100.0;
561     $form->{"discount_$i"} ||= $form->{vendor_discount};
562
563     if ($rows) {
564       $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
565       if( !$form->{"qty_$i"} ) {
566         $form->{"qty_$i"} = 1;
567       }
568
569       if ($rows > 1) {
570
571         select_item(mode => 'IR', pre_entered_qty => $form->{"qty_$i"});
572         $::dispatcher->end_request;
573
574       } else {
575
576         # override sellprice if there is one entered
577         my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
578
579         map { $form->{item_list}[$i]{$_} =~ s/\"/&quot;/g } qw(partnumber description unit);
580         map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
581
582         $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
583
584         ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
585         my $dec_qty       = length $1;
586         my $decimalplaces = max 2, $dec_qty;
587
588         if ($sellprice) {
589           $form->{"sellprice_$i"} = $sellprice;
590         } else {
591           my $record        = _make_record();
592           my $price_source  = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
593           my $best_price    = $price_source->best_price;
594           my $best_discount = $price_source->best_discount;
595
596           if ($best_price) {
597             $::form->{"sellprice_$i"}           = $best_price->price;
598             $::form->{"active_price_source_$i"} = $best_price->source;
599           }
600           if ($best_discount) {
601             $::form->{"discount_$i"}               = $best_discount->discount;
602             $::form->{"active_discount_source_$i"} = $best_discount->source;
603           }
604
605           # if there is an exchange rate adjust sellprice
606           $form->{"sellprice_$i"} /= $exchangerate;
607         }
608
609         my $amount                = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"});
610         $form->{creditremaining} -= $amount;
611         $form->{"sellprice_$i"}   = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
612         $form->{"qty_$i"}         = $form->format_amount(\%myconfig, $form->{"qty_$i"},       $dec_qty);
613         $form->{"discount_$i"}    = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
614       }
615
616       &display_form;
617
618     } else {
619
620       # ok, so this is a new part
621       # ask if it is a part or service item
622
623       if (   $form->{"partsgroup_$i"}
624           && ($form->{"partsnumber_$i"} eq "")
625           && ($form->{"description_$i"} eq "")) {
626         $form->{rowcount}--;
627         $form->{"discount_$i"} = "";
628         display_form();
629
630       } else {
631         $form->{"id_$i"}   = 0;
632         new_item();
633       }
634     }
635   }
636   $main::lxdebug->leave_sub();
637 }
638
639 sub storno {
640   $main::lxdebug->enter_sub();
641
642   my $form     = $main::form;
643   my %myconfig = %main::myconfig;
644   my $locale   = $main::locale;
645
646   $main::auth->assert('vendor_invoice_edit');
647
648   if ($form->{storno}) {
649     $form->error($locale->text('Cannot storno storno invoice!'));
650   }
651
652   if (IS->has_storno(\%myconfig, $form, "ap")) {
653     $form->error($locale->text("Invoice has already been storno'd!"));
654   }
655
656   $form->error($locale->text('Cannot post storno for a closed period!'))
657     if ( $form->date_closed($form->{invdate}, \%myconfig));
658
659   my $employee_id = $form->{employee_id};
660   invoice_links();
661   prepare_invoice();
662   relink_accounts();
663
664   # Payments must not be recorded for the new storno invoice.
665   $form->{paidaccounts} = 0;
666   map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
667   # set new ids for storno invoice
668   # set new persistent ids for storno invoice items
669   $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
670
671   # saving the history
672   if(!exists $form->{addition} && $form->{id} ne "") {
673     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
674     $form->{what_done} = "invoice";
675     $form->{addition}  = "CANCELED";
676     $form->save_history;
677   }
678   # /saving the history
679
680   # record link invoice to storno
681   $form->{convert_from_ap_ids} = $form->{id};
682   $form->{storno_id} = $form->{id};
683   $form->{storno} = 1;
684   $form->{id} = "";
685   $form->{invnumber} = "Storno zu " . $form->{invnumber};
686   $form->{rowcount}++;
687   $form->{employee_id} = $employee_id;
688   post();
689   $main::lxdebug->leave_sub();
690
691 }
692
693 sub use_as_new {
694   $main::lxdebug->enter_sub();
695
696   my $form     = $main::form;
697   my %myconfig = %main::myconfig;
698
699   $main::auth->assert('vendor_invoice_edit');
700
701   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);
702   $form->{paidaccounts} = 1;
703   $form->{rowcount}--;
704   $form->{invdate} = $form->current_date(\%myconfig);
705
706   $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
707
708   $form->{useasnew} = 1;
709   &display_form;
710
711   $main::lxdebug->leave_sub();
712 }
713
714 sub post_payment {
715   $main::lxdebug->enter_sub();
716
717   my $form     = $main::form;
718   my %myconfig = %main::myconfig;
719   my $locale   = $main::locale;
720
721   $main::auth->assert('vendor_invoice_edit');
722
723   $form->mtime_ischanged('ap') ;
724   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
725   for my $i (1 .. $form->{paidaccounts}) {
726     if ($form->{"paid_$i"}) {
727       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
728
729       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
730
731       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
732         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
733
734       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
735       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
736       $form->error($locale->text('Cannot post payment for a closed period!'))
737         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
738
739       if ($form->{currency} ne $form->{defaultcurrency}) {
740 #        $form->{"exchangerate_$i"} = $form->{exchangerate} if ($invdate == $datepaid); # invdate isn't set here
741         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
742       }
743     }
744   }
745
746   ($form->{AP})      = split /--/, $form->{AP};
747   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
748   if (IR->post_payment(\%myconfig, \%$form)){
749     if (!exists $form->{addition} && $form->{id} ne "") {
750       # saving the history
751       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
752       $form->{addition}  = "PAYMENT POSTED";
753       $form->{what_done} = "invoice";
754       $form->save_history;
755       # /saving the history
756     }
757
758     $form->redirect($locale->text('Payment posted!'));
759   }
760
761   $form->error($locale->text('Cannot post payment!'));
762
763   $main::lxdebug->leave_sub();
764 }
765
766 sub _max_datepaid {
767   my $form  =  $main::form;
768
769   my @dates = sort { $b->[1] cmp $a->[1] }
770               map  { [ $_, $main::locale->reformat_date(\%main::myconfig, $_, 'yyyy-mm-dd') ] }
771               grep { $_ }
772               map  { $form->{"datepaid_${_}"} }
773               (1..$form->{rowcount});
774
775   return @dates ? $dates[0]->[0] : undef;
776 }
777
778
779 sub post {
780   $main::lxdebug->enter_sub();
781
782   my $form     = $main::form;
783   my %myconfig = %main::myconfig;
784   my $locale   = $main::locale;
785
786   $main::auth->assert('vendor_invoice_edit');
787
788   $form->mtime_ischanged('ap');
789   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
790
791   $form->isblank("invdate",   $locale->text('Invoice Date missing!'));
792   $form->isblank("vendor_id", $locale->text('Vendor missing!'));
793   $form->isblank("invnumber", $locale->text('Invnumber missing!'));
794
795   $form->{invnumber} =~ s/^\s*//g;
796   $form->{invnumber} =~ s/\s*$//g;
797
798   # if the vendor changed get new values
799   if (($form->{previous_vendor_id} || $form->{vendor_id}) != $form->{vendor_id}) {
800     &update;
801     $::dispatcher->end_request;
802   }
803
804   if ($myconfig{mandatory_departments} && !$form->{department_id}) {
805     $form->{saved_message} = $::locale->text('You have to specify a department.');
806     update();
807     exit;
808   }
809
810   remove_emptied_rows();
811   &validate_items;
812
813   my $closedto     = $form->datetonum($form->{closedto}, \%myconfig);
814   my $invdate      = $form->datetonum($form->{invdate},  \%myconfig);
815   my $max_datepaid = _max_datepaid();
816
817   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
818     if ($form->date_max_future($invdate, \%myconfig));
819   $form->error($locale->text('Cannot post invoice for a closed period!'))
820     if ($invdate <= $closedto);
821
822   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
823     if ($form->{currency} ne $form->{defaultcurrency});
824
825   my $i;
826   for $i (1 .. $form->{paidaccounts}) {
827     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
828       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
829
830       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
831
832       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
833         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
834
835       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
836       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
837       $form->error($locale->text('Cannot post payment for a closed period!'))
838         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
839
840       if ($form->{currency} ne $form->{defaultcurrency}) {
841         $form->{"exchangerate_$i"} = $form->{exchangerate}
842           if ($invdate == $datepaid);
843         $form->isblank("exchangerate_$i",
844                        $locale->text('Exchangerate for payment missing!'));
845       }
846     }
847   }
848
849   ($form->{AP})      = split /--/, $form->{AP};
850   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
851   $form->{storno}  ||= 0;
852
853   $form->{id} = 0 if $form->{postasnew};
854
855
856   relink_accounts();
857   if (IR->post_invoice(\%myconfig, \%$form)){
858     # saving the history
859     if(!exists $form->{addition} && $form->{id} ne "") {
860       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
861       $form->{addition}  = "POSTED";
862       $form->{what_done} = 'invoice';
863       $form->save_history;
864     }
865     # /saving the history
866     $form->{callback} = 'ir.pl?action=add';
867     $form->redirect(  $locale->text('Invoice')
868                   . " $form->{invnumber} "
869                   . $locale->text('posted!'));
870   }
871   $form->error($locale->text('Cannot post invoice!'));
872
873   $main::lxdebug->leave_sub();
874 }
875
876 sub delete {
877   $main::lxdebug->enter_sub();
878
879   my $form     = $main::form;
880   my $locale   = $main::locale;
881
882   $main::auth->assert('vendor_invoice_edit');
883
884   $form->header;
885   print qq|
886 <form method=post action=$form->{script}>
887 |;
888
889   # delete action variable
890   map { delete $form->{$_} } qw(action header);
891
892   foreach my $key (keys %$form) {
893     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
894     $form->{$key} =~ s/\"/&quot;/g;
895     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
896   }
897
898   print qq|
899 <h2 class=confirm>| . $locale->text('Confirm!') . qq|</h2>
900
901 <h4>|
902     . $locale->text('Are you sure you want to delete Invoice Number')
903     . qq| $form->{invnumber}</h4>
904 <p>
905 <input name=action class=submit type=submit value="|
906     . $locale->text('Yes') . qq|">
907 </form>
908 |;
909
910   $main::lxdebug->leave_sub();
911 }
912
913 sub display_form {
914   $::lxdebug->enter_sub;
915
916   $::auth->assert('vendor_invoice_edit');
917
918   relink_accounts();
919
920   my $new_rowcount = $::form->{"rowcount"} * 1 + 1;
921   $::form->{"project_id_${new_rowcount}"} = $::form->{"globalproject_id"};
922
923   $::form->language_payment(\%::myconfig);
924
925   Common::webdav_folder($::form);
926
927   form_header();
928   display_row(++$::form->{rowcount});
929   form_footer();
930
931   $::lxdebug->leave_sub;
932 }
933
934 sub yes {
935   $main::lxdebug->enter_sub();
936
937   my $form     = $main::form;
938   my %myconfig = %main::myconfig;
939   my $locale   = $main::locale;
940
941   $main::auth->assert('vendor_invoice_edit');
942
943   if (IR->delete_invoice(\%myconfig, \%$form)) {
944     # saving the history
945     if(!exists $form->{addition}) {
946       $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
947       $form->{addition} = "DELETED";
948       $form->save_history;
949     }
950     # /saving the history
951     $form->redirect($locale->text('Invoice deleted!'));
952   }
953   $form->error($locale->text('Cannot delete invoice!'));
954
955   $main::lxdebug->leave_sub();
956 }
957
958 sub get_duedate_vendor {
959   $::lxdebug->enter_sub;
960
961   my $result = IR->get_duedate(
962     vendor_id => $::form->{vendor_id},
963     invdate   => $::form->{invdate},
964     default   => $::form->{old_duedate},
965   );
966
967   print $::form->ajax_response_header, $result;
968   $::lxdebug->leave_sub;
969 }