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