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