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