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