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