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