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