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