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