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