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