Zahlungsbedingungen: Flag »Fälligkeitsdatum automatisch berechnen«
[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   #/show hhistory button
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->{webdav}   = $::instance_conf->get_webdav;
144
145   $form->create_links("AR", \%myconfig, "customer");
146
147   if ($form->{all_customer}) {
148     unless ($form->{customer_id}) {
149       $form->{customer_id} = $form->{all_customer}->[0]->{id};
150       $form->{salesman_id} = $form->{all_customer}->[0]->{salesman_id};
151     }
152   }
153
154   my $editing = $form->{id};
155
156   $form->backup_vars(qw(payment_id language_id taxzone_id salesman_id
157                         taxincluded currency cp_id intnotes id shipto_id
158                         delivery_term_id));
159
160   IS->get_customer(\%myconfig, \%$form);
161
162   #quote all_customer Bug 133
163   foreach my $ref (@{ $form->{all_customer} }) {
164     $ref->{name} = $form->quote($ref->{name});
165   }
166
167   $form->restore_vars(qw(id));
168
169   IS->retrieve_invoice(\%myconfig, \%$form);
170   $form->restore_vars(qw(payment_id language_id taxzone_id currency intnotes
171                          cp_id shipto_id delivery_term_id));
172   $form->restore_vars(qw(taxincluded)) if $form->{id};
173   $form->restore_vars(qw(salesman_id)) if $editing;
174
175
176   # build vendor/customer drop down comatibility... don't ask
177   if (@{ $form->{"all_customer"} }) {
178     $form->{"selectcustomer"} = 1;
179     $form->{customer}         = qq|$form->{customer}--$form->{"customer_id"}|;
180   }
181
182   $form->{"oldcustomer"}  = $form->{customer};
183
184   if ($form->{"oldcustomer"} !~ m/--\d+$/ && $form->{"customer_id"}) {
185     $form->{"oldcustomer"} .= qq|--$form->{"customer_id"}|
186   }
187
188
189 #  $form->{oldcustomer} = "$form->{customer}--$form->{customer_id}";
190 #  $form->{selectcustomer} = 1;
191
192   $form->{employee} = "$form->{employee}--$form->{employee_id}";
193
194   # forex
195   $form->{forex} = $form->{exchangerate};
196   my $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
197
198   foreach my $key (keys %{ $form->{AR_links} }) {
199     foreach my $ref (@{ $form->{AR_links}{$key} }) {
200       $form->{"select$key"} .= "<option>$ref->{accno}--$ref->{description}</option>\n";
201     }
202
203     if ($key eq "AR_paid") {
204       next unless $form->{acc_trans}{$key};
205       for my $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
206         $form->{"AR_paid_$i"}      = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
207
208         $form->{"acc_trans_id_$i"}    = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
209         # reverse paid
210         $form->{"paid_$i"}         = $form->{acc_trans}{$key}->[$i - 1]->{amount} * -1;
211         $form->{"datepaid_$i"}     = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
212         $form->{"gldate_$i"}       = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
213         $form->{"exchangerate_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
214         $form->{"forex_$i"}        = $form->{"exchangerate_$i"};
215         $form->{"source_$i"}       = $form->{acc_trans}{$key}->[$i - 1]->{source};
216         $form->{"memo_$i"}         = $form->{acc_trans}{$key}->[$i - 1]->{memo};
217
218         $form->{paidaccounts} = $i;
219       }
220     } else {
221       $form->{$key} = "$form->{acc_trans}{$key}->[0]->{accno}--$form->{acc_trans}{$key}->[0]->{description}";
222     }
223   }
224
225   $form->{paidaccounts} = 1 unless (exists $form->{paidaccounts});
226
227   $form->{AR} = $form->{AR_1} unless $form->{id};
228
229   $form->{locked} = ($form->datetonum($form->{invdate},  \%myconfig)
230                   <= $form->datetonum($form->{closedto}, \%myconfig));
231
232   $main::lxdebug->leave_sub();
233 }
234
235 sub prepare_invoice {
236   $main::lxdebug->enter_sub();
237
238   my $form     = $main::form;
239   my %myconfig = %main::myconfig;
240
241   $main::auth->assert('invoice_edit');
242
243   if ($form->{type} eq "credit_note") {
244     $form->{type}     = "credit_note";
245     $form->{formname} = "credit_note";
246   } else {
247     $form->{type}     = "invoice";
248     $form->{formname} = "invoice";
249   }
250
251   if ($form->{id}) {
252
253     my $i = 0;
254
255     foreach my $ref (@{ $form->{invoice_details} }) {
256       $i++;
257
258       map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
259
260       $form->{"discount_$i"}   = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100);
261       my ($dec)                = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
262       $dec                     = length $dec;
263       my $decimalplaces        = ($dec > 2) ? $dec : 2;
264
265       $form->{"sellprice_$i"}  = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
266       (my $dec_qty)            = ($form->{"qty_$i"} =~ /\.(\d+)/);
267       $dec_qty                 = length $dec_qty;
268
269       $form->{"lastcost_$i"}  = $form->format_amount(\%myconfig, $form->{"lastcost_$i"}, $decimalplaces);
270
271       $form->{"qty_$i"}        = $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
272
273       $form->{"sellprice_pg_$i"} = join ('--', $form->{"sellprice_$i"}, $form->{"pricegroup_id_$i"});
274
275       $form->{rowcount}        = $i;
276
277     }
278   }
279   $main::lxdebug->leave_sub();
280 }
281
282 sub form_header {
283   $main::lxdebug->enter_sub();
284
285   my $form     = $main::form;
286   my %myconfig = %main::myconfig;
287   my $locale   = $main::locale;
288   my $cgi      = $::request->{cgi};
289
290   $main::auth->assert('invoice_edit');
291
292   my %TMPL_VAR = ();
293   my @custom_hiddens;
294
295   $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
296   $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
297
298   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
299
300   $form->get_lists("taxzones"      => ($form->{id} ? "ALL_TAXZONES" : "ALL_ACTIVE_TAXZONES"),
301                    "currencies"    => "ALL_CURRENCIES",
302                    "customers"     => "ALL_CUSTOMERS",
303                    "departments"   => "all_departments",
304                    "price_factors" => "ALL_PRICE_FACTORS");
305
306   # Projects
307   my @old_project_ids = uniq grep { $_ } map { $_ * 1 } ($form->{"globalproject_id"}, map { $form->{"project_id_$_"} } 1..$form->{"rowcount"});
308   my @old_ids_cond    = @old_project_ids ? (id => \@old_project_ids) : ();
309   my @customer_cond;
310   if ($::instance_conf->get_customer_projects_only_in_sales) {
311     @customer_cond = (
312       or => [
313         customer_id          => $::form->{customer_id},
314         billable_customer_id => $::form->{customer_id},
315       ]);
316   }
317   my @conditions = (
318     or => [
319       and => [ active => 1, @customer_cond ],
320       @old_ids_cond,
321     ]);
322
323   $TMPL_VAR{ALL_PROJECTS}          = SL::DB::Manager::Project->get_all_sorted(query => \@conditions);
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   });
491 ##print $form->parse_html_template('is/_payments'); # parser
492 ##print $form->parse_html_template('webdav/_list'); # parser
493
494   $main::lxdebug->leave_sub();
495 }
496
497 sub mark_as_paid {
498   $main::lxdebug->enter_sub();
499
500   my $form     = $main::form;
501   my %myconfig = %main::myconfig;
502
503   $main::auth->assert('invoice_edit');
504
505   &mark_as_paid_common(\%myconfig,"ar");
506
507   $main::lxdebug->leave_sub();
508 }
509
510 sub update {
511   $main::lxdebug->enter_sub();
512
513   my $form     = $main::form;
514   my %myconfig = %main::myconfig;
515
516   $main::auth->assert('invoice_edit');
517
518   my ($recursive_call) = @_;
519
520   $form->{print_and_post} = 0         if $form->{second_run};
521   my $taxincluded         = $form->{taxincluded} ? "checked" : '';
522   $form->{update} = 1;
523
524   &check_name("customer");
525
526   $form->{taxincluded} ||= $taxincluded;
527
528   if (!$form->{forex}) {        # read exchangerate from input field (not hidden)
529     $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate}) unless $recursive_call;
530   }
531   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
532   $form->{exchangerate} = $form->{forex} if $form->{forex};
533
534   for my $i (1 .. $form->{paidaccounts}) {
535     next unless $form->{"paid_$i"};
536     map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
537     if (!$form->{"forex_$i"}) {   #read exchangerate from input field (not hidden)
538       $form->{exchangerate} = $form->{"exchangerate_$i"};
539     }
540     $form->{"forex_$i"}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
541     $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
542   }
543
544   my $i            = $form->{rowcount};
545   my $exchangerate = $form->{exchangerate} || 1;
546
547   # if last row empty, check the form otherwise retrieve new item
548   if (   ($form->{"partnumber_$i"} eq "")
549       && ($form->{"description_$i"} eq "")
550       && ($form->{"partsgroup_$i"}  eq "")) {
551
552     $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
553     &check_form;
554
555   } else {
556
557     IS->retrieve_item(\%myconfig, \%$form);
558
559     my $rows = scalar @{ $form->{item_list} };
560
561     $form->{"discount_$i"}   = $form->parse_amount(\%myconfig, $form->{"discount_$i"}) / 100.0;
562     $form->{"discount_$i"} ||= $form->{customer_discount};
563
564     if ($rows) {
565       $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
566       if( !$form->{"qty_$i"} ) {
567         $form->{"qty_$i"} = 1;
568       }
569
570       if ($rows > 1) {
571
572         select_item(mode => 'IS', pre_entered_qty => $form->{"qty_$i"});
573         ::end_of_request();
574
575       } else {
576
577         my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
578
579         map { $form->{item_list}[$i]{$_} =~ s/\"/&quot;/g } qw(partnumber description unit);
580         map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
581
582         $form->{payment_id}    = $form->{"part_payment_id_$i"} if $form->{"part_payment_id_$i"} ne "";
583         $form->{"discount_$i"} = 0                             if $form->{"not_discountable_$i"};
584
585         $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
586
587         ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
588         my $decimalplaces = max 2, length $1;
589
590         if ($sellprice) {
591           $form->{"sellprice_$i"} = $sellprice;
592         } else {
593           my $record        = _make_record();
594           my $price_source  = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
595           my $best_price    = $price_source->best_price;
596           my $best_discount = $price_source->best_discount;
597
598           if ($best_price) {
599             $::form->{"sellprice_$i"}           = $best_price->price;
600             $::form->{"active_price_source_$i"} = $best_price->source;
601           }
602           if ($best_discount) {
603             $::form->{"discount_$i"}               = $best_discount->discount;
604             $::form->{"active_discount_source_$i"} = $best_discount->source;
605           }
606
607           # if there is an exchange rate adjust sellprice
608           $form->{"sellprice_$i"} /= $exchangerate;
609         }
610
611         $form->{"listprice_$i"} /= $exchangerate;
612
613         my $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"});
614         map { $form->{"${_}_base"} = 0 }                                 split / /, $form->{taxaccounts};
615         map { $form->{"${_}_base"} += $amount }                          split / /, $form->{"taxaccounts_$i"};
616         map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{"taxaccounts_$i"} if !$form->{taxincluded};
617
618         $form->{creditremaining} -= $amount;
619
620         map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces) } qw(sellprice lastcost);
621
622         $form->{"qty_$i"}      = $form->format_amount(\%myconfig, $form->{"qty_$i"});
623         $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
624       }
625
626       &display_form;
627
628     } else {
629
630       # ok, so this is a new part
631       # ask if it is a part or service item
632
633       if (   $form->{"partsgroup_$i"}
634           && ($form->{"partsnumber_$i"} eq "")
635           && ($form->{"description_$i"} eq "")) {
636         $form->{rowcount}--;
637         $form->{"discount_$i"} = "";
638         display_form();
639
640       } else {
641         $form->{"id_$i"}   = 0;
642         new_item();
643       }
644     }
645   }
646   $main::lxdebug->leave_sub();
647 }
648
649 sub post_payment {
650   $main::lxdebug->enter_sub();
651
652   my $form     = $main::form;
653   my %myconfig = %main::myconfig;
654   my $locale   = $main::locale;
655
656   $main::auth->assert('invoice_edit');
657
658   my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
659
660   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
661   for my $i (1 .. $form->{paidaccounts}) {
662     if ($form->{"paid_$i"}) {
663       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
664
665       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
666
667
668       if ($form->{currency} ne $form->{defaultcurrency}) {
669         $form->{"exchangerate_$i"} = $form->{exchangerate}
670           if ($invdate == $datepaid);
671         $form->isblank("exchangerate_$i",
672                        $locale->text('Exchangerate for payment missing!'));
673       }
674     }
675   }
676   # Abgeschlossene Zeiträume nur für den letzten (aktuellen) Zahlungseingang prüfen
677   # Details s.a. Bug 1502
678   # Das Problem ist jetzt, dass man Zahlungseingänge nachträglich ändern kann
679   # Wobei dies für Installationen die sowieso nicht mit Bücherkontrolle arbeiten keinen
680   # keinen Unterschied macht.
681   # Optimal wäre, wenn gegen einen Zeitstempel des Zahlungsfelds geprüft würde ...
682   # Das Problem hierbei ist, dass in IS.pm post_invoice IMMER alle Zahlungseingänge aus $form
683   # erneut gespeichert werden. Prinzipiell wäre es besser NUR die Änderungen des Rechnungs-
684   # belegs (neue Zahlung aber nichts anderes) zu speichern ...
685   # Vielleicht könnte man ähnlich wie bei Rechnung löschen verfahren
686   $form->error($locale->text('Cannot post payment for a closed period!'))
687     if ($form->date_closed($form->{"datepaid_$form->{paidaccounts}"}, \%myconfig));
688
689   ($form->{AR})      = split /--/, $form->{AR};
690   ($form->{AR_paid}) = split /--/, $form->{AR_paid};
691   relink_accounts();
692   $form->redirect($locale->text('Payment posted!'))
693       if (IS->post_payment(\%myconfig, \%$form));
694     $form->error($locale->text('Cannot post payment!'));
695
696
697   $main::lxdebug->leave_sub();
698 }
699
700 sub post {
701   $main::lxdebug->enter_sub();
702
703   my $form     = $main::form;
704   my %myconfig = %main::myconfig;
705   my $locale   = $main::locale;
706
707   $main::auth->assert('invoice_edit');
708
709   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
710   $form->isblank("invdate",  $locale->text('Invoice Date missing!'));
711   $form->isblank("customer", $locale->text('Customer missing!'));
712   $form->error($locale->text('Cannot post invoice for a closed period!'))
713         if ($form->date_closed($form->{"invdate"}, \%myconfig));
714
715   $form->{invnumber} =~ s/^\s*//g;
716   $form->{invnumber} =~ s/\s*$//g;
717
718   # if oldcustomer ne customer redo form
719   if (&check_name('customer')) {
720     &update;
721     ::end_of_request();
722   }
723
724   if ($myconfig{mandatory_departments} && !$form->{department_id}) {
725     $form->{saved_message} = $::locale->text('You have to specify a department.');
726     update();
727     exit;
728   }
729
730   if ($form->{second_run}) {
731     $form->{print_and_post} = 0;
732   }
733
734   remove_emptied_rows();
735   &validate_items;
736
737   my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
738   my $invdate  = $form->datetonum($form->{invdate},  \%myconfig);
739
740   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
741     if ($form->date_max_future($invdate, \%myconfig));
742   $form->error($locale->text('Cannot post invoice for a closed period!'))
743     if ($invdate <= $closedto);
744
745   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
746     if ($form->{currency} ne $form->{defaultcurrency});
747
748   for my $i (1 .. $form->{paidaccounts}) {
749     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
750       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
751
752       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
753
754       $form->error($locale->text('Cannot post payment for a closed period!'))
755         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
756
757       if ($form->{currency} ne $form->{defaultcurrency}) {
758         $form->{"exchangerate_$i"} = $form->{exchangerate}
759           if ($invdate == $datepaid);
760         $form->isblank("exchangerate_$i",
761                        $locale->text('Exchangerate for payment missing!'));
762       }
763     }
764   }
765
766   ($form->{AR})        = split /--/, $form->{AR};
767   ($form->{AR_paid})   = split /--/, $form->{AR_paid};
768   $form->{storno}    ||= 0;
769
770   $form->{label} = $form->{type} eq 'credit_note' ? $locale->text('Credit Note') : $locale->text('Invoice');
771
772   $form->{id} = 0 if $form->{postasnew};
773
774   # get new invnumber in sequence if no invnumber is given or if posasnew was requested
775   if ($form->{postasnew}) {
776     if ($form->{type} eq "credit_note") {
777       undef($form->{cnnumber});
778     } else {
779       undef($form->{invnumber});
780     }
781   }
782
783   relink_accounts();
784
785   my $terms        = get_payment_terms_for_invoice();
786   $form->{duedate} = $terms->calc_date(reference_date => $form->{invdate}, due_date => $form->{due_due})->to_kivitendo if $terms;
787
788   # If transfer_out is requested, get rose db handle and do post and
789   # transfer out in one transaction. Otherwise just post the invoice.
790   if ($::instance_conf->get_is_transfer_out && $form->{type} ne 'credit_note' && !$form->{storno}) {
791     require SL::DB::Inventory;
792     my $rose_db = SL::DB::Inventory->new->db;
793     my @errors;
794
795     if (!$rose_db->with_transaction(sub {
796       if (!eval {
797         if (!IS->post_invoice(\%myconfig, \%$form, $rose_db->dbh)) {
798           push @errors, $locale->text('Cannot post invoice!');
799           die 'posting error';
800         }
801         my $err = IS->transfer_out(\%$form, $rose_db->dbh);
802         if (@{ $err }) {
803           push @errors, @{ $err };
804           die 'transfer error';
805         }
806
807         1;
808       }) {
809         push @errors, $EVAL_ERROR;
810         die 'transaction error';
811       }
812
813       1;
814     })) {
815       push @errors, $rose_db->error;
816       $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
817     }
818   } else {
819     if (!IS->post_invoice(\%myconfig, \%$form)) {
820       $form->error($locale->text('Cannot post invoice!'));
821     }
822   }
823
824   remove_draft() if $form->{remove_draft};
825
826   if(!exists $form->{addition}) {
827     $form->{snumbers} =  'invnumber' .'_'. $form->{invnumber}; # ($form->{type} eq 'credit_note' ? 'cnnumber' : 'invnumber') .'_'. $form->{invnumber};
828     $form->{addition} = $form->{print_and_post} ? "PRINTED AND POSTED" :
829                         $form->{storno}         ? "STORNO"             :
830                                                   "POSTED";
831     $form->save_history;
832   }
833
834   if (!$form->{no_redirect_after_post}) {
835     $form->{action} = 'edit';
836     $form->{script} = 'is.pl';
837     $form->{saved_message} = $form->{label} . " $form->{invnumber} " . $locale->text('posted!');
838     $form->{callback} = build_std_url(qw(action edit id saved_message));
839     $form->redirect;
840   }
841
842   $main::lxdebug->leave_sub();
843 }
844
845 sub print_and_post {
846   $main::lxdebug->enter_sub();
847
848   my $form     = $main::form;
849
850   $main::auth->assert('invoice_edit');
851
852   my $old_form                    = Form->new;
853   $form->{no_redirect_after_post} = 1;
854   $form->{print_and_post}         = 1;
855   &post();
856
857   &edit();
858   $main::lxdebug->leave_sub();
859
860 }
861
862 sub use_as_new {
863   $main::lxdebug->enter_sub();
864
865   my $form     = $main::form;
866   my %myconfig = %main::myconfig;
867
868   $main::auth->assert('invoice_edit');
869
870   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)};
871   $form->{rowcount}--;
872   $form->{paidaccounts} = 1;
873   $form->{invdate}      = $form->current_date(\%myconfig);
874   my $terms             = get_payment_terms_for_invoice();
875   $form->{duedate}      = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
876   $form->{employee_id}  = SL::DB::Manager::Employee->current->id;
877   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
878   $form->{exchangerate} = $form->{forex} if $form->{forex};
879
880   $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
881
882   $form->{useasnew} = 1;
883   &display_form;
884
885   $main::lxdebug->leave_sub();
886 }
887
888 sub storno {
889   $main::lxdebug->enter_sub();
890
891   my $form     = $main::form;
892   my %myconfig = %main::myconfig;
893   my $locale   = $main::locale;
894
895   $main::auth->assert('invoice_edit');
896
897   if ($form->{storno}) {
898     $form->error($locale->text('Cannot storno storno invoice!'));
899   }
900
901   if (IS->has_storno(\%myconfig, $form, "ar")) {
902     $form->error($locale->text("Invoice has already been storno'd!"));
903   }
904   if ($form->datetonum($form->{invdate},  \%myconfig) <= $form->datetonum($form->{closedto}, \%myconfig)) {
905     $form->error($locale->text('Cannot storno invoice for a closed period!'));
906   }
907
908   # save the history of invoice being stornoed
909   $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
910   $form->{addition} = "STORNO";
911   $form->save_history;
912
913   map({ my $key = $_; delete($form->{$key}) unless (grep({ $key eq $_ } qw(id login password type))); } keys(%{ $form }));
914
915   invoice_links();
916   prepare_invoice();
917   relink_accounts();
918
919   # Payments must not be recorded for the new storno invoice.
920   $form->{paidaccounts} = 0;
921   map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
922
923   $form->{storno_id} = $form->{id};
924   $form->{storno} = 1;
925   $form->{id} = "";
926   $form->{invnumber} = "Storno zu " . $form->{invnumber};
927   $form->{invdate}   = DateTime->today->to_lxoffice;
928   $form->{rowcount}++;
929   # set new ids for storno invoice
930   delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
931
932   post();
933   $main::lxdebug->leave_sub();
934 }
935
936 sub preview {
937   $main::lxdebug->enter_sub();
938
939   my $form     = $main::form;
940
941   $main::auth->assert('invoice_edit');
942
943   $form->{preview} = 1;
944   my $old_form = Form->new;
945   for (keys %$form) { $old_form->{$_} = $form->{$_} }
946
947   &print_form($old_form);
948   $main::lxdebug->leave_sub();
949
950 }
951
952 sub delete {
953   $main::lxdebug->enter_sub();
954
955   my $form     = $main::form;
956   my $locale   = $main::locale;
957
958   $main::auth->assert('invoice_edit');
959
960   if ($form->{second_run}) {
961     $form->{print_and_post} = 0;
962   }
963   $form->header;
964
965   print qq|
966 <form method="post" action="$form->{script}">
967 |;
968
969   # delete action variable
970   map { delete $form->{$_} } qw(action header);
971
972   foreach my $key (keys %$form) {
973     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
974     $form->{$key} =~ s/\"/&quot;/g;
975     print qq|<input type="hidden" name="$key" value="$form->{$key}">\n|;
976   }
977
978   print qq|
979 <h2 class="confirm">| . $locale->text('Confirm!') . qq|</h2>
980
981 <h4>|
982     . $locale->text('Are you sure you want to delete Invoice Number')
983     . qq| $form->{invnumber}
984 </h4>
985
986 <p>
987 <input name="action" class="submit" type="submit" value="|
988     . $locale->text('Yes') . qq|">
989 </form>
990 |;
991
992   $main::lxdebug->leave_sub();
993 }
994
995 sub credit_note {
996   $main::lxdebug->enter_sub();
997
998   my $form     = $main::form;
999   my %myconfig = %main::myconfig;
1000   my $locale   = $main::locale;
1001
1002   $main::auth->assert('invoice_edit');
1003
1004   $form->{transdate} = $form->{invdate} = $form->current_date(\%myconfig);
1005   $form->{duedate} =
1006     $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
1007
1008   $form->{convert_from_ar_ids} = $form->{id};
1009   $form->{id}     = '';
1010   $form->{rowcount}--;
1011
1012
1013   $form->{title}  = $locale->text('Add Credit Note');
1014   $form->{script} = 'is.pl';
1015
1016   # Bei Gutschriften bezug zur Rechnungsnummer
1017   $form->{invnumber_for_credit_note} = $form->{invnumber};
1018   # bo creates the id, reset it
1019   map { delete $form->{$_} }
1020     qw(id invnumber subject message cc bcc printed emailed queued);
1021   $form->{ $form->{vc} } =~ s/--.*//g;
1022   $form->{type} = "credit_note";
1023
1024
1025   map { $form->{"select$_"} = "" } ($form->{vc}, 'currency');
1026
1027 #  map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
1028 #    qw(creditlimit creditremaining);
1029
1030   # set new persistent ids for credit note and link previous invoice id
1031   $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1032
1033   my $currency = $form->{currency};
1034   &invoice_links;
1035
1036   $form->{currency}     = $currency;
1037   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1038   $form->{exchangerate} = $form->{forex} || '';
1039
1040   $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
1041
1042   # bei Gutschriften werden Zahlungseingänge aus Rechnung nicht übernommen
1043   for my $i (1 .. $form->{paidaccounts}) {
1044     delete $form->{"paid_$i"};
1045     delete $form->{"source_$i"};
1046     delete $form->{"memo_$i"};
1047     delete $form->{"datepaid_$i"};
1048     delete $form->{"gldate_$i"};
1049     delete $form->{"acc_trans_id_$i"};
1050     delete $form->{"AR_paid_$i"};
1051   };
1052   $form->{paidaccounts} = 1;
1053
1054   &prepare_invoice;
1055
1056
1057   &display_form;
1058
1059   $main::lxdebug->leave_sub();
1060 }
1061
1062 sub yes {
1063   $main::lxdebug->enter_sub();
1064
1065   my $form     = $main::form;
1066   my %myconfig = %main::myconfig;
1067   my $locale   = $main::locale;
1068
1069   $main::auth->assert('invoice_edit');
1070
1071   if (IS->delete_invoice(\%myconfig, \%$form)) {
1072     # saving the history
1073     if(!exists $form->{addition}) {
1074       $form->{snumbers} = 'invnumber' .'_'. $form->{invnumber}; # ($form->{type} eq 'credit_note' ? 'cnnumber' : 'invnumber') .'_'. $form->{invnumber};
1075       $form->{addition} = "DELETED";
1076       $form->save_history;
1077     }
1078     # /saving the history
1079     $form->redirect($locale->text('Invoice deleted!'));
1080   }
1081   $form->error($locale->text('Cannot delete invoice!'));
1082
1083   $main::lxdebug->leave_sub();
1084 }
1085
1086 sub post_and_e_mail {
1087   e_mail();
1088 };
1089
1090 sub e_mail {
1091   $main::lxdebug->enter_sub();
1092
1093   my $form     = $main::form;
1094
1095   $main::auth->assert('invoice_edit');
1096
1097   if (!$form->{id}) {
1098     $form->{no_redirect_after_post} = 1;
1099
1100     my $saved_form = save_form();
1101
1102     post();
1103
1104     restore_form($saved_form, 0, qw(id invnumber));
1105   }
1106
1107   edit_e_mail();
1108
1109   $main::lxdebug->leave_sub();
1110 }