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