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