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