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