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