4b8b8175d0538c87ed5738ac0b018ec2f78663e3
[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 Data::Dumper;
38 use List::Util qw(max sum);
39
40 require "bin/mozilla/io.pl";
41 require "bin/mozilla/invoice_io.pl";
42 require "bin/mozilla/arap.pl";
43 require "bin/mozilla/drafts.pl";
44
45 use strict;
46
47 my $edit;
48 my $print_post;
49
50 1;
51
52 # end of main
53
54 sub add {
55   $main::lxdebug->enter_sub();
56
57   my $form     = $main::form;
58   my $locale   = $main::locale;
59
60   $main::auth->assert('invoice_edit');
61
62   return $main::lxdebug->leave_sub() if (load_draft_maybe());
63
64   if ($form->{type} eq "credit_note") {
65     $form->{title} = $locale->text('Add Credit Note');
66
67     if ($form->{storno}) {
68       $form->{title} = $locale->text('Add Storno Credit Note');
69     }
70   } else {
71     $form->{title} = $locale->text('Add Sales Invoice');
72
73   }
74
75
76   $form->{callback} = "$form->{script}?action=add&type=$form->{type}" unless $form->{callback};
77
78   $form->{jsscript} = "date";
79
80   &invoice_links;
81   &prepare_invoice;
82   &display_form;
83
84   $main::lxdebug->leave_sub();
85 }
86
87 sub edit {
88   $main::lxdebug->enter_sub();
89
90   my $form     = $main::form;
91   my $locale   = $main::locale;
92
93   $main::auth->assert('invoice_edit');
94
95   # show history button
96   $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
97   #/show hhistory button
98
99   if ($form->{type} eq "credit_note") {
100     $form->{title} = $locale->text('Edit Credit Note');
101     $form->{title} = $locale->text('Edit Storno Credit Note') if $form->{storno};
102   } else {
103     $form->{title} = $locale->text('Edit Sales Invoice');
104     $form->{title} = $locale->text('Edit Storno Invoice')     if $form->{storno};
105   }
106
107   my ($language_id, $printer_id);
108   if ($form->{print_and_post}) {
109     $form->{action}   = "print";
110     $form->{resubmit} = 1;
111     $language_id = $form->{language_id};
112     $printer_id = $form->{printer_id};
113   }
114   &invoice_links;
115   &prepare_invoice;
116   if ($form->{print_and_post}) {
117     $form->{language_id} = $language_id;
118     $form->{printer_id} = $printer_id;
119   }
120
121   &display_form;
122
123   $main::lxdebug->leave_sub();
124 }
125
126 sub invoice_links {
127   $main::lxdebug->enter_sub();
128
129   my $form     = $main::form;
130   my %myconfig = %main::myconfig;
131
132   $main::auth->assert('invoice_edit');
133
134   $form->{vc} = 'customer';
135
136   # create links
137   $form->{webdav}   = $main::webdav;
138   $form->{lizenzen} = $main::lizenzen;
139
140   $form->create_links("AR", \%myconfig, "customer");
141
142   if ($form->{all_customer}) {
143     unless ($form->{customer_id}) {
144       $form->{customer_id} = $form->{all_customer}->[0]->{id};
145       $form->{salesman_id} = $form->{all_customer}->[0]->{salesman_id};
146     }
147   }
148
149   $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 $main::editing;
164
165   # build vendor/customer drop down comatibility... don't ask
166   if (@{ $form->{"all_customer"} }) {
167     $form->{"selectcustomer"} = 1;
168     $form->{customer}         = qq|$form->{customer}--$form->{"customer_id"}|;
169   }
170
171   $form->{"oldcustomer"}  = $form->{customer};
172
173   if ($form->{"oldcustomer"} !~ m/--\d+$/ && $form->{"customer_id"}) {
174     $form->{"oldcustomer"} .= qq|--$form->{"customer_id"}|
175   }
176
177
178 #  $form->{oldcustomer} = "$form->{customer}--$form->{customer_id}";
179 #  $form->{selectcustomer} = 1;
180
181   $form->{employee} = "$form->{employee}--$form->{employee_id}";
182
183   # forex
184   $form->{forex} = $form->{exchangerate};
185   my $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
186
187   foreach my $key (keys %{ $form->{AR_links} }) {
188     foreach my $ref (@{ $form->{AR_links}{$key} }) {
189       $form->{"select$key"} .= "<option>$ref->{accno}--$ref->{description}</option>\n";
190     }
191
192     if ($key eq "AR_paid") {
193       next unless $form->{acc_trans}{$key};
194       for my $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
195         $form->{"AR_paid_$i"}      = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
196
197         # reverse paid
198         $form->{"paid_$i"}         = $form->{acc_trans}{$key}->[$i - 1]->{amount} * -1;
199         $form->{"datepaid_$i"}     = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
200         $form->{"exchangerate_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
201         $form->{"forex_$i"}        = $form->{"exchangerate_$i"};
202         $form->{"source_$i"}       = $form->{acc_trans}{$key}->[$i - 1]->{source};
203         $form->{"memo_$i"}         = $form->{acc_trans}{$key}->[$i - 1]->{memo};
204
205         $form->{paidaccounts} = $i;
206       }
207     } else {
208       $form->{$key} = "$form->{acc_trans}{$key}->[0]->{accno}--$form->{acc_trans}{$key}->[0]->{description}";
209     }
210   }
211
212   $form->{paidaccounts} = 1 unless (exists $form->{paidaccounts});
213
214   $form->{AR} = $form->{AR_1} unless $form->{id};
215
216   $form->{locked} = ($form->datetonum($form->{invdate},  \%myconfig)
217                   <= $form->datetonum($form->{closedto}, \%myconfig));
218
219   $main::lxdebug->leave_sub();
220 }
221
222 sub prepare_invoice {
223   $main::lxdebug->enter_sub();
224
225   my $form     = $main::form;
226   my %myconfig = %main::myconfig;
227
228   $main::auth->assert('invoice_edit');
229
230   if ($form->{type} eq "credit_note") {
231     $form->{type}     = "credit_note";
232     $form->{formname} = "credit_note";
233   } else {
234     $form->{type}     = "invoice";
235     $form->{formname} = "invoice";
236   }
237
238   if ($form->{id}) {
239
240     my $i = 0;
241
242     foreach my $ref (@{ $form->{invoice_details} }) {
243       $i++;
244
245       map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
246
247       $form->{"discount_$i"}   = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100);
248       my ($dec)                = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
249       $dec                     = length $dec;
250       my $decimalplaces        = ($dec > 2) ? $dec : 2;
251
252       $form->{"sellprice_$i"}  = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
253       (my $dec_qty)            = ($form->{"qty_$i"} =~ /\.(\d+)/);
254       $dec_qty                 = length $dec_qty;
255
256       $form->{"qty_$i"}        = $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
257
258       $form->{rowcount}        = $i;
259
260     }
261
262     # get pricegroups for parts
263     IS->get_pricegroups_for_parts(\%myconfig, \%$form);
264     set_pricegroup($_) for 1 .. $form->{rowcount};
265   }
266   $main::lxdebug->leave_sub();
267 }
268
269 sub form_header {
270   $main::lxdebug->enter_sub();
271
272   my $form     = $main::form;
273   my %myconfig = %main::myconfig;
274   my $locale   = $main::locale;
275   my $cgi      = $main::cgi;
276
277   $main::auth->assert('invoice_edit');
278
279   our %TMPL_VAR = ();
280   my @custom_hiddens;
281
282   $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
283   $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
284
285   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
286   $form->{radier}          = ($form->current_date(\%myconfig) eq $form->{gldate}) ? 1 : 0;
287
288   my $set_duedate_url = "$form->{script}?action=set_duedate";
289
290   push @ { $form->{AJAX} }, new CGI::Ajax( 'set_duedate' => $set_duedate_url );
291
292   my @old_project_ids = ($form->{"globalproject_id"});
293   map { push @old_project_ids, $form->{"project_id_$_"} if $form->{"project_id_$_"}; } 1..$form->{"rowcount"};
294
295   $form->get_lists("contacts"      => "ALL_CONTACTS",
296                    "shipto"        => "ALL_SHIPTO",
297                    "projects"      => { "key"    => "ALL_PROJECTS",
298                                         "all"    => 0,
299                                         "old_id" => \@old_project_ids },
300                    "employees"     => "ALL_EMPLOYEES",
301                    "salesmen"      => "ALL_SALESMEN",
302                    "taxzones"      => "ALL_TAXZONES",
303                    "currencies"    => "ALL_CURRENCIES",
304                    "customers"     => "ALL_CUSTOMERS",
305                    "price_factors" => "ALL_PRICE_FACTORS");
306
307   $TMPL_VAR{sales_employee_labels} = sub { $_[0]->{name} || $_[0]->{login} };
308   $TMPL_VAR{shipto_labels}         = sub { join "; ", grep { $_ } map { $_[0]->{"shipto${_}" } } qw(name department_1 street city) };
309   $TMPL_VAR{contact_labels}        = sub { join(', ', $_[0]->{"cp_name"}, $_[0]->{"cp_givenname"}) . ($_[0]->{cp_abteilung} ? " ($_[0]->{cp_abteilung})" : "") };
310   $TMPL_VAR{department_labels}     = sub { "$_[0]->{description}--$_[0]->{id}" };
311
312   # customer
313   $TMPL_VAR{vc_keys} = sub { "$_[0]->{name}--$_[0]->{id}" };
314   $TMPL_VAR{vclimit} = $myconfig{vclimit};
315   $TMPL_VAR{vc_select} = "customer_or_vendor_selection_window('customer', '', 0, 0)";
316   push @custom_hiddens, "customer_id";
317   push @custom_hiddens, "oldcustomer";
318   push @custom_hiddens, "selectcustomer";
319
320   # currencies and exchangerate
321   my @values = map { $_       } @{ $form->{ALL_CURRENCIES} };
322   my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
323   $form->{currency}            = $form->{defaultcurrency} unless $form->{currency};
324   $TMPL_VAR{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
325   $TMPL_VAR{currencies}        = NTI($cgi->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
326                                                       '-values' => \@values, '-labels' => \%labels)) if scalar @values;
327   push @custom_hiddens, "forex";
328   push @custom_hiddens, "exchangerate" if $form->{forex};
329
330   $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
331   $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
332
333   $form->{fokus} = "invoice.customer";
334
335   my $follow_up_vc         =  $form->{customer};
336   $follow_up_vc            =~ s/--\d*\s*$//;
337   $TMPL_VAR{customer_name} = $follow_up_vc;
338
339 # set option selected
340   foreach my $item (qw(AR)) {
341     $form->{"select$item"} =~ s/ selected//;
342     $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
343   }
344
345   $TMPL_VAR{is_type_credit_note} = $form->{type}   eq "credit_note";
346   $TMPL_VAR{is_format_html}      = $form->{format} eq 'html';
347   $TMPL_VAR{dateformat}          = $myconfig{dateformat};
348   $TMPL_VAR{numberformat}        = $myconfig{numberformat};
349
350   # hiddens
351   $TMPL_VAR{HIDDENS} = [qw(
352     id action type media format queued printed emailed title vc discount
353     title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
354     max_dunning_level dunning_amount
355     shiptoname shiptostreet shiptozipcode shiptocity shiptocountry  shiptocontact shiptophone shiptofax
356     shiptoemail shiptodepartment_1 shiptodepartment_2 message email subject cc bcc taxaccounts cursor_fokus
357     convert_from_do_ids convert_from_oe_ids
358   ), @custom_hiddens,
359   map { $_.'_rate', $_.'_description', $_.'_taxnumber' } split / /, $form->{taxaccounts}];
360
361   $form->{jsscript} = 1;
362   $form->header();
363
364   print $form->parse_html_template("is/form_header", \%TMPL_VAR);
365
366   $main::lxdebug->leave_sub();
367 }
368
369 sub form_footer {
370   $main::lxdebug->enter_sub();
371
372   my $form     = $main::form;
373   my %myconfig = %main::myconfig;
374   my $locale   = $main::locale;
375
376   $main::auth->assert('invoice_edit');
377
378   $form->{invtotal}    = $form->{invsubtotal};
379   $form->{oldinvtotal} = $form->{invtotal};
380
381   # note rows
382   $form->{rows} = max 2,
383     $form->numtextrows($form->{notes},    26, 8),
384     $form->numtextrows($form->{intnotes}, 35, 8);
385
386
387   # tax, total and subtotal calculations
388   my ($tax, $subtotal);
389   $form->{taxaccounts_array} = [ split / /, $form->{taxaccounts} ];
390
391   foreach my $item (@{ $form->{taxaccounts_array} }) {
392     if ($form->{"${item}_base"}) {
393       if ($form->{taxincluded}) {
394         $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
395                                                                                  / (1 + $form->{"${item}_rate"})), 2);
396         $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
397       } else {
398         $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
399         $form->{invtotal} += $form->{"${item}_total"};
400       }
401     }
402   }
403
404   # follow ups
405   if ($form->{id}) {
406     $form->{follow_ups}            = FU->follow_ups('trans_id' => $form->{id}) || [];
407     $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
408   }
409
410   # payments
411   my $totalpaid = 0;
412   $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
413   $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
414
415   for my $i (1 .. $form->{paidaccounts}) {
416     $form->{"selectAR_paid_$i"} = $form->{selectAR_paid};
417     $form->{"selectAR_paid_$i"} =~ s/option>\Q$form->{"AR_paid_$i"}\E/option selected>$form->{"AR_paid_$i"}/;
418     $totalpaid += $form->{"paid_$i"};
419   }
420
421   print $form->parse_html_template('is/form_footer', {
422     is_type_credit_note => ($form->{type} eq "credit_note"),
423     totalpaid           => $totalpaid,
424     paid_missing        => $form->{invtotal} - $totalpaid,
425     print_options       => print_options(inline => 1),
426     show_storno         => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ar") && !$totalpaid,
427     show_delete         => ($form->current_date(\%myconfig) eq $form->{gldate}),
428   });
429 ##print $form->parse_html_template('is/_payments'); # parser
430 ##print $form->parse_html_template('webdav/_list'); # parser
431
432   $main::lxdebug->leave_sub();
433 }
434
435 sub mark_as_paid {
436   $main::lxdebug->enter_sub();
437
438   my $form     = $main::form;
439   my %myconfig = %main::myconfig;
440
441   $main::auth->assert('invoice_edit');
442
443   &mark_as_paid_common(\%myconfig,"ar");
444
445   $main::lxdebug->leave_sub();
446 }
447
448 sub update {
449   $main::lxdebug->enter_sub();
450
451   my $form     = $main::form;
452   my %myconfig = %main::myconfig;
453
454   $main::auth->assert('invoice_edit');
455
456   my ($recursive_call) = shift;
457
458 #  map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) } qw(exchangerate creditlimit creditremaining) unless $recursive_call;
459
460   $form->{print_and_post} = 0         if $form->{second_run};
461   my $taxincluded            = "checked" if $form->{taxincluded};
462   $form->{update} = 1;
463
464   &check_name("customer");
465
466   $form->{taxincluded} ||= $taxincluded;
467
468   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
469   $form->{exchangerate} = $form->{forex} if $form->{forex};
470
471   for my $i (1 .. $form->{paidaccounts}) {
472     next unless $form->{"paid_$i"};
473     map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
474     $form->{"forex_$i"}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
475     $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
476   }
477
478   my $i            = $form->{rowcount};
479   my $exchangerate = $form->{exchangerate} || 1;
480
481   # if last row empty, check the form otherwise retrieve new item
482   if (   ($form->{"partnumber_$i"} eq "")
483       && ($form->{"description_$i"} eq "")
484       && ($form->{"partsgroup_$i"}  eq "")) {
485
486     $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
487     &check_form;
488
489   } else {
490
491     IS->retrieve_item(\%myconfig, \%$form);
492
493     my $rows = scalar @{ $form->{item_list} };
494
495     $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{customer_discount} * 100);
496
497     if ($rows) {
498       $form->{"qty_$i"} = ($form->{"qty_$i"} * 1) ? $form->{"qty_$i"} : 1;
499
500       if ($rows > 1) {
501
502         &select_item;
503         exit;
504
505       } else {
506
507         my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
508
509         map { $form->{item_list}[$i]{$_} =~ s/\"/&quot;/g } qw(partnumber description unit);
510         map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
511
512         $form->{payment_id}    = $form->{"part_payment_id_$i"} if $form->{"part_payment_id_$i"} ne "";
513         $form->{"discount_$i"} = 0                             if $form->{"not_discountable_$i"};
514
515         $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
516
517         ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
518         my $decimalplaces = max 2, length $1;
519
520         if ($sellprice) {
521           $form->{"sellprice_$i"} = $sellprice;
522         } else {
523           # if there is an exchange rate adjust sellprice
524           $form->{"sellprice_$i"} *= (1 - $form->{tradediscount});
525           $form->{"sellprice_$i"} /= $exchangerate;
526         }
527
528         $form->{"listprice_$i"} /= $exchangerate;
529
530         my $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"} / 100);
531         map { $form->{"${_}_base"} = 0 }                                 split / /, $form->{taxaccounts};
532         map { $form->{"${_}_base"} += $amount }                          split / /, $form->{"taxaccounts_$i"};
533         map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{"taxaccounts_$i"} if !$form->{taxincluded};
534
535         $form->{creditremaining} -= $amount;
536
537         map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces) } qw(sellprice listprice);
538
539         $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"});
540
541         if ($main::lizenzen) {
542           if ($form->{"inventory_accno_$i"} ne "") {
543             $form->{"lizenzen_$i"} = qq|<option></option>|;
544             foreach my $item (@{ $form->{LIZENZEN}{ $form->{"id_$i"} } }) {
545               $form->{"lizenzen_$i"} .= qq|<option value="$item->{"id"}">$item->{"licensenumber"}</option>|;
546             }
547             $form->{"lizenzen_$i"} .= qq|<option value=-1>Neue Lizenz</option>|;
548           }
549         }
550
551         # get pricegroups for parts
552         IS->get_pricegroups_for_parts(\%myconfig, \%$form);
553
554         # build up html code for prices_$i
555         &set_pricegroup($i);
556       }
557
558       &display_form;
559
560     } else {
561
562       # ok, so this is a new part
563       # ask if it is a part or service item
564
565       if (   $form->{"partsgroup_$i"}
566           && ($form->{"partsnumber_$i"} eq "")
567           && ($form->{"description_$i"} eq "")) {
568         $form->{rowcount}--;
569         $form->{"discount_$i"} = "";
570         display_form();
571
572       } else {
573         $form->{"id_$i"}   = 0;
574         new_item();
575       }
576     }
577   }
578   $main::lxdebug->leave_sub();
579 }
580
581 sub post_payment {
582   $main::lxdebug->enter_sub();
583
584   my $form     = $main::form;
585   my %myconfig = %main::myconfig;
586   my $locale   = $main::locale;
587
588   $main::auth->assert('invoice_edit');
589
590   our $invdate;
591
592   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
593   for my $i (1 .. $form->{paidaccounts}) {
594     if ($form->{"paid_$i"}) {
595       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
596
597       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
598
599       $form->error($locale->text('Cannot post payment for a closed period!'))
600         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
601
602       if ($form->{currency} ne $form->{defaultcurrency}) {
603         $form->{"exchangerate_$i"} = $form->{exchangerate}
604           if ($invdate == $datepaid);
605         $form->isblank("exchangerate_$i",
606                        $locale->text('Exchangerate for payment missing!'));
607       }
608     }
609   }
610
611   ($form->{AR})      = split /--/, $form->{AR};
612   ($form->{AR_paid}) = split /--/, $form->{AR_paid};
613   relink_accounts();
614   $form->redirect($locale->text('Payment posted!'))
615       if (IS->post_payment(\%myconfig, \%$form));
616     $form->error($locale->text('Cannot post payment!'));
617
618
619   $main::lxdebug->leave_sub();
620 }
621
622 sub post {
623   $main::lxdebug->enter_sub();
624
625   my $form     = $main::form;
626   my %myconfig = %main::myconfig;
627   my $locale   = $main::locale;
628
629   $main::auth->assert('invoice_edit');
630
631   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
632   $form->isblank("invdate",  $locale->text('Invoice Date missing!'));
633   $form->isblank("customer", $locale->text('Customer missing!'));
634   $form->error($locale->text('Cannot post invoice for a closed period!'))
635         if ($form->date_closed($form->{"invdate"}, \%myconfig));
636
637   $form->{invnumber} =~ s/^\s*//g;
638   $form->{invnumber} =~ s/\s*$//g;
639
640   # if oldcustomer ne customer redo form
641   if (&check_name('customer')) {
642     &update;
643     exit;
644   }
645   if ($form->{second_run}) {
646     $form->{print_and_post} = 0;
647   }
648
649   &validate_items;
650
651   my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
652   my $invdate  = $form->datetonum($form->{invdate},  \%myconfig);
653
654   $form->error($locale->text('Cannot post invoice for a closed period!'))
655     if ($invdate <= $closedto);
656
657   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
658     if ($form->{currency} ne $form->{defaultcurrency});
659
660   for my $i (1 .. $form->{paidaccounts}) {
661     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
662       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
663
664       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
665
666       $form->error($locale->text('Cannot post payment for a closed period!'))
667         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
668
669       if ($form->{currency} ne $form->{defaultcurrency}) {
670         $form->{"exchangerate_$i"} = $form->{exchangerate}
671           if ($invdate == $datepaid);
672         $form->isblank("exchangerate_$i",
673                        $locale->text('Exchangerate for payment missing!'));
674       }
675     }
676   }
677
678   ($form->{AR})        = split /--/, $form->{AR};
679   ($form->{AR_paid})   = split /--/, $form->{AR_paid};
680   $form->{storno}    ||= 0;
681
682   $form->{label} = $locale->text('Invoice');
683
684   $form->{id} = 0 if $form->{postasnew};
685
686   # get new invnumber in sequence if no invnumber is given or if posasnew was requested
687   if ($form->{postasnew}) {
688     if ($form->{type} eq "credit_note") {
689       undef($form->{cnnumber});
690     } else {
691       undef($form->{invnumber});
692     }
693   }
694
695   relink_accounts();
696   $form->error($locale->text('Cannot post invoice!'))
697     unless IS->post_invoice(\%myconfig, \%$form);
698   remove_draft() if $form->{remove_draft};
699
700   if(!exists $form->{addition}) {
701     $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
702     $form->{addition} = $print_post     ? "PRINTED AND POSTED" :
703                         $form->{storno} ? "STORNO"             :
704                                           "POSTED";
705     $form->save_history($form->dbconnect(\%myconfig));
706   }
707
708   $form->redirect( $form->{label} . " $form->{invnumber} " . $locale->text('posted!'))
709     unless $print_post;
710
711   $main::lxdebug->leave_sub();
712 }
713
714 sub print_and_post {
715   $main::lxdebug->enter_sub();
716
717   my $form     = $main::form;
718
719   $main::auth->assert('invoice_edit');
720
721   my $old_form               = new Form;
722   $print_post             = 1;
723   $form->{print_and_post} = 1;
724   &post();
725
726   &edit();
727   $main::lxdebug->leave_sub();
728
729 }
730
731 sub use_as_template {
732   $main::lxdebug->enter_sub();
733
734   my $form     = $main::form;
735   my %myconfig = %main::myconfig;
736
737   $main::auth->assert('invoice_edit');
738
739   map { delete $form->{$_} } qw(printed emailed queued invnumber invdate deliverydate id datepaid_1 source_1 memo_1 paid_1 exchangerate_1 AP_paid_1 storno);
740   $form->{paidaccounts} = 1;
741   $form->{rowcount}--;
742   $form->{invdate} = $form->current_date(\%myconfig);
743   &display_form;
744
745   $main::lxdebug->leave_sub();
746 }
747
748 sub storno {
749   $main::lxdebug->enter_sub();
750
751   my $form     = $main::form;
752   my %myconfig = %main::myconfig;
753   my $locale   = $main::locale;
754
755   $main::auth->assert('invoice_edit');
756
757   if ($form->{storno}) {
758     $form->error($locale->text('Cannot storno storno invoice!'));
759   }
760
761   if (IS->has_storno(\%myconfig, $form, "ar")) {
762     $form->error($locale->text("Invoice has already been storno'd!"));
763   }
764
765   map({ my $key = $_; delete($form->{$key}) unless (grep({ $key eq $_ } qw(id login password stylesheet type))); } keys(%{ $form }));
766
767   invoice_links();
768   prepare_invoice();
769   relink_accounts();
770
771   # Payments must not be recorded for the new storno invoice.
772   $form->{paidaccounts} = 0;
773   map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
774
775   $form->{storno_id} = $form->{id};
776   $form->{storno} = 1;
777   $form->{id} = "";
778   $form->{invnumber} = "Storno zu " . $form->{invnumber};
779   $form->{rowcount}++;
780
781   post();
782   $main::lxdebug->leave_sub();
783 }
784
785 sub preview {
786   $main::lxdebug->enter_sub();
787
788   my $form     = $main::form;
789
790   $main::auth->assert('invoice_edit');
791
792   $form->{preview} = 1;
793   my $old_form = new Form;
794   for (keys %$form) { $old_form->{$_} = $form->{$_} }
795
796   &print_form($old_form);
797   $main::lxdebug->leave_sub();
798
799 }
800
801 sub delete {
802   $main::lxdebug->enter_sub();
803
804   my $form     = $main::form;
805   my $locale   = $main::locale;
806
807   $main::auth->assert('invoice_edit');
808
809   if ($form->{second_run}) {
810     $form->{print_and_post} = 0;
811   }
812   $form->header;
813
814   print qq|
815 <body>
816
817 <form method="post" action="$form->{script}">
818 |;
819
820   # delete action variable
821   map { delete $form->{$_} } qw(action header);
822
823   foreach my $key (keys %$form) {
824     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
825     $form->{$key} =~ s/\"/&quot;/g;
826     print qq|<input type="hidden" name="$key" value="$form->{$key}">\n|;
827   }
828
829   print qq|
830 <h2 class="confirm">| . $locale->text('Confirm!') . qq|</h2>
831
832 <h4>|
833     . $locale->text('Are you sure you want to delete Invoice Number')
834     . qq| $form->{invnumber}
835 </h4>
836
837 <p>
838 <input name="action" class="submit" type="submit" value="|
839     . $locale->text('Yes') . qq|">
840 </form>
841 |;
842
843   $main::lxdebug->leave_sub();
844 }
845
846 sub credit_note {
847   $main::lxdebug->enter_sub();
848
849   my $form     = $main::form;
850   my %myconfig = %main::myconfig;
851   my $locale   = $main::locale;
852
853   $main::auth->assert('invoice_edit');
854
855   $form->{transdate} = $form->{invdate} = $form->current_date(\%myconfig);
856   $form->{duedate} =
857     $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
858
859   $form->{id}     = '';
860   $form->{rowcount}--;
861   $form->{shipto} = 1;
862
863
864   $form->{title}  = $locale->text('Add Credit Note');
865   $form->{script} = 'is.pl';
866   our $script         = "is";
867   our $buysell        = 'buy';
868
869
870   # bo creates the id, reset it
871   map { delete $form->{$_} }
872     qw(id invnumber subject message cc bcc printed emailed queued);
873   $form->{ $form->{vc} } =~ s/--.*//g;
874   $form->{type} = "credit_note";
875
876
877   map { $form->{"select$_"} = "" } ($form->{vc}, 'currency');
878
879 #  map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
880 #    qw(creditlimit creditremaining);
881
882   my $currency = $form->{currency};
883   &invoice_links;
884
885   $form->{currency}     = $currency;
886   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, $buysell);
887   $form->{exchangerate} = $form->{forex} || '';
888
889   $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
890
891   &prepare_invoice;
892
893
894   &display_form;
895
896   $main::lxdebug->leave_sub();
897 }
898
899 sub yes {
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   if (IS->delete_invoice(\%myconfig, \%$form, $main::spool)) {
909     # saving the history
910         if(!exists $form->{addition}) {
911     $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
912           $form->{addition} = "DELETED";
913           $form->save_history($form->dbconnect(\%myconfig));
914     }
915     # /saving the history
916     $form->redirect($locale->text('Invoice deleted!'));
917   }
918   $form->error($locale->text('Cannot delete invoice!'));
919
920   $main::lxdebug->leave_sub();
921 }
922
923 sub e_mail {
924   $main::lxdebug->enter_sub();
925
926   my $form     = $main::form;
927
928   $main::auth->assert('invoice_edit');
929
930   if (!$form->{id}) {
931     $print_post = 1;
932
933     my $saved_form = save_form();
934
935     post();
936
937     restore_form($saved_form, 0, qw(id invnumber));
938   }
939
940   edit_e_mail();
941
942   $main::lxdebug->leave_sub();
943 }