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