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