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