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