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