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