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