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