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