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