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