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