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