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