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