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