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