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