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