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