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