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