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