]> wagnertech.de Git - mfinanz.git/blob - bin/mozilla/is.pl
restart apache2 in postinst
[mfinanz.git] / bin / mozilla / is.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 invoicing module
32 #
33 #======================================================================
34
35 use SL::FU;
36 use SL::IS;
37 use SL::OE;
38 use SL::Helper::UserPreferences::DisplayPreferences;
39 use SL::MoreCommon qw(restore_form save_form);
40 use SL::RecordLinks;
41
42 use Data::Dumper;
43 use DateTime;
44 use List::MoreUtils qw(any uniq);
45 use List::Util qw(max sum);
46 use List::UtilsBy qw(sort_by);
47 use English qw(-no_match_vars);
48
49 use SL::DB::BankTransactionAccTrans;
50 use SL::DB::Default;
51 use SL::DB::Chart;
52 use SL::DB::Customer;
53 use SL::DB::Department;
54 use SL::DB::Invoice;
55 use SL::DB::PaymentTerm;
56 use SL::DB::Reclamation;
57 use SL::DB::EmailJournal;
58 use SL::DB::ValidityToken;
59 use SL::Helper::QrBillFunctions qw(get_ref_number_formatted);
60
61 require "bin/mozilla/common.pl";
62 require "bin/mozilla/io.pl";
63
64 use strict;
65
66 1;
67
68 # end of main
69
70 sub _may_view_or_edit_this_invoice {
71   return 1 if  $::auth->assert('invoice_edit', 1);       # may edit all invoices
72   return 0 if !$::form->{id};                            # creating new invoices isn't allowed without invoice_edit
73   return 1 if  $::auth->assert('sales_invoice_view', 1); # viewing is allowed with this right
74   return 0 if !$::form->{globalproject_id};              # existing records without a project ID are not allowed
75   return SL::DB::Project->new(id => $::form->{globalproject_id})->load->may_employee_view_project_invoices(SL::DB::Manager::Employee->current);
76 }
77
78 sub _assert_access {
79   my $cache = $::request->cache('is.pl::_assert_access');
80
81   $cache->{_may_view_or_edit_this_invoice} = _may_view_or_edit_this_invoice()                              if !exists $cache->{_may_view_or_edit_this_invoice};
82   $::form->show_generic_error($::locale->text("You do not have the permissions to access this function.")) if !       $cache->{_may_view_or_edit_this_invoice};
83 }
84
85 sub add {
86   $main::lxdebug->enter_sub();
87
88   my $form     = $main::form;
89   my $locale   = $main::locale;
90
91   $main::auth->assert('invoice_edit');
92
93   $form->{show_details} = $::myconfig{show_form_details};
94
95   if ($form->{type} eq "credit_note") {
96     $form->{title} = $locale->text('Add Credit Note');
97
98     if ($form->{storno}) {
99       $form->{title} = $locale->text('Add Storno Credit Note');
100     }
101
102   } elsif ($form->{type} eq "invoice_for_advance_payment") {
103     $form->{title} = $locale->text('Add Invoice for Advance Payment');
104
105   } elsif ($form->{type} eq "final_invoice") {
106     $form->{title} = $locale->text('Add Final Invoice');
107
108   } else {
109     $form->{title} = $locale->text('Add Sales Invoice');
110
111   }
112
113   if (!$form->{form_validity_token}) {
114     $form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_SALES_INVOICE_POST())->token;
115   }
116
117   $form->{callback} = "$form->{script}?action=add&type=$form->{type}" unless $form->{callback};
118
119   invoice_links(is_new => 1);
120   &prepare_invoice;
121   &display_form;
122
123   $main::lxdebug->leave_sub();
124 }
125
126 sub add_from_email_journal {
127   die "No 'email_journal_id' was given." unless ($::form->{email_journal_id});
128   &add;
129 }
130
131 sub edit_with_email_journal_workflow {
132   my ($self) = @_;
133   die "No 'email_journal_id' was given." unless ($::form->{email_journal_id});
134   $::form->{workflow_email_journal_id}    = delete $::form->{email_journal_id};
135   $::form->{workflow_email_attachment_id} = delete $::form->{email_attachment_id};
136   $::form->{workflow_email_callback}      = delete $::form->{callback};
137
138   &edit;
139 }
140
141 sub edit {
142   $main::lxdebug->enter_sub();
143
144   # Delay access check to after the invoice's been loaded in
145   # "invoice_links" so that project-specific invoice rights can be
146   # evaluated.
147
148   my $form     = $main::form;
149   my $locale   = $main::locale;
150
151   $form->{show_details}                = $::myconfig{show_form_details};
152   $form->{taxincluded_changed_by_user} = 1;
153
154   # show history button
155   $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
156
157   my ($language_id, $printer_id);
158   if ($form->{print_and_post}) {
159     $form->{action}   = "print";
160     $form->{resubmit} = 1;
161     $language_id = $form->{language_id};
162     $printer_id = $form->{printer_id};
163   }
164
165   &invoice_links;
166   if ($form->{type} eq "credit_note") {
167     $form->{title} = $locale->text('Edit Credit Note');
168     $form->{title} = $locale->text('Edit Storno Credit Note') if $form->{storno};
169
170   } elsif ($form->{type} eq "invoice_for_advance_payment") {
171     $form->{title} = $locale->text('Edit Invoice for Advance Payment');
172     $form->{title} = $locale->text('Edit Storno Invoice for Advance Payment') if $form->{storno};
173
174   } elsif ($form->{type} eq "final_invoice") {
175     $form->{title} = $locale->text('Edit Final Invoice');
176
177   } else {
178     $form->{title} = $locale->text('Edit Sales Invoice');
179     $form->{title} = $locale->text('Edit Storno Invoice')     if $form->{storno};
180   }
181
182   &prepare_invoice;
183   if ($form->{print_and_post}) {
184     $form->{language_id} = $language_id;
185     $form->{printer_id} = $printer_id;
186   }
187
188   &display_form;
189
190   $main::lxdebug->leave_sub();
191 }
192
193 sub invoice_links {
194   $main::lxdebug->enter_sub();
195
196   # Delay access check to after the invoice's been loaded so that
197   # project-specific invoice rights can be evaluated.
198
199   my %params   = @_;
200   my $form     = $main::form;
201   my %myconfig = %main::myconfig;
202
203   $form->{vc} = 'customer';
204
205   # create links
206   $form->create_links("AR", \%myconfig, "customer");
207
208   my $transfer_chart_id = $::instance_conf->get_advance_payment_clearing_chart_id;
209   if ($transfer_chart_id) {
210     # remove transfer chart for select box AR
211     @{ $form->{AR_links}{AR} } =  grep { $_->{chart_id} != $transfer_chart_id } @{ $form->{AR_links}{AR} };
212   }
213
214   _assert_access();
215
216   my $editing = $form->{id};
217
218   $form->backup_vars(qw(payment_id language_id taxzone_id salesman_id
219                         taxincluded currency cp_id intnotes id shipto_id
220                         delivery_term_id));
221
222   IS->get_customer(\%myconfig, \%$form);
223
224   $form->{billing_address_id} = $form->{default_billing_address_id} if $params{is_new};
225
226   $form->restore_vars(qw(id));
227
228   IS->retrieve_invoice(\%myconfig, \%$form);
229   $form->restore_vars(qw(payment_id language_id taxzone_id currency intnotes
230                          cp_id shipto_id delivery_term_id));
231   $form->restore_vars(qw(taxincluded)) if $form->{id};
232   $form->restore_vars(qw(salesman_id)) if $editing;
233
234   $form->{employee} = "$form->{employee}--$form->{employee_id}";
235
236   # forex
237   $form->{forex} = $form->{exchangerate};
238   my $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
239
240   foreach my $key (keys %{ $form->{AR_links} }) {
241     foreach my $ref (@{ $form->{AR_links}{$key} }) {
242       $form->{"select$key"} .= "<option>$ref->{accno}--$ref->{description}</option>\n";
243     }
244
245     if ($key eq "AR_paid") {
246       next unless $form->{acc_trans}{$key};
247       for my $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
248         $form->{"AR_paid_$i"}      = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
249
250         $form->{"acc_trans_id_$i"}    = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
251         # reverse paid
252         $form->{"paid_$i"}         = $form->{acc_trans}{$key}->[$i - 1]->{amount} * -1;
253         $form->{"datepaid_$i"}     = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
254         $form->{"gldate_$i"}       = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
255         $form->{"exchangerate_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
256         $form->{"forex_$i"}        = $form->{"exchangerate_$i"};
257         $form->{"source_$i"}       = $form->{acc_trans}{$key}->[$i - 1]->{source};
258         $form->{"memo_$i"}         = $form->{acc_trans}{$key}->[$i - 1]->{memo};
259         $form->{"defaultcurrency_paid_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{defaultcurrency_paid};
260         $form->{"fx_transaction_$i"}  = $form->{acc_trans}{$key}->[$i - 1]->{fx_transaction};
261
262
263         $form->{paidaccounts} = $i;
264         # hook for calc of of defaultcurrency_paid and check if banktransaction has a record exchangerate
265         if ($form->{"exchangerate_$i"} && $form->{"acc_trans_id_$i"}) {
266           my $bt_acc_trans = SL::DB::Manager::BankTransactionAccTrans->find_by(acc_trans_id => $form->{"acc_trans_id_$i"});
267           if ($bt_acc_trans) {
268             if ($bt_acc_trans->bank_transaction->exchangerate > 0) {
269               $form->{"exchangerate_$i"} = $bt_acc_trans->bank_transaction->exchangerate;
270               $form->{"forex_$i"}        = $form->{"exchangerate_$i"};
271               $form->{"record_forex_$i"} = 1;
272             }
273           }
274           if (!$form->{"fx_transaction_$i"}) {
275             # this is a banktransaction that was paid in internal currency. revert paid/defaultcurrency_paid
276             $form->{"defaultcurrency_paid_$i"} = $form->{"paid_$i"};
277             $form->{"paid_$i"} /= $form->{"exchangerate_$i"};
278           }
279           $form->{"defaultcurrency_paid_$i"} //= $form->{"paid_$i"} * $form->{"exchangerate_$i"};
280           $form->{"defaultcurrency_totalpaid"} +=  $form->{"defaultcurrency_paid_$i"};
281         } # end hook defaultcurrency_paid
282
283       }
284     } else {
285       $form->{$key} = "$form->{acc_trans}{$key}->[0]->{accno}--$form->{acc_trans}{$key}->[0]->{description}";
286     }
287   }
288
289   $form->{paidaccounts} = 1 unless (exists $form->{paidaccounts});
290
291   my ($chart_accno) = split /--/, $form->{AR}; # is empty if total is 0
292   $form->{AR_chart_id} = $form->{id} && $chart_accno ? SL::DB::Manager::Chart->find_by(accno => $chart_accno)->id
293                        : $form->{AR_chart_id}        ? $form->{AR_chart_id}
294                        : $::instance_conf->get_ar_chart_id;
295
296   $form->{locked} = ($form->datetonum($form->{invdate},  \%myconfig)
297                   <= $form->datetonum($form->{closedto}, \%myconfig));
298
299   $main::lxdebug->leave_sub();
300 }
301
302 sub prepare_invoice {
303   $main::lxdebug->enter_sub();
304
305   _assert_access();
306
307   my $form     = $main::form;
308   my %myconfig = %main::myconfig;
309
310   if ($form->{type} eq "credit_note") {
311     $form->{type}     = "credit_note";
312     $form->{formname} = "credit_note";
313
314   } elsif ($form->{type} eq "invoice_for_advance_payment") {
315     $form->{type}     = "invoice_for_advance_payment";
316     $form->{formname} = "invoice_for_advance_payment";
317
318   } elsif ($form->{type} eq "final_invoice") {
319     $form->{type}     = "final_invoice";
320     $form->{formname} = "final_invoice";
321
322   } elsif ($form->{formname} eq "proforma" ) {
323     $form->{type}     = "invoice";
324
325   } else {
326     $form->{type}     = "invoice";
327     $form->{formname} = "invoice";
328   }
329
330   if ($form->{id}) {
331
332     my $i = 0;
333
334     foreach my $ref (@{ $form->{invoice_details} }) {
335       $i++;
336
337       map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
338
339       $form->{"discount_$i"}   = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100);
340       my ($dec)                = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
341       $dec                     = length $dec;
342       my $decimalplaces        = ($dec > 2) ? $dec : 2;
343
344       $form->{"sellprice_$i"}  = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
345       (my $dec_qty)            = ($form->{"qty_$i"} =~ /\.(\d+)/);
346       $dec_qty                 = length $dec_qty;
347
348       $form->{"lastcost_$i"}  = $form->format_amount(\%myconfig, $form->{"lastcost_$i"}, $decimalplaces);
349
350       $form->{"qty_$i"}        = $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
351
352       $form->{"sellprice_pg_$i"} = join ('--', $form->{"sellprice_$i"}, $form->{"pricegroup_id_$i"});
353
354       $form->{rowcount}        = $i;
355
356     }
357   }
358   $main::lxdebug->leave_sub();
359 }
360
361 sub setup_is_action_bar {
362   my ($tmpl_var)              = @_;
363   my $form                    = $::form;
364   my $change_never            = $::instance_conf->get_is_changeable == 0;
365   my $change_on_same_day_only = $::instance_conf->get_is_changeable == 2 && ($form->current_date(\%::myconfig) ne $form->{gldate});
366   my $payments_balanced       = ($::form->{oldtotalpaid} == 0);
367   my $has_storno              = ($::form->{storno} && !$::form->{storno_id});
368   my $may_edit_create         = $::auth->assert('invoice_edit', 1);
369   my $factur_x_enabled        = $tmpl_var->{invoice_obj} && $tmpl_var->{invoice_obj}->customer->create_zugferd_invoices_for_this_customer;
370   my ($is_linked_bank_transaction, $warn_unlinked_delivery_order);
371     if ($::form->{id}
372         && SL::DB::Default->get->payments_changeable != 0
373         && SL::DB::Manager::BankTransactionAccTrans->find_by(ar_id => $::form->{id})) {
374
375       $is_linked_bank_transaction = 1;
376     }
377   if ($::instance_conf->get_warn_no_delivery_order_for_invoice && !$form->{id}) {
378     $warn_unlinked_delivery_order = 1 unless $form->{convert_from_do_ids};
379   }
380
381   my $has_further_invoice_for_advance_payment;
382   if ($form->{id} && $form->{type} eq "invoice_for_advance_payment") {
383     my $invoice_obj = SL::DB::Invoice->load_cached($form->{id});
384     my $lr          = $invoice_obj->linked_records(direction => 'to', to => ['Invoice']);
385     $has_further_invoice_for_advance_payment = any {'SL::DB::Invoice' eq ref $_ && "invoice_for_advance_payment" eq $_->type} @$lr;
386   }
387
388   my $has_final_invoice;
389   if ($form->{id} && $form->{type} eq "invoice_for_advance_payment") {
390     my $invoice_obj = SL::DB::Invoice->load_cached($form->{id});
391     my $lr          = $invoice_obj->linked_records(direction => 'to', to => ['Invoice']);
392     $has_final_invoice = any {'SL::DB::Invoice' eq ref $_ && "final_invoice" eq $_->invoice_type} @$lr;
393   }
394
395   my $is_invoice_for_advance_payment_from_order;
396   if ($form->{id} && $form->{type} eq "invoice_for_advance_payment") {
397     my $invoice_obj = SL::DB::Invoice->load_cached($form->{id});
398     my $lr          = $invoice_obj->linked_records(direction => 'from', from => ['Order']);
399     $is_invoice_for_advance_payment_from_order = scalar @$lr >= 1;
400   }
401   # add readonly state in tmpl_vars
402   $tmpl_var->{readonly} = !$may_edit_create                     ? 1
403                     : $form->{locked}                           ? 1
404                     : $form->{storno}                           ? 1
405                     : ($form->{id} && $change_never)            ? 1
406                     : ($form->{id} && $change_on_same_day_only) ? 1
407                     : $is_linked_bank_transaction               ? 1
408                     : 0;
409
410   for my $bar ($::request->layout->get('actionbar')) {
411     $bar->add(
412       action => [
413         t8('Update'),
414         submit    => [ '#form', { action => "update" } ],
415         disabled  => !$may_edit_create ? t8('You must not change this invoice.')
416                    : $form->{locked}   ? t8('The billing period has already been locked.')
417                    :                     undef,
418         id        => 'update_button',
419         accesskey => 'enter',
420       ],
421
422       combobox => [
423         action => [
424           t8('Post'),
425           submit   => [ '#form', { action => "post" } ],
426           checks   => [ 'kivi.validate_form' ],
427           confirm  => t8('The invoice is not linked with a sales delivery order. Post anyway?') x !!$warn_unlinked_delivery_order,
428           disabled => !$may_edit_create                         ? t8('You must not change this invoice.')
429                     : $form->{locked}                           ? t8('The billing period has already been locked.')
430                     : $form->{storno}                           ? t8('A canceled invoice cannot be posted.')
431                     : ($form->{id} && $change_never)            ? t8('Changing invoices has been disabled in the configuration.')
432                     : ($form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
433                     : $is_linked_bank_transaction               ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
434                     :                                             undef,
435         ],
436         action => [
437           t8('Post and Close'),
438           submit   => [ '#form', { action => "post_and_close" } ],
439           checks   => [ 'kivi.validate_form' ],
440           confirm  => t8('The invoice is not linked with a sales delivery order. Post anyway?') x !!$warn_unlinked_delivery_order,
441           disabled => !$may_edit_create                         ? t8('You must not change this invoice.')
442                     : $form->{locked}                           ? t8('The billing period has already been locked.')
443                     : $form->{storno}                           ? t8('A canceled invoice cannot be posted.')
444                     : ($form->{id} && $change_never)            ? t8('Changing invoices has been disabled in the configuration.')
445                     : ($form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
446                     : $is_linked_bank_transaction               ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
447                     :                                             undef,
448         ],
449         action => [
450           t8('Post Payment'),
451           submit   => [ '#form', { action => "post_payment" } ],
452           checks   => [ 'kivi.validate_form' ],
453           disabled => !$may_edit_create           ? t8('You must not change this invoice.')
454                     : !$form->{id}                ? t8('This invoice has not been posted yet.')
455                     : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
456                     :                               undef,
457           only_if  => $form->{type} ne "invoice_for_advance_payment",
458         ],
459         action => [ t8('Mark as paid'),
460           submit   => [ '#form', { action => "mark_as_paid" } ],
461           confirm  => t8('This will remove the invoice from showing as unpaid even if the unpaid amount does not match the amount. Proceed?'),
462           disabled => !$may_edit_create ? t8('You must not change this invoice.')
463                     : !$form->{id}      ? t8('This invoice has not been posted yet.')
464                     :                     undef,
465           only_if  => ($::instance_conf->get_is_show_mark_as_paid && $form->{type} ne "invoice_for_advance_payment") || $form->{type} eq 'final_invoice',
466         ],
467       ], # end of combobox "Post"
468
469       combobox => [
470         action => [ t8('Storno'),
471           submit   => [ '#form', { action => "storno" } ],
472           confirm  => t8('Do you really want to cancel this invoice?'),
473           checks   => [ 'kivi.validate_form' ],
474           disabled => !$may_edit_create   ? t8('You must not change this invoice.')
475                     : !$form->{id}        ? t8('This invoice has not been posted yet.')
476                     : $form->{storno}     ? t8('Cannot storno storno invoice!')
477                     : $form->{locked}     ? t8('The billing period has already been locked.')
478                     : !$payments_balanced ? t8('Cancelling is disallowed. Either undo or balance the current payments until the open amount matches the invoice amount')
479                     : undef,
480         ],
481         action => [ t8('Delete'),
482           submit   => [ '#form', { action => "delete" } ],
483           confirm  => t8('Do you really want to delete this object?'),
484           checks   => [ 'kivi.validate_form' ],
485           disabled => !$may_edit_create        ? t8('You must not change this invoice.')
486                     : !$form->{id}             ? t8('This invoice has not been posted yet.')
487                     : $form->{locked}          ? t8('The billing period has already been locked.')
488                     : $change_never            ? t8('Changing invoices has been disabled in the configuration.')
489                     : $change_on_same_day_only ? t8('Invoices can only be changed on the day they are posted.')
490                     : $has_storno              ? t8('Can only delete the "Storno zu" part of the cancellation pair.')
491                     :                            undef,
492         ],
493       ], # end of combobox "Storno"
494
495       'separator',
496
497       combobox => [
498         action => [ t8('Workflow') ],
499         action => [
500           t8('Use As New'),
501           submit   => [ '#form', { action => "use_as_new" } ],
502           checks   => [ 'kivi.validate_form' ],
503           disabled => !$may_edit_create ? t8('You must not change this invoice.')
504                     : !$form->{id}      ? t8('This invoice has not been posted yet.')
505                     :                     undef,
506         ],
507         action => [
508           t8('Further Invoice for Advance Payment'),
509           submit   => [ '#form', { action => "further_invoice_for_advance_payment" } ],
510           checks   => [ 'kivi.validate_form' ],
511           disabled => !$may_edit_create                          ? t8('You must not change this invoice.')
512                     : !$form->{id}                               ? t8('This invoice has not been posted yet.')
513                     : $has_further_invoice_for_advance_payment   ? t8('This invoice has already a further invoice for advanced payment.')
514                     : $has_final_invoice                         ? t8('This invoice has already a final invoice.')
515                     : $is_invoice_for_advance_payment_from_order ? t8('This invoice was added from an order. See there.')
516                     :                                              undef,
517           only_if  => ($form->{type} eq "invoice_for_advance_payment" && $::instance_conf->get_show_invoice_for_advance_payment),
518         ],
519         action => [
520           t8('Final Invoice'),
521           submit   => [ '#form', { action => "final_invoice" } ],
522           checks   => [ 'kivi.validate_form' ],
523           disabled => !$may_edit_create                          ? t8('You must not change this invoice.')
524                     : !$form->{id}                               ? t8('This invoice has not been posted yet.')
525                     : $has_further_invoice_for_advance_payment   ? t8('This invoice has a further invoice for advanced payment.')
526                     : $has_final_invoice                         ? t8('This invoice has already a final invoice.')
527                     : $is_invoice_for_advance_payment_from_order ? t8('This invoice was added from an order. See there.')
528                     :                                              undef,
529           only_if  => ($form->{type} eq "invoice_for_advance_payment" && $::instance_conf->get_show_invoice_for_advance_payment),
530         ],
531         action => [
532           t8('Credit Note'),
533           submit   => [ '#form', { action => "credit_note" } ],
534           checks   => [ 'kivi.validate_form' ],
535           disabled => !$may_edit_create              ? t8('You must not change this invoice.')
536                     : $form->{type} eq "credit_note" ? t8('Credit notes cannot be converted into other credit notes.')
537                     : !$form->{id}                   ? t8('This invoice has not been posted yet.')
538                     : $form->{storno}                ? t8('A canceled invoice cannot be used. Please undo the cancellation first.')
539                     :                                  undef,
540         ],
541         action => [
542           t8('Sales Order'),
543           submit   => [ '#form', { action => "order" } ],
544           checks   => [ 'kivi.validate_form' ],
545           disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
546         ],
547         action => [
548           t8('Reclamation'),
549           submit   => ['#form', { action => "sales_reclamation" }], # can't call Reclamation directly
550           disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
551           only_if  => ($::instance_conf->get_show_sales_reclamation && $::form->{type} eq 'invoice' && !$::form->{storno}),
552         ],
553       ], # end of combobox "Workflow"
554
555       combobox => [
556         action => [ t8('Export') ],
557         action => [
558           ($form->{id} ? t8('Print') : t8('Preview')),
559           call     => [ 'kivi.SalesPurchase.show_print_dialog', $form->{id} ? 'print' : 'preview' ],
560           checks   => [ 'kivi.validate_form' ],
561           disabled => !$may_edit_create               ? t8('You must not print this invoice.')
562                     : !$form->{id} && $form->{locked} ? t8('The billing period has already been locked.')
563                     :                                   undef,
564         ],
565         action => [ t8('Print and Post'),
566           call     => [ 'kivi.SalesPurchase.show_print_dialog', 'print_and_post' ],
567           checks   => [ 'kivi.validate_form' ],
568           confirm  => t8('The invoice is not linked with a sales delivery order. Post anyway?') x !!$warn_unlinked_delivery_order,
569           disabled => !$may_edit_create                         ? t8('You must not change this invoice.')
570                     : $form->{locked}                           ? t8('The billing period has already been locked.')
571                     : $form->{storno}                           ? t8('A canceled invoice cannot be posted.')
572                     : ($form->{id} && $change_never)            ? t8('Changing invoices has been disabled in the configuration.')
573                     : ($form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
574                     : $is_linked_bank_transaction               ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
575                     :                                             undef,
576         ],
577         action => [ t8('E Mail'),
578           call     => [ 'kivi.SalesPurchase.show_email_dialog' ],
579           checks   => [ 'kivi.validate_form' ],
580           disabled => !$may_edit_create       ? t8('You must not print this invoice.')
581                     : !$form->{id}            ? t8('This invoice has not been posted yet.')
582                     : $form->{postal_invoice} ? t8('This customer wants a postal invoices.')
583                     :                     undef,
584         ],
585         action => [ t8('Factur-X/ZUGFeRD'),
586           submit   => [ '#form', { action => "download_factur_x_xml" } ],
587           checks   => [ 'kivi.validate_form' ],
588           disabled => !$may_edit_create  ? t8('You must not print this invoice.')
589                     : !$form->{id}       ? t8('This invoice has not been posted yet.')
590                     : !$factur_x_enabled ? t8('Creating Factur-X/ZUGFeRD invoices is not enabled for this customer.')
591                     :                      undef,
592         ],
593       ], # end of combobox "Export"
594
595       combobox => [
596         action => [ t8('more') ],
597         action => [
598           t8('History'),
599           call     => [ 'set_history_window', $form->{id} * 1, 'glid' ],
600           disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
601         ],
602         action => [
603           t8('Follow-Up'),
604           call     => [ 'follow_up_window' ],
605           disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
606         ],
607         action => [
608           t8('Drafts'),
609           call     => [ 'kivi.Draft.popup', 'is', 'invoice', $form->{draft_id}, $form->{draft_description} ],
610           disabled => !$may_edit_create ? t8('You must not change this invoice.')
611                     :  $form->{id}      ? t8('This invoice has already been posted.')
612                     : $form->{locked}   ? t8('The billing period has already been locked.')
613                     :                     undef,
614         ],
615       ], # end of combobox "more"
616     );
617   }
618   $::request->layout->add_javascripts('kivi.Validator.js');
619 }
620
621 sub form_header {
622   $main::lxdebug->enter_sub();
623
624   _assert_access();
625
626   my $form     = $main::form;
627   my %myconfig = %main::myconfig;
628   my $locale   = $main::locale;
629   my $cgi      = $::request->{cgi};
630
631   my %TMPL_VAR = ();
632   my @custom_hiddens;
633
634   $TMPL_VAR{customer_obj} = SL::DB::Customer->load_cached($form->{customer_id}) if $form->{customer_id};
635   $TMPL_VAR{invoice_obj}  = SL::DB::Invoice->load_cached($form->{id})           if $form->{id};
636
637   # only print, no mail
638   $form->{postal_invoice} = $TMPL_VAR{customer_obj}->postal_invoice if ref $TMPL_VAR{customer_obj} eq 'SL::DB::Customer';
639
640   my $current_employee   = SL::DB::Manager::Employee->current;
641   $form->{employee_id}   = $form->{old_employee_id} if $form->{old_employee_id};
642   $form->{salesman_id}   = $form->{old_salesman_id} if $form->{old_salesman_id};
643   $form->{employee_id} ||= $current_employee->id;
644   $form->{salesman_id} ||= $current_employee->id;
645
646   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
647
648   if( $form->{customer_id} && !$form->{taxincluded_changed_by_user} ) {
649     my $customer = SL::DB::Customer->load_cached($form->{customer_id});
650     $form->{taxincluded} = defined($customer->taxincluded_checked) ? $customer->taxincluded_checked : $myconfig{taxincluded_checked};
651   }
652   $TMPL_VAR{taxincluded} = $form->{taxincluded};
653
654   $form->get_lists("taxzones"      => ($form->{id} ? "ALL_TAXZONES" : "ALL_ACTIVE_TAXZONES"),
655                    "currencies"    => "ALL_CURRENCIES",
656                    "price_factors" => "ALL_PRICE_FACTORS");
657
658   $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
659   $form->{ALL_LANGUAGES}   = SL::DB::Manager::Language->get_all_sorted;
660   $form->{ALL_DELIVERY_TERMS} = SL::DB::Manager::DeliveryTerm->get_valid($form->{delivery_term_id});
661
662   # Projects
663   my @old_project_ids = uniq grep { $_ } map { $_ * 1 } ($form->{"globalproject_id"}, map { $form->{"project_id_$_"} } 1..$form->{"rowcount"});
664   my @old_ids_cond    = @old_project_ids ? (id => \@old_project_ids) : ();
665   my @customer_cond;
666   if ($::instance_conf->get_customer_projects_only_in_sales) {
667     @customer_cond = (
668       or => [
669         customer_id          => $::form->{customer_id},
670         billable_customer_id => $::form->{customer_id},
671       ]);
672   }
673   my @conditions = (
674     or => [
675       and => [ active => 1, @customer_cond ],
676       @old_ids_cond,
677     ]);
678
679   $TMPL_VAR{ALL_PROJECTS}          = SL::DB::Manager::Project->get_all_sorted(query => \@conditions);
680   $form->{ALL_PROJECTS}            = $TMPL_VAR{ALL_PROJECTS}; # make projects available for second row drop-down in io.pl
681   $TMPL_VAR{ALL_EMPLOYEES}         = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{employee_id},  deleted => 0 ] ]);
682   $TMPL_VAR{ALL_SALESMEN}          = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{salesman_id},  deleted => 0 ] ]);
683   $TMPL_VAR{ALL_SHIPTO}            = SL::DB::Manager::Shipto->get_all_sorted(query => [
684     or => [ and => [ trans_id  => $::form->{"$::form->{vc}_id"} * 1, module => 'CT' ], and => [ shipto_id => $::form->{shipto_id} * 1, trans_id => undef ] ]
685   ]);
686   $TMPL_VAR{ALL_CONTACTS}          = SL::DB::Manager::Contact->get_all_sorted(query => [
687     or => [
688       cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
689       and      => [
690         cp_cv_id => undef,
691         cp_id    => $::form->{cp_id} * 1
692       ]
693     ]
694   ]);
695
696   # currencies and exchangerate
697   my @values = map { $_       } @{ $form->{ALL_CURRENCIES} };
698   my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
699   $form->{currency}            = $form->{defaultcurrency} unless $form->{currency};
700   $form->{show_exchangerate}   = $form->{currency} ne $form->{defaultcurrency};
701   $TMPL_VAR{currencies}        = NTI($::request->{cgi}->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
702                                                       '-values' => \@values, '-labels' => \%labels,
703                                                       '-onchange' => "document.getElementById('update_button').click();"
704                                      )) if scalar @values;
705   push @custom_hiddens, "forex";
706   push @custom_hiddens, "exchangerate" if $form->{forex};
707
708   $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
709   $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
710
711   # qr reference
712   my $has_qr_reference = $::instance_conf->get_create_qrbill_invoices == 1 &&
713                          $form->{formname} eq 'invoice' ? 1 : 0;
714   $TMPL_VAR{has_qr_reference} = $has_qr_reference;
715
716   if ($has_qr_reference && defined $form->{qr_reference}) {
717     $TMPL_VAR{qr_reference_formatted} = get_ref_number_formatted($form->{qr_reference});
718   }
719
720   # set option selected
721   foreach my $item (qw(AR)) {
722     $form->{"select$item"} =~ s/ selected//;
723     $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
724   }
725
726   $TMPL_VAR{is_type_normal_invoice}                 = $form->{type} eq "invoice";
727   $TMPL_VAR{is_type_credit_note}                    = $form->{type}   eq "credit_note";
728   $TMPL_VAR{is_format_html}                         = $form->{format} eq 'html';
729   $TMPL_VAR{dateformat}                             = $myconfig{dateformat};
730   $TMPL_VAR{numberformat}                           = $myconfig{numberformat};
731   $TMPL_VAR{longdescription_dialog_size_percentage} = SL::Helper::UserPreferences::DisplayPreferences->new()->get_longdescription_dialog_size_percentage();
732
733   # hiddens
734   $TMPL_VAR{HIDDENS} = [qw(
735     id type queued printed emailed vc discount
736     title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
737     max_dunning_level dunning_amount dunning_description
738     taxaccounts cursor_fokus
739     convert_from_reclamations_ids convert_from_do_ids convert_from_oe_ids convert_from_ar_ids useasnew
740     invoice_id
741     show_details
742   ), @custom_hiddens,
743   map { $_.'_rate', $_.'_description', $_.'_taxnumber', $_.'_tax_id' } split / /, $form->{taxaccounts}];
744
745   $::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 client_js autocomplete_chart));
746
747   $TMPL_VAR{payment_terms_obj} = get_payment_terms_for_invoice();
748   $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};
749
750   setup_is_action_bar(\%TMPL_VAR);
751
752   $form->header();
753
754   print $form->parse_html_template("is/form_header", \%TMPL_VAR);
755
756   $main::lxdebug->leave_sub();
757 }
758
759 sub _sort_payments {
760   my @fields   = qw(acc_trans_id gldate datepaid source memo paid AR_paid);
761   my @payments =
762     grep { $_->{paid} != 0 }
763     map  {
764       my $idx = $_;
765       +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
766     } (1..$::form->{paidaccounts});
767
768   @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
769
770   $::form->{paidaccounts} = max scalar(@payments), 1;
771
772   foreach my $idx (1 .. scalar(@payments)) {
773     my $payment = $payments[$idx - 1];
774     $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
775   }
776 }
777
778 sub form_footer {
779   $main::lxdebug->enter_sub();
780
781   _assert_access();
782
783   my $form     = $main::form;
784   my %myconfig = %main::myconfig;
785   my $locale   = $main::locale;
786
787   $form->{invtotal}    = $form->{invsubtotal};
788
789   # tax, total and subtotal calculations
790   my ($tax, $subtotal);
791   $form->{taxaccounts_array} = [ split(/ /, $form->{taxaccounts}) ];
792
793   foreach my $item (@{ $form->{taxaccounts_array} }) {
794     if ($form->{"${item}_base"}) {
795       if ($form->{taxincluded}) {
796         $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
797                                                                                  / (1 + $form->{"${item}_rate"})), 2);
798         $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
799       } else {
800         $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
801         $form->{invtotal} += $form->{"${item}_total"};
802       }
803     }
804   }
805
806   my $grossamount = $form->{invtotal};
807   $form->{invtotal} = $form->round_amount( $form->{invtotal}, 2, 1 );
808   $form->{rounding} = $form->round_amount(
809     $form->{invtotal} - $form->round_amount($grossamount, 2),
810     2
811   );
812
813   # follow ups
814   if ($form->{id}) {
815     $form->{follow_ups}            = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1) || [];
816     $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
817   }
818
819   # payments
820   _sort_payments();
821
822   my $totalpaid = 0;
823   $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
824   $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
825
826   # Standard Konto für Umlaufvermögen
827   my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
828
829   for my $i (1 .. $form->{paidaccounts}) {
830     $form->{"changeable_$i"} = 1;
831     if (SL::DB::Default->get->payments_changeable == 0) {
832       # never
833       $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
834     } elsif (SL::DB::Default->get->payments_changeable == 2) {
835       # on the same day
836       $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
837                                   ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
838     }
839
840     #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
841     if ($form->date_closed($form->{"gldate_$i"})) {
842       $form->{"changeable_$i"} = 0;
843     }
844     # don't add manual bookings for charts which are assigned to real bank accounts
845     # and are flagged for use with bank import
846     my $bank_accounts = SL::DB::Manager::BankAccount->get_all();
847     foreach my $bank (@{ $bank_accounts }) {
848       if ($bank->use_with_bank_import) {
849         my $accno_paid_bank = $bank->chart->accno;
850         $form->{selectAR_paid} =~ s/<option>$accno_paid_bank--(.*?)<\/option>//;
851       }
852     }
853
854     $form->{"selectAR_paid_$i"} = $form->{selectAR_paid};
855     if (!$form->{"AR_paid_$i"}) {
856       $form->{"selectAR_paid_$i"} =~ s/option>$accno_arap--(.*?)</option selected>$accno_arap--$1</;
857     } else {
858       $form->{"selectAR_paid_$i"} =~ s/option>\Q$form->{"AR_paid_$i"}\E/option selected>$form->{"AR_paid_$i"}/;
859     }
860
861     $totalpaid += $form->{"paid_$i"};
862   }
863
864   $form->{oldinvtotal} = $form->{invtotal};
865
866   my $shipto_cvars       = SL::DB::Shipto->new->cvars_by_config;
867   foreach my $var (@{ $shipto_cvars }) {
868     my $name = "shiptocvar_" . $var->config->name;
869     $var->value($form->{$name}) if exists $form->{$name};
870   }
871
872   print $form->parse_html_template('is/form_footer', {
873     is_type_normal_invoice              => ($form->{type} eq "invoice"),
874     is_type_credit_note                 => ($form->{type} eq "credit_note"),
875     totalpaid                           => $totalpaid,
876     paid_missing                        => $form->{invtotal} - $totalpaid,
877     print_options                       => setup_sales_purchase_print_options(),
878     show_storno                         => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ar") && !$totalpaid,
879     show_delete                         => ($::instance_conf->get_is_changeable == 2)
880                                              ? ($form->current_date(\%myconfig) eq $form->{gldate})
881                                              : ($::instance_conf->get_is_changeable == 1),
882     today                               => DateTime->today,
883     vc_obj                              => $form->{customer_id} ? SL::DB::Customer->load_cached($form->{customer_id}) : undef,
884     shipto_cvars                        => $shipto_cvars,
885   });
886 ##print $form->parse_html_template('is/_payments'); # parser
887 ##print $form->parse_html_template('webdav/_list'); # parser
888
889   $main::lxdebug->leave_sub();
890 }
891
892 sub mark_as_paid {
893   $::auth->assert('invoice_edit');
894
895   SL::DB::Invoice->new(id => $::form->{id})->load->mark_as_paid;
896
897   $::form->redirect($::locale->text("Marked as paid"));
898 }
899
900 sub show_draft {
901   # unless no lazy implementation of save draft without invdate
902   # set the current date like in version <= 3.4.1
903   $::form->{invdate}   = DateTime->today->to_lxoffice;
904   $::form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_SALES_INVOICE_POST())->token;
905   update();
906 }
907
908 sub update {
909   $main::lxdebug->enter_sub();
910
911   _assert_access();
912
913   my $form     = $main::form;
914   my %myconfig = %main::myconfig;
915
916   my ($recursive_call) = @_;
917
918   $form->{print_and_post} = 0         if $form->{second_run};
919   $form->{update} = 1;
920
921   if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
922     $::form->{salesman_id} = SL::DB::Manager::Employee->current->id if exists $::form->{salesman_id};
923
924     IS->get_customer(\%myconfig, $form);
925     $::form->{billing_address_id} = $::form->{default_billing_address_id};
926   }
927
928   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
929   if ($form->{defaultcurrency} ne $form->{currency}) {
930     if ($form->{exchangerate}) { # user input OR first default ->  leave this value
931       $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate}) unless $recursive_call;
932       # does this differ from daily default?
933       my $current_daily_rate = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
934       $form->{record_forex}  = $current_daily_rate > 0 && $current_daily_rate != $form->{exchangerate}
935                            ?   1 : 0;
936     } else {                     # no value, but get defaults -> maybe user changes invdate as well ...
937       ($form->{exchangerate}, $form->{record_forex}) = $form->check_exchangerate(\%myconfig, $form->{currency},
938                                                                                  $form->{invdate}, 'buy', $form->{id}, 'ar');
939     }
940   }
941   for my $i (1 .. $form->{paidaccounts}) {
942     next unless $form->{"paid_$i"};
943     map { $form->{"${_}_$i"}   = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
944     $form->{"forex_$i"}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
945     $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
946   }
947
948   my $i            = $form->{rowcount};
949   my $exchangerate = $form->{exchangerate} || 1;
950
951   # if last row empty, check the form otherwise retrieve new item
952   if (   ($form->{"partnumber_$i"} eq "")
953       && ($form->{"description_$i"} eq "")
954       && ($form->{"partsgroup_$i"}  eq "")) {
955
956     $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
957     &check_form;
958
959   } else {
960
961     IS->retrieve_item(\%myconfig, \%$form);
962
963     my $rows = scalar @{ $form->{item_list} };
964
965     $form->{"discount_$i"}   = $form->parse_amount(\%myconfig, $form->{"discount_$i"}) / 100.0;
966     $form->{"discount_$i"} ||= $form->{customer_discount};
967
968     if ($rows) {
969       $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
970       if( !$form->{"qty_$i"} ) {
971         $form->{"qty_$i"} = 1;
972       }
973
974       if ($rows > 1) {
975
976         select_item(mode => 'IS', pre_entered_qty => $form->{"qty_$i"});
977         $::dispatcher->end_request;
978
979       } else {
980
981         my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
982
983         map { $form->{item_list}[$i]{$_} =~ s/\"/&quot;/g } qw(partnumber description unit);
984         map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
985
986         $form->{payment_id}    = $form->{"part_payment_id_$i"} if $form->{"part_payment_id_$i"} ne "";
987         $form->{"discount_$i"} = 0                             if $form->{"not_discountable_$i"};
988
989         $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
990
991         ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
992         my $decimalplaces = max 2, length $1;
993
994         if ($sellprice) {
995           $form->{"sellprice_$i"} = $sellprice;
996         } else {
997           my $record        = _make_record();
998           my $price_source  = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
999           my $best_price    = $price_source->best_price;
1000           my $best_discount = $price_source->best_discount;
1001
1002           if ($best_price) {
1003             $::form->{"sellprice_$i"}           = $best_price->price;
1004             $::form->{"active_price_source_$i"} = $best_price->source;
1005           }
1006           if ($best_discount) {
1007             $::form->{"discount_$i"}               = $best_discount->discount;
1008             $::form->{"active_discount_source_$i"} = $best_discount->source;
1009           }
1010
1011           # if there is an exchange rate adjust sellprice
1012           $form->{"sellprice_$i"} /= $exchangerate;
1013         }
1014
1015         $form->{"listprice_$i"} /= $exchangerate;
1016
1017         my $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"});
1018         map { $form->{"${_}_base"} = 0 }                                 split / /, $form->{taxaccounts};
1019         map { $form->{"${_}_base"} += $amount }                          split / /, $form->{"taxaccounts_$i"};
1020         map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{"taxaccounts_$i"} if !$form->{taxincluded};
1021
1022         $form->{creditremaining} -= $amount;
1023
1024         map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces) } qw(sellprice lastcost);
1025
1026         $form->{"qty_$i"}      = $form->format_amount(\%myconfig, $form->{"qty_$i"});
1027         $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
1028       }
1029
1030       &display_form;
1031
1032     } else {
1033
1034       # ok, so this is a new part
1035       # ask if it is a part or service item
1036
1037       if (   $form->{"partsgroup_$i"}
1038           && ($form->{"partnumber_$i" } eq "")
1039           && ($form->{"description_$i"} eq "")) {
1040         $form->{rowcount}--;
1041         $form->{"discount_$i"} = "";
1042         display_form();
1043
1044       } else {
1045         $form->{"id_$i"}   = 0;
1046         new_item();
1047       }
1048     }
1049   }
1050   $main::lxdebug->leave_sub();
1051 }
1052
1053 sub post_payment {
1054   $main::lxdebug->enter_sub();
1055
1056   my $form     = $main::form;
1057   my %myconfig = %main::myconfig;
1058   my $locale   = $main::locale;
1059
1060   $main::auth->assert('invoice_edit');
1061
1062   $form->mtime_ischanged('ar') ;
1063   my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
1064
1065   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
1066   for my $i (1 .. $form->{paidaccounts}) {
1067     if ($form->{"paid_$i"}) {
1068       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
1069
1070       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
1071
1072
1073       if ($form->{currency} ne $form->{defaultcurrency}) {
1074         $form->{"exchangerate_$i"} = $form->{exchangerate}
1075           if ($invdate == $datepaid);
1076         $form->isblank("exchangerate_$i",
1077                        $locale->text('Exchangerate for payment missing!'));
1078       }
1079       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
1080         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
1081
1082       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
1083       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
1084       $form->error($locale->text('Cannot post payment for a closed period!'))
1085         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
1086     }
1087   }
1088
1089   #($form->{AR})      = split /--/, $form->{AR};
1090   $form->{AR}      = SL::DB::Manager::Chart->find_by( id => $form->{AR_chart_id} )->accno;
1091   ($form->{AR_paid}) = split /--/, $form->{AR_paid};
1092   relink_accounts();
1093   if ( IS->post_payment(\%myconfig, \%$form) ) {
1094     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
1095     $form->{what_done} = 'invoice';
1096     $form->{addition}  = "PAYMENT POSTED";
1097     $form->save_history;
1098     $form->redirect($locale->text('Payment posted!'))
1099   } else {
1100    $form->error($locale->text('Cannot post payment!'));
1101   };
1102
1103   $main::lxdebug->leave_sub();
1104 }
1105
1106 sub post {
1107   $main::lxdebug->enter_sub();
1108
1109   my $form     = $main::form;
1110   my %myconfig = %main::myconfig;
1111   my $locale   = $main::locale;
1112
1113   $main::auth->assert('invoice_edit');
1114   $form->mtime_ischanged('ar');
1115
1116   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
1117   $form->isblank("invdate",  $locale->text('Invoice Date missing!'));
1118   $form->isblank("customer_id", $locale->text('Customer missing!'));
1119   $form->error($locale->text('Cannot post invoice for a closed period!'))
1120         if ($form->date_closed($form->{"invdate"}, \%myconfig));
1121
1122   $form->{invnumber} =~ s/^\s*//g;
1123   $form->{invnumber} =~ s/\s*$//g;
1124
1125   # if oldcustomer ne customer redo form
1126   if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
1127     &update;
1128     $::dispatcher->end_request;
1129   }
1130
1131   if ($myconfig{mandatory_departments} && !$form->{department_id}) {
1132     $form->{saved_message} = $::locale->text('You have to specify a department.');
1133     update();
1134     exit;
1135   }
1136
1137   if ($form->{second_run}) {
1138     $form->{print_and_post} = 0;
1139   }
1140
1141   remove_emptied_rows();
1142   &validate_items;
1143
1144   my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
1145   my $invdate  = $form->datetonum($form->{invdate},  \%myconfig);
1146
1147   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
1148     if ($form->date_max_future($invdate, \%myconfig));
1149   $form->error($locale->text('Cannot post invoice for a closed period!'))
1150     if ($invdate <= $closedto);
1151
1152   if ($form->{currency} ne $form->{defaultcurrency}) {
1153     $form->isblank("exchangerate", $locale->text('Exchangerate missing!'));
1154     $form->error($locale->text('Cannot post invoice with negative exchange rate'))
1155       unless ($form->parse_amount(\%myconfig, $form->{"exchangerate"}) > 0);
1156   }
1157
1158   # advance payment allows only one tax
1159   if ($form->{type} eq 'invoice_for_advance_payment') {
1160     my @current_taxaccounts = (split(/ /, $form->{taxaccounts}));
1161     $form->error($locale->text('Cannot post invoice for advance payment with more than one tax'))
1162       if (scalar @current_taxaccounts > 1);
1163     $form->error($locale->text('Cannot post invoice for advance payment with taxincluded'))
1164       if ($form->{taxincluded});
1165   }
1166
1167   for my $i (1 .. $form->{paidaccounts}) {
1168     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
1169       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
1170
1171       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
1172
1173       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
1174         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
1175
1176       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
1177       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
1178       $form->error($locale->text('Cannot post payment for a closed period!'))
1179         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
1180
1181       if ($form->{currency} ne $form->{defaultcurrency}) {
1182         $form->{"exchangerate_$i"} = $form->{exchangerate}
1183           if ($invdate == $datepaid);
1184         $form->isblank("exchangerate_$i",
1185                        $locale->text('Exchangerate for payment missing!'));
1186       }
1187     }
1188   }
1189
1190   #($form->{AR})        = split /--/, $form->{AR};
1191   $form->{AR}      = SL::DB::Manager::Chart->find_by( id => $form->{AR_chart_id} )->accno;
1192   ($form->{AR_paid})   = split /--/, $form->{AR_paid};
1193   $form->{storno}    ||= 0;
1194
1195   $form->{label} = $form->{type} eq 'credit_note' ? $locale->text('Credit Note') : $locale->text('Invoice');
1196
1197   relink_accounts();
1198
1199   my $terms        = get_payment_terms_for_invoice();
1200   $form->{duedate} = $terms->calc_date(reference_date => $form->{invdate}, due_date => $form->{duedate})->to_kivitendo if $terms;
1201
1202   # If transfer_out is requested, get rose db handle and do post and
1203   # transfer out in one transaction. Otherwise just post the invoice.
1204   if ($::instance_conf->get_is_transfer_out && $form->{type} ne 'credit_note' && !$form->{storno}) {
1205     require SL::DB::Inventory;
1206     my $rose_db = SL::DB::Inventory->new->db;
1207     my @errors;
1208
1209     if (!$rose_db->with_transaction(sub {
1210       if (!eval {
1211         if (!IS->post_invoice(\%myconfig, \%$form, $rose_db->dbh)) {
1212           push @errors, $locale->text('Cannot post invoice!');
1213           die 'posting error';
1214         }
1215         my $err = IS->transfer_out(\%$form, $rose_db->dbh);
1216         if (@{ $err }) {
1217           push @errors, @{ $err };
1218           die 'transfer error';
1219         }
1220
1221         1;
1222       }) {
1223         push @errors, $EVAL_ERROR;
1224         $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
1225       }
1226
1227       1;
1228     })) {
1229       push @errors, $rose_db->error;
1230       $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
1231     }
1232   } else {
1233     if (!IS->post_invoice(\%myconfig, \%$form)) {
1234       $form->error($locale->text('Cannot post invoice!'));
1235     }
1236   }
1237
1238   if(!exists $form->{addition}) {
1239     $form->{snumbers}  =  'invnumber' .'_'. $form->{invnumber}; # ($form->{type} eq 'credit_note' ? 'cnnumber' : 'invnumber') .'_'. $form->{invnumber};
1240     $form->{what_done} = 'invoice';
1241     $form->{addition}  = $form->{print_and_post} ? "PRINTED AND POSTED" :
1242                          $form->{storno}         ? "STORNO"             :
1243                                                    "POSTED";
1244     $form->save_history;
1245   }
1246
1247   if ($form->{email_journal_id} && $form->{id} ne "") {
1248     my $invoice = SL::DB::Invoice->new(id => $form->{id})->load;
1249     my $email_journal = SL::DB::EmailJournal->new(
1250       id => delete $form->{email_journal_id}
1251     )->load;
1252     $email_journal->link_to_record_with_attachment($invoice, delete $::form->{email_attachment_id});
1253   }
1254
1255   if (!$form->{no_redirect_after_post}) {
1256     $form->{action} = 'edit';
1257     $form->{script} = 'is.pl';
1258     $form->{callback} = build_std_url(qw(action edit id callback saved_message));
1259     $form->redirect($form->{label} . " $form->{invnumber} " . $locale->text('posted!'));
1260   }
1261
1262   $main::lxdebug->leave_sub();
1263 }
1264
1265 sub post_and_close {
1266   $main::lxdebug->enter_sub();
1267   my $locale   = $main::locale;
1268   my $form = $::form;
1269
1270   $form->{no_redirect_after_post} = 1;
1271   &post();
1272
1273   my $callback = $form->{callback}
1274     || "controller.pl?action=LoginScreen/user_login";
1275   my $msg = $form->{label} . " $form->{invnumber} " . $locale->text('posted!');
1276   SL::Helper::Flash::flash_later('info', $msg);
1277   print $form->redirect_header($callback);
1278   $::dispatcher->end_request;
1279
1280   $main::lxdebug->leave_sub();
1281 }
1282
1283 sub print_and_post {
1284   $main::lxdebug->enter_sub();
1285
1286   my $form     = $main::form;
1287
1288   $main::auth->assert('invoice_edit');
1289
1290   my $old_form                    = Form->new;
1291   $form->{no_redirect_after_post} = 1;
1292   $form->{print_and_post}         = 1;
1293   &post();
1294
1295   &edit();
1296   $main::lxdebug->leave_sub();
1297
1298 }
1299
1300 sub use_as_new {
1301   $main::lxdebug->enter_sub();
1302
1303   my $form     = $main::form;
1304   my %myconfig = %main::myconfig;
1305
1306   $main::auth->assert('invoice_edit');
1307
1308   $form->{email_journal_id}    = delete $form->{workflow_email_journal_id};
1309   $form->{email_attachment_id} = delete $form->{workflow_email_attachment_id};
1310   $form->{callback}            = delete $form->{workflow_email_callback};
1311
1312   delete @{ $form }{qw(printed emailed queued invnumber invdate exchangerate forex deliverydate id datepaid_1 gldate_1 acc_trans_id_1 source_1 memo_1 paid_1 exchangerate_1 AP_paid_1 storno locked qr_unstructured_message)};
1313   $form->{rowcount}--;
1314   $form->{paidaccounts} = 1;
1315   $form->{invdate}      = $form->current_date(\%myconfig);
1316   my $terms             = get_payment_terms_for_invoice();
1317   $form->{duedate}      = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
1318   $form->{employee_id}  = SL::DB::Manager::Employee->current->id;
1319   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1320   $form->{exchangerate} = $form->{forex} if $form->{forex};
1321   $form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_SALES_INVOICE_POST())->token;
1322
1323   $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1324
1325   $form->{useasnew} = 1;
1326   &display_form;
1327
1328   $main::lxdebug->leave_sub();
1329 }
1330
1331 sub further_invoice_for_advance_payment {
1332   my $form     = $main::form;
1333   my %myconfig = %main::myconfig;
1334
1335   $main::auth->assert('invoice_edit');
1336
1337   $form->{email_journal_id}    = delete $form->{workflow_email_journal_id};
1338   $form->{email_attachment_id} = delete $form->{workflow_email_attachment_id};
1339   $form->{callback}            = delete $form->{workflow_email_callback};
1340
1341   delete @{ $form }{qw(printed emailed queued invnumber invdate exchangerate forex deliverydate datepaid_1 gldate_1 acc_trans_id_1 source_1 memo_1 paid_1 exchangerate_1 AP_paid_1 storno locked)};
1342   $form->{convert_from_ar_ids} = $form->{id};
1343   $form->{id}                  = '';
1344   $form->{rowcount}--;
1345   $form->{paidaccounts}        = 1;
1346   $form->{invdate}             = $form->current_date(\%myconfig);
1347   my $terms                    = get_payment_terms_for_invoice();
1348   $form->{duedate}             = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
1349   $form->{employee_id}         = SL::DB::Manager::Employee->current->id;
1350   $form->{forex}               = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1351   $form->{exchangerate}        = $form->{forex} if $form->{forex};
1352   $form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_SALES_INVOICE_POST())->token;
1353
1354   $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1355
1356   &display_form;
1357 }
1358
1359 sub final_invoice {
1360   my $form     = $main::form;
1361   my %myconfig = %main::myconfig;
1362
1363   $main::auth->assert('invoice_edit');
1364
1365   $form->{email_journal_id}    = delete $form->{workflow_email_journal_id};
1366   $form->{email_attachment_id} = delete $form->{workflow_email_attachment_id};
1367   $form->{callback}            = delete $form->{workflow_email_callback};
1368
1369   my $related_invoices = IS->_get_invoices_for_advance_payment($form->{id});
1370
1371   delete @{ $form }{qw(printed emailed queued invnumber invdate exchangerate forex deliverydate datepaid_1 gldate_1 acc_trans_id_1 source_1 memo_1 paid_1 exchangerate_1 AP_paid_1 storno locked)};
1372
1373   $form->{convert_from_ar_ids} = $form->{id};
1374   $form->{id}                  = '';
1375   $form->{type}                = 'final_invoice';
1376   $form->{title}               = t8('Edit Final Invoice');
1377   $form->{paidaccounts}        = 1;
1378   $form->{invdate}             = $form->current_date(\%myconfig);
1379   my $terms                    = get_payment_terms_for_invoice();
1380   $form->{duedate}             = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
1381   $form->{employee_id}         = SL::DB::Manager::Employee->current->id;
1382   $form->{forex}               = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1383   $form->{exchangerate}        = $form->{forex} if $form->{forex};
1384   $form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_SALES_INVOICE_POST())->token;
1385
1386   foreach my $i (1 .. $form->{"rowcount"}) {
1387     delete $form->{"id_$i"};
1388     delete $form->{"invoice_id_$i"};
1389     delete $form->{"parts_id_$i"};
1390     delete $form->{"partnumber_$i"};
1391     delete $form->{"description_$i"};
1392   }
1393
1394   remove_emptied_rows(1);
1395
1396   my $i = 0;
1397   foreach my $ri (@$related_invoices) {
1398     foreach my $item (@{$ri->items_sorted}) {
1399       $i++;
1400       $form->{"id_$i"}         = $item->parts_id;
1401       $form->{"partnumber_$i"} = $item->part->partnumber;
1402       $form->{"discount_$i"}   = $item->discount*100.0;
1403       $form->{"sellprice_$i"}  = $item->fxsellprice;
1404       $form->{$_ . "_" . $i}   = $item->$_       for qw(description longdescription qty price_factor_id unit active_price_source active_discount_source);
1405
1406       $form->{$_ . "_" . $i}   = $form->format_amount(\%myconfig, $form->{$_ . "_" . $i}) for qw(qty sellprice discount);
1407     }
1408   }
1409   $form->{rowcount} = $i;
1410
1411   update();
1412   $::dispatcher->end_request;
1413 }
1414
1415 sub storno {
1416   $main::lxdebug->enter_sub();
1417
1418   my $form     = $main::form;
1419   my %myconfig = %main::myconfig;
1420   my $locale   = $main::locale;
1421
1422   $main::auth->assert('invoice_edit');
1423
1424   if ($form->{storno}) {
1425     $form->error($locale->text('Cannot storno storno invoice!'));
1426   }
1427
1428   if (IS->has_storno(\%myconfig, $form, "ar")) {
1429     $form->error($locale->text("Invoice has already been storno'd!"));
1430   }
1431   if ($form->datetonum($form->{invdate},  \%myconfig) <= $form->datetonum($form->{closedto}, \%myconfig)) {
1432     $form->error($locale->text('Cannot storno invoice for a closed period!'));
1433   }
1434
1435   # save the history of invoice being stornoed
1436   $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
1437   $form->{what_done} = 'invoice';
1438   $form->{addition}  = "STORNO";
1439   $form->save_history;
1440
1441   my $email_journal_id    = delete $form->{workflow_email_journal_id};
1442   my $email_attachment_id = delete $form->{workflow_email_attachment_id};
1443   my $callback            = delete $form->{workflow_email_callback};
1444   map({ my $key = $_; delete($form->{$key}) unless (grep({ $key eq $_ } qw(id login password type))); } keys(%{ $form }));
1445
1446   $form->{email_journal_id}    = $email_journal_id;
1447   $form->{email_attachment_id} = $email_attachment_id;
1448   $form->{callback}            = $callback;
1449
1450   invoice_links();
1451   prepare_invoice();
1452   relink_accounts();
1453
1454   # Payments must not be recorded for the new storno invoice.
1455   $form->{paidaccounts} = 0;
1456   map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
1457
1458   # record link invoice to storno
1459   $form->{convert_from_ar_ids} = $form->{id};
1460   $form->{storno_id} = $form->{id};
1461   $form->{storno} = 1;
1462   $form->{id} = "";
1463   $form->{invnumber} = "Storno zu " . $form->{invnumber};
1464   $form->{invdate}   = DateTime->today->to_lxoffice;
1465   $form->{rowcount}++;
1466   # set new ids for storno invoice
1467   # set new persistent ids for storno invoice items
1468   $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1469
1470   $form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_SALES_INVOICE_POST())->token;
1471   # post expects the field as user input
1472   $form->{exchangerate} = $form->format_amount(\%myconfig, $form->{exchangerate});
1473   $form->{script}       = 'is.pl';
1474   if ($form->{callback}) {
1475     post_and_close();
1476   } else {
1477     post();
1478   }
1479   $main::lxdebug->leave_sub();
1480 }
1481
1482 sub preview {
1483   $main::lxdebug->enter_sub();
1484
1485   my $form     = $main::form;
1486
1487   $main::auth->assert('invoice_edit');
1488
1489   $form->{preview} = 1;
1490   my $old_form = Form->new;
1491   for (keys %$form) { $old_form->{$_} = $form->{$_} }
1492
1493   &print_form($old_form);
1494   $main::lxdebug->leave_sub();
1495
1496 }
1497
1498 sub credit_note {
1499   $main::lxdebug->enter_sub();
1500
1501   my $form     = $main::form;
1502   my %myconfig = %main::myconfig;
1503   my $locale   = $main::locale;
1504
1505   $main::auth->assert('invoice_edit');
1506
1507   $form->{email_journal_id}    = delete $form->{workflow_email_journal_id};
1508   $form->{email_attachment_id} = delete $form->{workflow_email_attachment_id};
1509   $form->{callback}            = delete $form->{workflow_email_callback};
1510
1511   $form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_SALES_INVOICE_POST())->token;
1512
1513   $form->{transdate} = $form->{invdate} = $form->current_date(\%myconfig);
1514   $form->{duedate} =
1515     $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
1516
1517   $form->{convert_from_ar_ids} = $form->{id};
1518   $form->{id}     = '';
1519   $form->{rowcount}--;
1520
1521
1522   $form->{title}  = $locale->text('Add Credit Note');
1523   $form->{script} = 'is.pl';
1524
1525   # Bei Gutschriften bezug zur Rechnungsnummer
1526   $form->{invnumber_for_credit_note} = $form->{invnumber};
1527   # bo creates the id, reset it
1528   map { delete $form->{$_} }
1529     qw(id invnumber subject message cc bcc printed emailed queued);
1530   $form->{ $form->{vc} } =~ s/--.*//g;
1531   $form->{type} = "credit_note";
1532
1533
1534   map { $form->{"select$_"} = "" } ($form->{vc}, 'currency');
1535
1536 #  map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
1537 #    qw(creditlimit creditremaining);
1538
1539   # set new persistent ids for credit note and link previous invoice id
1540   $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1541
1542   my $currency = $form->{currency};
1543   &invoice_links;
1544
1545   $form->{currency}     = $currency;
1546   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1547   $form->{exchangerate} = $form->{forex} || '';
1548
1549   $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
1550
1551   # bei Gutschriften werden Zahlungseingänge aus Rechnung nicht übernommen
1552   for my $i (1 .. $form->{paidaccounts}) {
1553     delete $form->{"paid_$i"};
1554     delete $form->{"source_$i"};
1555     delete $form->{"memo_$i"};
1556     delete $form->{"datepaid_$i"};
1557     delete $form->{"gldate_$i"};
1558     delete $form->{"acc_trans_id_$i"};
1559     delete $form->{"AR_paid_$i"};
1560   };
1561   $form->{paidaccounts} = 1;
1562
1563   &prepare_invoice;
1564
1565   &display_form;
1566
1567   $main::lxdebug->leave_sub();
1568 }
1569
1570 sub credit_note_from_reclamation {
1571   $main::lxdebug->enter_sub();
1572
1573   $main::auth->assert('invoice_edit');
1574
1575   my $form     = $main::form;
1576   my %myconfig = %main::myconfig;
1577   my $locale   = $main::locale;
1578
1579   if (!$form->{form_validity_token}) {
1580     $form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_SALES_INVOICE_POST())->token;
1581   }
1582
1583   my $from_id = delete $form->{from_id};
1584   my $reclamation = SL::DB::Reclamation->new(id => $from_id)->load;
1585
1586   $reclamation->flatten_to_form($form, format_amounts => 1);
1587
1588   # set new persistent ids for credit note and link previous reclamation id
1589   $form->{convert_from_reclamations_ids} = $form->{id};
1590   $form->{id}     = '';
1591
1592   $form->{"converted_from_reclamation_items_id_$_"} = delete $form->{"reclamation_items_id_$_"} for 1 .. $form->{"rowcount"};
1593
1594   $form->{transdate} = $form->{invdate} = $form->current_date(\%myconfig);
1595   $form->{duedate} =
1596     $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
1597
1598   $form->{title}  = $locale->text('Add Credit Note');
1599   $form->{script} = 'is.pl';
1600
1601   # bo creates the id, reset it
1602   map { delete $form->{$_} }
1603     qw(id invnumber subject message cc bcc printed emailed queued);
1604   $form->{ $form->{vc} } =~ s/--.*//g;
1605
1606   $form->{type} = "credit_note";
1607
1608   my $currency = $form->{currency};
1609   &invoice_links;
1610   $form->{currency}     = $currency;
1611   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1612   $form->{exchangerate} = $form->{forex} || '';
1613
1614   $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
1615
1616   &prepare_invoice;
1617
1618   &display_form;
1619
1620   $main::lxdebug->leave_sub();
1621 }
1622
1623 sub display_form {
1624   $::lxdebug->enter_sub;
1625
1626   _assert_access();
1627
1628   relink_accounts();
1629
1630   my $new_rowcount = $::form->{"rowcount"} * 1 + 1;
1631   $::form->{"project_id_${new_rowcount}"} = $::form->{"globalproject_id"};
1632
1633   $::form->language_payment(\%::myconfig);
1634
1635   Common::webdav_folder($::form);
1636
1637   form_header();
1638   display_row(++$::form->{rowcount});
1639   form_footer();
1640
1641   $::lxdebug->leave_sub;
1642 }
1643
1644 sub delete {
1645   $::auth->assert('invoice_edit');
1646
1647   if (IS->delete_invoice(\%::myconfig, $::form)) {
1648     # saving the history
1649     if(!exists $::form->{addition}) {
1650       $::form->{snumbers}  = 'invnumber' .'_'. $::form->{invnumber};
1651       $::form->{what_done} = 'invoice';
1652       $::form->{addition}  = "DELETED";
1653       $::form->save_history;
1654     }
1655     # /saving the history
1656     $::form->redirect($::locale->text('Invoice deleted!'));
1657   }
1658   $::form->error($::locale->text('Cannot delete invoice!'));
1659 }
1660
1661 sub dispatcher {
1662   for my $action (qw(
1663     print update ship_to storno post_payment use_as_new credit_note
1664     delete post order preview post_and_e_mail print_and_post
1665     mark_as_paid
1666   )) {
1667     if ($::form->{"action_$action"}) {
1668       call_sub($action);
1669       return;
1670     }
1671   }
1672
1673   $::form->error($::locale->text('No action defined.'));
1674 }