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