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