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