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