0e67ed4750ab20c337b26949530390b47bd0cc4e
[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
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   $edit = 1;
100   my ($language_id, $printer_id);
101   if ($form->{print_and_post}) {
102     $form->{action}   = "print";
103     $form->{resubmit} = 1;
104     $language_id = $form->{language_id};
105     $printer_id = $form->{printer_id};
106   }
107   &invoice_links;
108   &prepare_invoice;
109   if ($form->{print_and_post}) {
110     $form->{language_id} = $language_id;
111     $form->{printer_id} = $printer_id;
112   }
113
114   &display_form;
115
116   $main::lxdebug->leave_sub();
117 }
118
119 sub invoice_links {
120   $main::lxdebug->enter_sub();
121
122   my $form     = $main::form;
123   my %myconfig = %main::myconfig;
124
125   $main::auth->assert('invoice_edit');
126
127   $form->{vc} = 'customer';
128
129   # create links
130   $form->{webdav}   = $main::webdav;
131   $form->{lizenzen} = $main::lizenzen;
132
133   $form->create_links("AR", \%myconfig, "customer");
134
135   if ($form->{all_customer}) {
136     unless ($form->{customer_id}) {
137       $form->{customer_id} = $form->{all_customer}->[0]->{id};
138       $form->{salesman_id} = $form->{all_customer}->[0]->{salesman_id};
139     }
140   }
141
142   my $payment_id;
143   if ($form->{payment_id}) {
144     $payment_id = $form->{payment_id};
145   }
146   my $language_id;
147   if ($form->{language_id}) {
148     $language_id = $form->{language_id};
149   }
150   my $taxzone_id;
151   if ($form->{taxzone_id}) {
152     $taxzone_id = $form->{taxzone_id};
153   }
154   my $id;
155   if ($form->{id}) {
156     $id = $form->{id};
157   }
158   my $shipto_id;
159   if ($form->{shipto_id}) {
160     $shipto_id = $form->{shipto_id};
161   }
162
163   my $cp_id = $form->{cp_id};
164   IS->get_customer(\%myconfig, \%$form);
165
166   #quote all_customer Bug 133
167   foreach my $ref (@{ $form->{all_customer} }) {
168     $ref->{name} = $form->quote($ref->{name});
169   }
170   if ($id) {
171     $form->{id} = $id;
172   }
173   IS->retrieve_invoice(\%myconfig, \%$form);
174   $form->{cp_id} = $cp_id;
175
176   if ($payment_id) {
177     $form->{payment_id} = $payment_id;
178   }
179   if ($language_id) {
180     $form->{language_id} = $language_id;
181   }
182   if ($taxzone_id) {
183     $form->{taxzone_id} = $taxzone_id;
184   }
185   if ($shipto_id) {
186     $form->{shipto_id} = $shipto_id;
187   }
188
189   $form->{oldcustomer} = "$form->{customer}--$form->{customer_id}";
190
191   # departments
192   if ($form->{all_departments}) {
193     $form->{selectdepartment} = "<option>\n";
194     $form->{department}       = "$form->{department}--$form->{department_id}";
195
196     map {
197       $form->{selectdepartment} .=
198         "<option>$_->{description}--$_->{id}</option>\n"
199     } (@{ $form->{all_departments} });
200   }
201
202   $form->{employee} = "$form->{employee}--$form->{employee_id}";
203
204   # forex
205   $form->{forex} = $form->{exchangerate};
206   my $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
207
208   foreach my $key (keys %{ $form->{AR_links} }) {
209     foreach my $ref (@{ $form->{AR_links}{$key} }) {
210       $form->{"select$key"} .=
211 "<option>$ref->{accno}--$ref->{description}</option>\n";
212     }
213
214     if ($key eq "AR_paid") {
215       next unless $form->{acc_trans}{$key};
216       for my $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
217         $form->{"AR_paid_$i"} =
218           "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
219
220         # reverse paid
221         $form->{"paid_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{amount} * -1;
222         $form->{"datepaid_$i"} =
223           $form->{acc_trans}{$key}->[$i - 1]->{transdate};
224         $form->{"forex_$i"} = $form->{"exchangerate_$i"} =
225           $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
226         $form->{"source_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{source};
227         $form->{"memo_$i"}   = $form->{acc_trans}{$key}->[$i - 1]->{memo};
228
229         $form->{paidaccounts} = $i;
230       }
231     } else {
232       $form->{$key} =
233         "$form->{acc_trans}{$key}->[0]->{accno}--$form->{acc_trans}{$key}->[0]->{description}";
234     }
235
236   }
237
238   $form->{paidaccounts} = 1 unless (exists $form->{paidaccounts});
239
240   $form->{AR} = $form->{AR_1} unless $form->{id};
241
242   $form->{locked} =
243     ($form->datetonum($form->{invdate}, \%myconfig) <=
244      $form->datetonum($form->{closedto}, \%myconfig));
245
246   $main::lxdebug->leave_sub();
247 }
248
249 sub prepare_invoice {
250   $main::lxdebug->enter_sub();
251
252   my $form     = $main::form;
253   my %myconfig = %main::myconfig;
254
255   $main::auth->assert('invoice_edit');
256
257   if ($form->{type} eq "credit_note") {
258     $form->{type}     = "credit_note";
259     $form->{formname} = "credit_note";
260   } else {
261     $form->{type}     = "invoice";
262     $form->{formname} = "invoice";
263   }
264
265   if ($form->{id}) {
266
267     my $i = 0;
268
269     foreach my $ref (@{ $form->{invoice_details} }) {
270       $i++;
271
272       map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
273
274       $form->{"discount_$i"}   = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100);
275       my ($dec)                = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
276       $dec                     = length $dec;
277       my $decimalplaces        = ($dec > 2) ? $dec : 2;
278
279       $form->{"sellprice_$i"}  = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
280       (my $dec_qty)            = ($form->{"qty_$i"} =~ /\.(\d+)/);
281       $dec_qty                 = length $dec_qty;
282
283       $form->{"qty_$i"}        = $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
284
285       $form->{rowcount}        = $i;
286
287     }
288
289     # get pricegroups for parts
290     IS->get_pricegroups_for_parts(\%myconfig, \%$form);
291     set_pricegroup($_) for 1 .. $form->{rowcount};
292   }
293   $main::lxdebug->leave_sub();
294 }
295
296 sub form_header {
297   $main::lxdebug->enter_sub();
298
299   my $form     = $main::form;
300   my %myconfig = %main::myconfig;
301   my $locale   = $main::locale;
302   my $cgi      = $main::cgi;
303
304   $main::auth->assert('invoice_edit');
305
306   our %TMPL_VAR = ();
307   my @custom_hiddens;
308
309   $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
310   $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
311
312   if ($edit) {
313     if ($form->{type} eq "credit_note") {
314       $form->{title} = $locale->text('Edit Credit Note');
315       $form->{title} = $locale->text('Edit Storno Credit Note') if $form->{storno};
316     } else {
317       $form->{title} = $locale->text('Edit Sales Invoice');
318       $form->{title} = $locale->text('Edit Storno Invoice')     if $form->{storno};
319     }
320   }
321   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
322   $form->{radier}          = ($form->current_date(\%myconfig) eq $form->{gldate}) ? 1 : 0;
323
324   $payment = qq|<option value=""></option>|;
325   foreach my $item (@{ $form->{payment_terms} }) {
326     if ($form->{payment_id} eq $item->{id}) {
327       $payment .= qq|<option value="$item->{id}" selected>$item->{description}</option>|;
328     } else {
329       $payment .= qq|<option value="$item->{id}">$item->{description}</option>|;
330     }
331   }
332
333   my $set_duedate_url = "$form->{script}?action=set_duedate";
334
335   my $pjx = new CGI::Ajax( 'set_duedate' => $set_duedate_url );
336   push(@ { $form->{AJAX} }, $pjx);
337
338   my @old_project_ids = ($form->{"globalproject_id"});
339   map { push @old_project_ids, $form->{"project_id_$_"} if $form->{"project_id_$_"}; } 1..$form->{"rowcount"};
340
341   $form->get_lists("contacts"      => "ALL_CONTACTS",
342                    "shipto"        => "ALL_SHIPTO",
343                    "projects"      => { "key"    => "ALL_PROJECTS",
344                                         "all"    => 0,
345                                         "old_id" => \@old_project_ids },
346                    "employees"     => "ALL_EMPLOYEES",
347                    "salesmen"      => "ALL_SALESMEN",
348                    "taxzones"      => "ALL_TAXZONES",
349                    "currencies"    => "ALL_CURRENCIES",
350                    "customers"     => "ALL_CUSTOMERS",
351                    "price_factors" => "ALL_PRICE_FACTORS");
352
353   $TMPL_VAR{sales_employee_labels} = sub { $_[0]->{name} || $_[0]->{login} };
354   $TMPL_VAR{shipto_labels}         = sub { join "; ", grep { $_ } map { $_[0]->{"shipto${_}" } } qw(name department_1 street city) };
355   $TMPL_VAR{contact_labels}        = sub { join(', ', $_[0]->{"cp_name"}, $_[0]->{"cp_givenname"}) . ($_[0]->{cp_abteilung} ? " ($_[0]->{cp_abteilung})" : "") };
356   $TMPL_VAR{department_labels}     = sub { "$_[0]->{description}--$_[0]->{id}" };
357
358   # customer
359   $TMPL_VAR{vc_keys} = sub { "$_[0]->{name}--$_[0]->{id}" };
360   $TMPL_VAR{vclimit} = $myconfig{vclimit};
361   $TMPL_VAR{vc_select} = "customer_or_vendor_selection_window('$form->{vc}', '', @{[ $form->{vc} eq 'vendor' ? 1 : 0 ]}, 0)";
362   push @custom_hiddens, "$form->{vc}_id";
363   push @custom_hiddens, "old$form->{vc}";
364   push @custom_hiddens, "select$form->{vc}";
365
366   # currencies and exchangerate
367   my @values = map { $_       } @{ $form->{ALL_CURRENCIES} };
368   my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
369   $form->{currency}            = $form->{defaultcurrency} unless $form->{currency};
370   $TMPL_VAR{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
371   $TMPL_VAR{currencies}        = NTI($cgi->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
372                                                       '-values' => \@values, '-labels' => \%labels)) if scalar @values;
373   push @custom_hiddens, "forex";
374   push @custom_hiddens, "exchangerate" if $form->{forex};
375
376   $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
377   $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
378
379   $form->{fokus} = "invoice.customer";
380
381   my $follow_up_vc         =  $form->{customer};
382   $follow_up_vc            =~ s/--\d*\s*$//;
383   $TMPL_VAR{customer_name} = $follow_up_vc;
384
385 # set option selected
386   foreach my $item (qw(AR customer currency department employee)) {
387     $form->{"select$item"} =~ s/ selected//;
388     $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
389   }
390
391   $TMPL_VAR{is_type_credit_note} = $form->{type} eq "credit_note";
392   $TMPL_VAR{is_format_html} = $form->{format} eq 'html';
393   $TMPL_VAR{dateformat} = $myconfig{dateformat};
394   $TMPL_VAR{numberformat} = $myconfig{numberformat};
395
396   # hiddens
397   $TMPL_VAR{HIDDEN} = [qw(
398     id action type media format queued printed emailed title vc discount
399     creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
400     max_dunning_level dunning_amount
401     shiptoname shiptostreet shiptozipcode shiptocity shiptocountry  shiptocontact shiptophone shiptofax
402     shiptoemail shiptodepartment_1 shiptodepartment_2 message email subject cc bcc taxaccounts cursor_fokus
403     convert_from_do_ids convert_from_oe_ids
404   ), @custom_hiddens,
405   map { $_.'_rate', $_.'_description', $_.'_taxnumber' } split / /, $form->{taxaccounts}];
406
407   $form->{jsscript} = 1;
408   $form->header();
409
410 #  print qq|
411 #<body onLoad="$onload">
412 #<script type="text/javascript" src="js/common.js"></script>
413 #<script type="text/javascript" src="js/delivery_customer_selection.js"></script>
414 #<script type="text/javascript" src="js/vendor_selection.js"></script>
415 #<script type="text/javascript" src="js/calculate_qty.js"></script>
416 #<script type="text/javascript" src="js/follow_up.js"></script>
417 #
418 #<form method="post" name="invoice" action="$form->{script}">
419 #| ;
420 #
421 #  $form->hide_form(qw(id action type media format queued printed emailed title vc discount
422 #                      creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
423 #                      max_dunning_level dunning_amount
424 #                      shiptoname shiptostreet shiptozipcode shiptocity shiptocountry  shiptocontact shiptophone shiptofax
425 #                      shiptoemail shiptodepartment_1 shiptodepartment_2 message email subject cc bcc taxaccounts cursor_fokus
426 #                      convert_from_do_ids convert_from_oe_ids),
427 #                      map { $_.'_rate', $_.'_description', $_.'_taxnumber' } split / /, $form->{taxaccounts} );
428 #
429 #  print qq|<p>$form->{saved_message}</p>| if $form->{saved_message};
430 #
431 #  print qq|
432 #
433 #<input type="hidden" name="follow_up_trans_id_1" value="| . H($form->{id}) . qq|">
434 #<input type="hidden" name="follow_up_trans_type_1" value="sales_invoice">
435 #<input type="hidden" name="follow_up_trans_info_1" value="| . H($follow_up_trans_info) . qq|">
436 #<input type="hidden" name="follow_up_rowcount" value="1">
437 #
438 #<input type="hidden" name="lizenzen" value="$lizenzen">
439 #
440 #<div class="listtop" width="100%">$form->{title}</div>
441 #
442 #<table width="100%">
443 #  <tr>
444 #    <td valign="top">
445 #      <table>
446 #        <tr>
447 #          $customers
448 #          <input type="hidden" name="customer_klass" value="| . H($form->{customer_klass}) . qq|">
449 #          <input type="hidden" name="customer_id" value="| . H($form->{customer_id}) . qq|">
450 #          <input type="hidden" name="oldcustomer" value="| . H($form->{oldcustomer}) . qq|">
451 #          <input type="hidden" name="selectcustomer" value="| . H($form->{selectcustomer}) . qq|">
452 #        </tr>
453 #        $contact
454 #        $shipto
455 #        <tr>
456 #          <td align="right">| . $locale->text('Credit Limit') . qq|</td>
457 #          <td>$form->{creditlimit}; | . $locale->text('Remaining') . qq| <span class="plus$n">$form->{creditremaining}</span></td>
458 #        </tr>
459 #        $dunning
460 #        $business
461 #             <tr>
462 #               <th align="right" nowrap>| . $locale->text('Record in') . qq|</th>
463 #               <td colspan="3"><select name="AR" style="width:250px;">$form->{selectAR}</select></td>
464 #               <input type="hidden" name="selectAR" value="$form->{selectAR}">
465 #             </tr>
466 #              $taxzone
467 #             $department
468 #             <tr>
469 #    $currencies
470 #               <input type="hidden" name="fxgain_accno" value="$form->{fxgain_accno}">
471 #               <input type="hidden" name="fxloss_accno" value="$form->{fxloss_accno}">
472 #               $exchangerate
473 #             </tr>
474 #             <tr>
475 #               <th align="right" nowrap>| . $locale->text('Shipping Point') . qq|</th>
476 #               <td colspan="3"> | .
477 #               $cgi->textfield("-name" => "shippingpoint", "-size" => 35, "-value" => $form->{shippingpoint}) .
478 #         qq|   </td>
479 #             </tr>
480 #             <tr>
481 #               <th align="right" nowrap>| . $locale->text('Ship via') . qq|</th>
482 #               <td colspan="3"> | .
483 #               $cgi->textfield("-name" => "shipvia", "-size" => 35, "-value" => $form->{shipvia}) .
484 #         qq|   </td>
485 #             </tr>
486 #              <tr>
487 #                <th align="right">| . $locale->text('Transaction description') . qq|</th>
488 #                <td colspan="3">| . $cgi->textfield("-name" => "transaction_description", "-size" => 35, "-value" => $form->{transaction_description}) . qq|</td>
489 #              </tr>|;
490 ##               <tr>
491 ##                 <td colspan=4>
492 ##                   <table>
493 ##                     <tr>
494 ##                       <td colspan=2>
495 ##                         <button type="button" onclick="delivery_customer_selection_window('delivery_customer_string','delivery_customer_id')">| . $locale->text('Choose Customer') . qq|</button>
496 ##                       </td>
497 ##                       <td colspan=2><input type=hidden name=delivery_customer_id value="$form->{delivery_customer_id}">
498 ##                       <input size=45 id=delivery_customer_string name=delivery_customer_string value="$form->{delivery_customer_string}"></td>
499 ##                     </tr>
500 ##                     <tr>
501 ##                       <td colspan=2>
502 ##                         <button type="button" onclick="vendor_selection_window('delivery_vendor_string','delivery_vendor_id')">| . $locale->text('Choose Vendor') . qq|</button>
503 ##                       </td>
504 ##                       <td colspan=2><input type=hidden name=delivery_vendor_id value="$form->{delivery_vendor_id}">
505 ##                       <input size=45 id=delivery_vendor_string name=delivery_vendor_string value="$form->{delivery_vendor_string}"></td>
506 ##                     </tr>
507 ##                   </table>
508 ##                 </td>
509 ##               </tr>
510 #print qq|          </table>
511 #         </td>
512 #         <td align="right" valign="top">
513 #           <table>
514 #             $employees
515 #        $salesman
516 #|;
517 #
518 ##ergänzung in der maske um das feld Lieferscheinnummer (Delivery Order Number), meiner meinung nach sinnvoll ueber dem feld lieferscheindatum 12.02.2009 jb
519 #if ($form->{type} eq "credit_note") {
520 #print qq|     <tr>
521 #               <th align="right" nowrap>| . $locale->text('Credit Note Number') . qq|</th>
522 #               <td> |.
523 #               $cgi->textfield("-name" => "invnumber", "-size" => 11, "-value" => $form->{invnumber}) .
524 #      qq|      </td>
525 #             </tr>
526 #             <tr>
527 #               <th align="right">| . $locale->text('Credit Note Date') . qq|</th>
528 #                $button1
529 #             </tr>|;
530 #} else {
531 #print qq|     <tr>
532 #               <th align="right" nowrap>| . $locale->text('Invoice Number') . qq|</th>
533 #               <td> |.
534 #               $cgi->textfield("-name" => "invnumber", "-size" => 11, "-value" => $form->{invnumber}) .
535 #      qq|      </td>
536 #             </tr>
537 #             <tr>
538 #               <th align="right">| . $locale->text('Invoice Date') . qq|</th>
539 #                $button1
540 #             </tr>
541 #             <tr>
542 #               <th align="right">| . $locale->text('Due Date') . qq|</th>
543 #                $button2
544 #             </tr>
545 #             <tr>
546 #               <th align="right" nowrap>| . $locale->text('Delivery Order Number') . qq|</th>
547 #               <td> |.
548 #               $cgi->textfield("-name" => "donumber", "-size" => 11, "-value" => $form->{donumber}) .
549 #      qq|      </td>
550 #             </tr>
551 #             <tr>
552 #               <th align="right">| . $locale->text('Delivery Date') . qq|</th>
553 #                $button3
554 #             </tr>|;
555 #}
556 #print qq|     <tr>
557 #               <th align="right" nowrap>| . $locale->text('Order Number') . qq|</th>
558 #               <td> |.
559 #               $cgi->textfield("-name" => "ordnumber", "-size" => 11, "-value" => $form->{ordnumber}) .
560 #      qq|      </td>
561 #             </tr>
562 #        <tr>
563 #          <th align="right" nowrap>| . $locale->text('Order Date') . qq|</th>
564 #          <td><input name="orddate" id="orddate" size="11" title="$myconfig{dateformat}" value="| . Q($form->{orddate}) . qq|" onBlur=\"check_right_date_format(this)\">
565 #           <input type="button" name="b_orddate" id="trigger_orddate" value="?"></td>
566 #        </tr>
567 #             <tr>
568 #               <th align="right" nowrap>| . $locale->text('Quotation Number') . qq|</th>
569 #               <td> |.
570 #               $cgi->textfield("-name" => "quonumber", "-size" => 11, "-value" => $form->{quonumber}) .
571 #      qq|      </td>
572 #             </tr>
573 #        <tr>
574 #          <th align="right" nowrap>| . $locale->text('Quotation Date') . qq|</th>
575 #          <td><input name="quodate" id="quodate" size="11" title="$myconfig{dateformat}" value="| . Q($form->{quodate}) . qq|" onBlur=\"check_right_date_format(this)\">
576 #           <input type="button" name="b_quodate" id="trigger_quodate" value="?"></td>
577 #        </tr>
578 #             <tr>
579 #               <th align="right" nowrap>| . $locale->text('Customer Order Number') . qq|</th>
580 #               <td> |.
581 #               $cgi->textfield("-name" => "cusordnumber", "-size" => 11, "-value" => $form->{cusordnumber}) .
582 #      qq|      </td>
583 #             </tr>
584 #             <tr>
585 #          <th align="right" nowrap>| . $locale->text('Project Number') . qq|</th>
586 #          <td>$globalprojectnumber</td>
587 #             </tr>
588 #           </table>
589 #          </td>
590 #       </tr>
591 #      </table>
592 #    </td>
593 #  </tr>
594 #  <tr>
595 #    <td>
596 #    </td>
597 #  </tr>
598 #  $jsscript
599 #|;
600 #  print qq|<input type="hidden" name="webdav" value="$webdav">|;
601
602   print $form->parse_html_template("is/form_header", \%TMPL_VAR);
603
604   $main::lxdebug->leave_sub();
605 }
606
607 sub form_footer {
608   $main::lxdebug->enter_sub();
609
610   my $form     = $main::form;
611   my %myconfig = %main::myconfig;
612   my $locale   = $main::locale;
613   my $cgi      = $main::cgi;
614
615   $main::auth->assert('invoice_edit');
616
617   $form->{invtotal} = $form->{invsubtotal};
618
619   my ($rows, $introws);
620   if (($rows = $form->numtextrows($form->{notes}, 26, 8)) < 2) {
621     $rows = 2;
622   }
623   if (($introws = $form->numtextrows($form->{intnotes}, 35, 8)) < 2) {
624     $introws = 2;
625   }
626   $rows = ($rows > $introws) ? $rows : $introws;
627   my $notes =
628     qq|<textarea name="notes" rows="$rows" cols="26" wrap="soft">$form->{notes}</textarea>|;
629   my $intnotes =
630     qq|<textarea name="intnotes" rows="$rows" cols="35" wrap="soft">$form->{intnotes}</textarea>|;
631
632   $form->{taxincluded} = ($form->{taxincluded} ? "checked" : "");
633
634   my $taxincluded = "";
635   if ($form->{taxaccounts}) {
636     $taxincluded = qq|
637                 <input name="taxincluded" class="checkbox" type="checkbox" $form->{taxincluded}> <b>|
638       . $locale->text('Tax Included') . qq|</b><br><br>|;
639   }
640
641   my ($tax, $subtotal);
642   if (!$form->{taxincluded}) {
643
644     foreach my $item (split / /, $form->{taxaccounts}) {
645       if ($form->{"${item}_base"}) {
646         $form->{"${item}_total"} =
647           $form->round_amount(
648                              $form->{"${item}_base"} * $form->{"${item}_rate"},
649                              2);
650         $form->{invtotal} += $form->{"${item}_total"};
651         $form->{"${item}_total"} =
652           $form->format_amount(\%myconfig, $form->{"${item}_total"}, 2);
653
654         $tax .= qq|
655               <tr>
656                 <th align="right">$form->{"${item}_description"}&nbsp;|
657                                     . $form->{"${item}_rate"} * 100 .qq|%</th>
658                 <td align="right">$form->{"${item}_total"}</td>
659               </tr>
660 |;
661       }
662     }
663
664     $form->{invsubtotal} =
665       $form->format_amount(\%myconfig, $form->{invsubtotal}, 2, 0);
666
667     $subtotal = qq|
668               <tr>
669                 <th align="right">| . $locale->text('Subtotal') . qq|</th>
670                 <td align="right">$form->{invsubtotal}</td>
671               </tr>
672 |;
673
674   }
675
676   if ($form->{taxincluded}) {
677     foreach my $item (split / /, $form->{taxaccounts}) {
678       if ($form->{"${item}_base"}) {
679         $form->{"${item}_total"} =
680           $form->round_amount(
681                            ($form->{"${item}_base"} * $form->{"${item}_rate"} /
682                               (1 + $form->{"${item}_rate"})
683                            ),
684                            2);
685         $form->{"${item}_netto"} =
686           $form->round_amount(
687                           ($form->{"${item}_base"} - $form->{"${item}_total"}),
688                           2);
689         $form->{"${item}_total"} =
690           $form->format_amount(\%myconfig, $form->{"${item}_total"}, 2);
691         $form->{"${item}_netto"} =
692           $form->format_amount(\%myconfig, $form->{"${item}_netto"}, 2);
693
694         $tax .= qq|
695               <tr>
696                 <th align="right">Enthaltene $form->{"${item}_description"}&nbsp;|
697                                     . $form->{"${item}_rate"} * 100 .qq|%</th>
698                 <td align="right">$form->{"${item}_total"}</td>
699               </tr>
700               <tr>
701                 <th align="right">Nettobetrag</th>
702                 <td align="right">$form->{"${item}_netto"}</td>
703               </tr>
704 |;
705       }
706     }
707
708   }
709
710   $form->{oldinvtotal} = $form->{invtotal};
711   $form->{invtotal}    =
712     $form->format_amount(\%myconfig, $form->{invtotal}, 2, 0);
713
714   my $follow_ups_block;
715   if ($form->{id}) {
716     my $follow_ups = FU->follow_ups('trans_id' => $form->{id});
717
718     if (@{ $follow_ups} ) {
719       my $num_due       = sum map { $_->{due} * 1 } @{ $follow_ups };
720       $follow_ups_block = qq|
721       <tr>
722         <td colspan="2">| . $locale->text("There are #1 unfinished follow-ups of which #2 are due.", scalar @{ $follow_ups }, $num_due) . qq|</td>
723       </tr>
724 |;
725     }
726   }
727
728   print qq|
729   <tr>
730     <td>
731       <table width="100%">
732         <tr valign="bottom">
733           <td>
734             <table>
735               <tr>
736                 <th align="left">| . $locale->text('Notes') . qq|</th>
737                 <th align="left">| . $locale->text('Internal Notes') . qq|</th>
738                 <th align="right">| . $locale->text('Payment Terms') . qq|</th>
739               </tr>
740               <tr valign="top">
741                 <td>$notes</td>
742                 <td>$intnotes</td>
743                 <td><select name="payment_id" onChange="if (this.value) set_duedate(['payment_id__' + this.value, 'invdate__' + invdate.value],['duedate'])">$payment
744                 </select></td>
745               </tr>
746         $follow_ups_block
747             </table>
748           </td>
749           <td>
750             <table>
751             <tr>
752               <th  align=left>| . $locale->text('Ertrag') . qq|</th>
753               <td>| .  $form->format_amount(\%myconfig, $form->{marge_total}, 2, 0) . qq|</td>
754             </tr>
755             <tr>
756               <th  align=left>| . $locale->text('Ertrag prozentual') . qq|</th>
757               <td>| .  $form->format_amount(\%myconfig, $form->{marge_percent}, 2, 0) . qq| %</td>
758             </tr>
759             <input type=hidden name="marge_total" value="$form->{"marge_total"}">
760             <input type=hidden name="marge_percent" value="$form->{"marge_percent"}">
761             </table>
762           </td>
763           <td align="right">
764             $taxincluded
765             <table>
766               $subtotal
767               $tax
768               <tr>
769                 <th align="right">| . $locale->text('Total') . qq|</th>
770                 <td align="right">$form->{invtotal}</td>
771               </tr>
772             </table>
773           </td>
774         </tr>
775       </table>
776     </td>
777   </tr>
778 |;
779   my $webdav_list;
780   if ($main::webdav) {
781     $webdav_list = qq|
782   <tr>
783     <td><hr size="3" noshade></td>
784   </tr>
785   <tr>
786     <th class="listtop" align="left">Dokumente im Webdav-Repository</th>
787   </tr>
788     <table width="100%">
789       <td align="left" width="30%"><b>Dateiname</b></td>
790       <td align="left" width="70%"><b>Webdavlink</b></td>
791 |;
792     foreach my $file (@{ $form->{WEBDAV} }) {
793       $webdav_list .= qq|
794       <tr>
795         <td align="left">$file->{name}</td>
796         <td align="left"><a href="$file->{link}">$file->{type}</a></td>
797       </tr>
798 |;
799     }
800     $webdav_list .= qq|
801     </table>
802   </tr>
803 |;
804
805     print $webdav_list;
806   }
807 if ($form->{type} eq "credit_note") {
808   print qq|
809   <tr>
810     <td>
811       <table width="100%">
812         <tr class="listheading">
813           <th colspan="6" class="listheading">|
814     . $locale->text('Payments') . qq|</th>
815         </tr>
816 |;
817 } else {
818   print qq|
819   <tr>
820     <td>
821       <table width="100%">
822         <tr class="listheading">
823           <th colspan="6" class="listheading">|
824     . $locale->text('Incoming Payments') . qq|</th>
825         </tr>
826 |;
827 }
828
829   my @column_index;
830   if ($form->{currency} eq $form->{defaultcurrency}) {
831     @column_index = qw(datepaid source memo paid AR_paid);
832   } else {
833     @column_index = qw(datepaid source memo paid exchangerate AR_paid);
834   }
835
836   my %column_data;
837   $column_data{datepaid}     = "<th>" . $locale->text('Date') . "</th>";
838   $column_data{paid}         = "<th>" . $locale->text('Amount') . "</th>";
839   $column_data{exchangerate} = "<th>" . $locale->text('Exch') . "</th>";
840   $column_data{AR_paid}      = "<th>" . $locale->text('Account') . "</th>";
841   $column_data{source}       = "<th>" . $locale->text('Source') . "</th>";
842   $column_data{memo}         = "<th>" . $locale->text('Memo') . "</th>";
843
844   print "
845         <tr>
846 ";
847   map { print "$column_data{$_}\n" } @column_index;
848   print "
849         </tr>
850 ";
851
852   my @triggers  = ();
853   my $totalpaid = 0;
854
855   $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
856   for my $i (1 .. $form->{paidaccounts}) {
857
858     print "
859         <tr>\n";
860
861     $form->{"selectAR_paid_$i"} = $form->{selectAR_paid};
862     $form->{"selectAR_paid_$i"} =~
863       s/option>\Q$form->{"AR_paid_$i"}\E/option selected>$form->{"AR_paid_$i"}/;
864
865     # format amounts
866     $totalpaid += $form->{"paid_$i"};
867     if ($form->{"paid_$i"}) {
868       $form->{"paid_$i"} =
869         $form->format_amount(\%myconfig, $form->{"paid_$i"}, 2);
870     }
871     $form->{"exchangerate_$i"} =
872       $form->format_amount(\%myconfig, $form->{"exchangerate_$i"});
873
874     if ($form->{"exchangerate_$i"} == 0) {
875       $form->{"exchangerate_$i"} = "";
876     }
877     my $exchangerate = qq|&nbsp;|;
878     if ($form->{currency} ne $form->{defaultcurrency}) {
879       if ($form->{"forex_$i"}) {
880         $exchangerate = qq|<input type="hidden" name="exchangerate_$i" value="$form->{"exchangerate_$i"}">$form->{"exchangerate_$i"}|;
881       } else {
882         $exchangerate = qq|<input name="exchangerate_$i" size="10" value="$form->{"exchangerate_$i"}">|;
883       }
884     }
885
886     $exchangerate .= qq|<input type="hidden" name="forex_$i" value="$form->{"forex_$i"}">|;
887
888     $column_data{"paid_$i"} =
889       qq|<td align="center"><input name="paid_$i" size="11" value="$form->{"paid_$i"}" onBlur=\"check_right_number_format(this)\"></td>|;
890     $column_data{"exchangerate_$i"} = qq|<td align="center">$exchangerate</td>|;
891     $column_data{"AR_paid_$i"}      =
892       qq|<td align="center"><select name="AR_paid_$i">$form->{"selectAR_paid_$i"}</select></td>|;
893     $column_data{"datepaid_$i"} =
894       qq|<td align="center"><input id="datepaid_$i" name="datepaid_$i"  size="11" title="$myconfig{dateformat}" value="$form->{"datepaid_$i"}" onBlur=\"check_right_date_format(this)\">
895          <input type="button" name="datepaid_$i" id="trigger_datepaid_$i" value="?"></td>|;
896     $column_data{"source_$i"} =
897       qq|<td align=center><input name="source_$i" size="11" value="$form->{"source_$i"}"></td>|;
898     $column_data{"memo_$i"} =
899       qq|<td align="center"><input name="memo_$i" size="11" value="$form->{"memo_$i"}"></td>|;
900
901     map { print qq|$column_data{"${_}_$i"}\n| } @column_index;
902     print "
903         </tr>\n";
904     push(@triggers, "datepaid_$i", "BL", "trigger_datepaid_$i");
905   }
906
907   my $paid_missing = $form->{oldinvtotal} - $totalpaid;
908
909   print qq|
910     <tr>
911       <td></td>
912       <td></td>
913       <td align="center">| . $locale->text('Total') . qq|</td>
914       <td align="center">| . H($form->format_amount(\%myconfig, $totalpaid, 2)) . qq|</td>
915     </tr>
916     <tr>
917       <td></td>
918       <td></td>
919       <td align="center">| . $locale->text('Missing amount') . qq|</td>
920       <td align="center">| . H($form->format_amount(\%myconfig, $paid_missing, 2)) . qq|</td>
921     </tr>
922 |;
923
924   map({ print($cgi->hidden("-name" => $_, "-value" => $form->{$_})); } qw(paidaccounts selectAR_paid oldinvtotal));
925   print qq|<input type="hidden" name="oldtotalpaid" value="$totalpaid">
926     </table>
927     </td>
928   </tr>
929   <tr>
930     <td><hr size="3" noshade></td>
931   </tr>
932   <tr>
933     <td>
934 |;
935
936   print_options();
937
938   print qq|
939     </td>
940   </tr>
941 </table>
942 |;
943
944   my $invdate  = $form->datetonum($form->{invdate},  \%myconfig);
945   my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
946
947   if ($form->{id}) {
948     my $show_storno = !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ar") && (($totalpaid == 0) || ($totalpaid eq ""));
949
950     print qq|
951     <input class="submit" type="submit" accesskey="u" name="action" id="update_button" value="|
952       . $locale->text('Update') . qq|">
953     <input class="submit" type="submit" name="action" value="|
954       . $locale->text('Ship to') . qq|">
955     <input class="submit" type="submit" name="action" value="|
956       . $locale->text('Print') . qq|">
957     <input class="submit" type="submit" name="action" value="|
958       . $locale->text('E-mail') . qq|"> |;
959     print qq|<input class="submit" type="submit" name="action" value="|
960       . $locale->text('Storno') . qq|"> | if ($show_storno);
961     print qq|<input class="submit" type="submit" name="action" value="|
962       . $locale->text('Post Payment') . qq|">
963 |;
964     print qq|<input class="submit" type="submit" name="action" value="|
965       . $locale->text('Use As Template') . qq|">
966 |;
967     if ($form->{id} && !($form->{type} eq "credit_note")) {
968       print qq|
969     <input class="submit" type="submit" name="action" value="|
970       . $locale->text('Credit Note') . qq|">
971 |;
972     }
973     if ($form->{radier}) {
974     print qq|
975     <input class="submit" type="submit" name="action" value="|
976       . $locale->text('Delete') . qq|">
977 |;
978     }
979
980
981     if ($invdate > $closedto) {
982       print qq|
983       <input class="submit" type="submit" name="action" value="|
984         . $locale->text('Order') . qq|">
985 |;
986     }
987
988     print qq|
989       <input type="button" class="submit" onclick="follow_up_window()" value="|
990       . $locale->text('Follow-Up')
991       . qq|">|;
992
993   } else {
994     if ($invdate > $closedto) {
995       print qq|<input class="submit" type="submit" name="action" id="update_button" value="|
996         . $locale->text('Update') . qq|">
997       <input class="submit" type="submit" name="action" value="|
998         . $locale->text('Ship to') . qq|">
999       <input class="submit" type="submit" name="action" value="|
1000         . $locale->text('Preview') . qq|">
1001       <input class="submit" type="submit" name="action" value="|
1002         . $locale->text('E-mail') . qq|">
1003       <input class="submit" type="submit" name="action" value="|
1004         . $locale->text('Print and Post') . qq|">
1005       <input class="submit" type="submit" name="action" value="|
1006         . $locale->text('Post') . qq|"> | .
1007         NTI($cgi->submit('-name' => 'action', '-value' => $locale->text('Save draft'),
1008                          '-class' => 'submit'));
1009     }
1010   }
1011
1012   # button for saving history
1013   if($form->{id} ne "") {
1014     print qq|
1015           <input type="button" class="submit" onclick="set_history_window(|
1016           . Q($form->{id})
1017           . qq|);" name="history" id="history" value="|
1018           . $locale->text('history')
1019           . qq|"> |;
1020   }
1021   # /button for saving history
1022
1023   # mark_as_paid button
1024   if($form->{id} ne "") {
1025     print qq|<input type="submit" class="submit" name="action" value="|
1026           . $locale->text('mark as paid') . qq|">|;
1027   }
1028   # /mark_as_paid button
1029   print $form->write_trigger(\%myconfig, scalar(@triggers) / 3, @triggers) .
1030     qq|
1031
1032 <input type="hidden" name="rowcount" value="$form->{rowcount}">
1033 | .
1034 $cgi->hidden("-name" => "callback", "-value" => $form->{callback})
1035 . $cgi->hidden('-name' => 'draft_id', '-default' => [$form->{draft_id}])
1036 . $cgi->hidden('-name' => 'draft_description', '-default' => [$form->{draft_description}])
1037 . $cgi->hidden('-name' => 'customer_discount', '-value' => [$form->{customer_discount}])
1038 . qq|
1039 </form>
1040
1041 </body>
1042
1043  </html>
1044 |;
1045
1046   $main::lxdebug->leave_sub();
1047 }
1048
1049 sub mark_as_paid {
1050   $main::lxdebug->enter_sub();
1051
1052   my $form     = $main::form;
1053   my %myconfig = %main::myconfig;
1054
1055   $main::auth->assert('invoice_edit');
1056
1057   &mark_as_paid_common(\%myconfig,"ar");
1058
1059   $main::lxdebug->leave_sub();
1060 }
1061
1062 sub update {
1063   $main::lxdebug->enter_sub();
1064
1065   my $form     = $main::form;
1066   my %myconfig = %main::myconfig;
1067
1068   $main::auth->assert('invoice_edit');
1069
1070   my ($recursive_call) = shift;
1071
1072   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) } qw(exchangerate creditlimit creditremaining) unless $recursive_call;
1073
1074   $form->{print_and_post} = 0         if $form->{second_run};
1075   my $taxincluded            = "checked" if $form->{taxincluded};
1076   $form->{update} = 1;
1077
1078   &check_name("customer");
1079
1080   $form->{taxincluded} ||= $taxincluded;
1081
1082   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1083   $form->{exchangerate} = $form->{forex} if $form->{forex};
1084
1085   for my $i (1 .. $form->{paidaccounts}) {
1086     next unless $form->{"paid_$i"};
1087     map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
1088     $form->{"forex_$i"}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
1089     $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
1090   }
1091
1092   my $i            = $form->{rowcount};
1093   my $exchangerate = $form->{exchangerate} || 1;
1094
1095   # if last row empty, check the form otherwise retrieve new item
1096   if (   ($form->{"partnumber_$i"} eq "")
1097       && ($form->{"description_$i"} eq "")
1098       && ($form->{"partsgroup_$i"}  eq "")) {
1099
1100     $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
1101     &check_form;
1102
1103   } else {
1104
1105     IS->retrieve_item(\%myconfig, \%$form);
1106
1107     my $rows = scalar @{ $form->{item_list} };
1108
1109     $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{customer_discount} * 100);
1110
1111     if ($rows) {
1112       $form->{"qty_$i"} = ($form->{"qty_$i"} * 1) ? $form->{"qty_$i"} : 1;
1113
1114       if ($rows > 1) {
1115
1116         &select_item;
1117         exit;
1118
1119       } else {
1120
1121         my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
1122
1123         map { $form->{item_list}[$i]{$_} =~ s/\"/&quot;/g } qw(partnumber description unit);
1124         map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
1125
1126         $form->{payment_id}    = $form->{"part_payment_id_$i"} if $form->{"part_payment_id_$i"} ne "";
1127         $form->{"discount_$i"} = 0                             if $form->{"not_discountable_$i"};
1128
1129         $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
1130
1131         ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
1132         my $decimalplaces = max 2, length $1;
1133
1134         if ($sellprice) {
1135           $form->{"sellprice_$i"} = $sellprice;
1136         } else {
1137           # if there is an exchange rate adjust sellprice
1138           $form->{"sellprice_$i"} *= (1 - $form->{tradediscount});
1139           $form->{"sellprice_$i"} /= $exchangerate;
1140         }
1141
1142         $form->{"listprice_$i"} /= $exchangerate;
1143
1144         my $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"} / 100);
1145         map { $form->{"${_}_base"} = 0 }                                 split / /, $form->{taxaccounts};
1146         map { $form->{"${_}_base"} += $amount }                          split / /, $form->{"taxaccounts_$i"};
1147         map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{"taxaccounts_$i"} if !$form->{taxincluded};
1148
1149         $form->{creditremaining} -= $amount;
1150
1151         map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces) } qw(sellprice listprice);
1152
1153         $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"});
1154
1155         if ($main::lizenzen) {
1156           if ($form->{"inventory_accno_$i"} ne "") {
1157             $form->{"lizenzen_$i"} = qq|<option></option>|;
1158             foreach my $item (@{ $form->{LIZENZEN}{ $form->{"id_$i"} } }) {
1159               $form->{"lizenzen_$i"} .= qq|<option value="$item->{"id"}">$item->{"licensenumber"}</option>|;
1160             }
1161             $form->{"lizenzen_$i"} .= qq|<option value=-1>Neue Lizenz</option>|;
1162           }
1163         }
1164
1165         # get pricegroups for parts
1166         IS->get_pricegroups_for_parts(\%myconfig, \%$form);
1167
1168         # build up html code for prices_$i
1169         &set_pricegroup($i);
1170       }
1171
1172       &display_form;
1173
1174     } else {
1175
1176       # ok, so this is a new part
1177       # ask if it is a part or service item
1178
1179       if (   $form->{"partsgroup_$i"}
1180           && ($form->{"partsnumber_$i"} eq "")
1181           && ($form->{"description_$i"} eq "")) {
1182         $form->{rowcount}--;
1183         $form->{"discount_$i"} = "";
1184         display_form();
1185
1186       } else {
1187         $form->{"id_$i"}   = 0;
1188         new_item();
1189       }
1190     }
1191   }
1192   $main::lxdebug->leave_sub();
1193 }
1194
1195 sub post_payment {
1196   $main::lxdebug->enter_sub();
1197
1198   my $form     = $main::form;
1199   my %myconfig = %main::myconfig;
1200   my $locale   = $main::locale;
1201
1202   $main::auth->assert('invoice_edit');
1203
1204   our $invdate;
1205
1206   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
1207   for my $i (1 .. $form->{paidaccounts}) {
1208     if ($form->{"paid_$i"}) {
1209       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
1210
1211       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
1212
1213       $form->error($locale->text('Cannot post payment for a closed period!'))
1214         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
1215
1216       if ($form->{currency} ne $form->{defaultcurrency}) {
1217         $form->{"exchangerate_$i"} = $form->{exchangerate}
1218           if ($invdate == $datepaid);
1219         $form->isblank("exchangerate_$i",
1220                        $locale->text('Exchangerate for payment missing!'));
1221       }
1222     }
1223   }
1224
1225   ($form->{AR})      = split /--/, $form->{AR};
1226   ($form->{AR_paid}) = split /--/, $form->{AR_paid};
1227   relink_accounts();
1228   $form->redirect($locale->text('Payment posted!'))
1229       if (IS->post_payment(\%myconfig, \%$form));
1230     $form->error($locale->text('Cannot post payment!'));
1231
1232
1233   $main::lxdebug->leave_sub();
1234 }
1235
1236 sub post {
1237   $main::lxdebug->enter_sub();
1238
1239   my $form     = $main::form;
1240   my %myconfig = %main::myconfig;
1241   my $locale   = $main::locale;
1242
1243   $main::auth->assert('invoice_edit');
1244
1245   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
1246   $form->isblank("invdate",  $locale->text('Invoice Date missing!'));
1247   $form->isblank("customer", $locale->text('Customer missing!'));
1248   $form->error($locale->text('Cannot post invoice for a closed period!'))
1249         if ($form->date_closed($form->{"invdate"}, \%myconfig));
1250
1251   $form->{invnumber} =~ s/^\s*//g;
1252   $form->{invnumber} =~ s/\s*$//g;
1253
1254   # if oldcustomer ne customer redo form
1255   if (&check_name('customer')) {
1256     &update;
1257     exit;
1258   }
1259   if ($form->{second_run}) {
1260     $form->{print_and_post} = 0;
1261   }
1262
1263   &validate_items;
1264
1265   my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
1266   my $invdate  = $form->datetonum($form->{invdate},  \%myconfig);
1267
1268   $form->error($locale->text('Cannot post invoice for a closed period!'))
1269     if ($invdate <= $closedto);
1270
1271   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
1272     if ($form->{currency} ne $form->{defaultcurrency});
1273
1274   for my $i (1 .. $form->{paidaccounts}) {
1275     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
1276       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
1277
1278       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
1279
1280       $form->error($locale->text('Cannot post payment for a closed period!'))
1281         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
1282
1283       if ($form->{currency} ne $form->{defaultcurrency}) {
1284         $form->{"exchangerate_$i"} = $form->{exchangerate}
1285           if ($invdate == $datepaid);
1286         $form->isblank("exchangerate_$i",
1287                        $locale->text('Exchangerate for payment missing!'));
1288       }
1289     }
1290   }
1291
1292   ($form->{AR})        = split /--/, $form->{AR};
1293   ($form->{AR_paid})   = split /--/, $form->{AR_paid};
1294   $form->{storno}    ||= 0;
1295
1296   $form->{label} = $locale->text('Invoice');
1297
1298   $form->{id} = 0 if $form->{postasnew};
1299
1300   # get new invnumber in sequence if no invnumber is given or if posasnew was requested
1301   if ($form->{postasnew}) {
1302     if ($form->{type} eq "credit_note") {
1303       undef($form->{cnnumber});
1304     } else {
1305       undef($form->{invnumber});
1306     }
1307   }
1308
1309   relink_accounts();
1310   $form->error($locale->text('Cannot post invoice!'))
1311     unless IS->post_invoice(\%myconfig, \%$form);
1312   remove_draft() if $form->{remove_draft};
1313
1314   if(!exists $form->{addition}) {
1315     $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1316     $form->{addition} = $print_post     ? "PRINTED AND POSTED" :
1317                         $form->{storno} ? "STORNO"             :
1318                                           "POSTED";
1319     $form->save_history($form->dbconnect(\%myconfig));
1320   }
1321
1322   $form->redirect( $form->{label} . " $form->{invnumber} " . $locale->text('posted!'))
1323     unless $print_post;
1324
1325   $main::lxdebug->leave_sub();
1326 }
1327
1328 sub print_and_post {
1329   $main::lxdebug->enter_sub();
1330
1331   my $form     = $main::form;
1332
1333   $main::auth->assert('invoice_edit');
1334
1335   my $old_form               = new Form;
1336   $print_post             = 1;
1337   $form->{print_and_post} = 1;
1338   &post();
1339
1340   &edit();
1341   $main::lxdebug->leave_sub();
1342
1343 }
1344
1345 sub use_as_template {
1346   $main::lxdebug->enter_sub();
1347
1348   my $form     = $main::form;
1349   my %myconfig = %main::myconfig;
1350
1351   $main::auth->assert('invoice_edit');
1352
1353   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);
1354   $form->{paidaccounts} = 1;
1355   $form->{rowcount}--;
1356   $form->{invdate} = $form->current_date(\%myconfig);
1357   &display_form;
1358
1359   $main::lxdebug->leave_sub();
1360 }
1361
1362 sub storno {
1363   $main::lxdebug->enter_sub();
1364
1365   my $form     = $main::form;
1366   my %myconfig = %main::myconfig;
1367   my $locale   = $main::locale;
1368
1369   $main::auth->assert('invoice_edit');
1370
1371   if ($form->{storno}) {
1372     $form->error($locale->text('Cannot storno storno invoice!'));
1373   }
1374
1375   if (IS->has_storno(\%myconfig, $form, "ar")) {
1376     $form->error($locale->text("Invoice has already been storno'd!"));
1377   }
1378
1379   map({ my $key = $_; delete($form->{$key}) unless (grep({ $key eq $_ } qw(id login password stylesheet type))); } keys(%{ $form }));
1380
1381   invoice_links();
1382   prepare_invoice();
1383   relink_accounts();
1384
1385   # Payments must not be recorded for the new storno invoice.
1386   $form->{paidaccounts} = 0;
1387   map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
1388
1389   $form->{storno_id} = $form->{id};
1390   $form->{storno} = 1;
1391   $form->{id} = "";
1392   $form->{invnumber} = "Storno zu " . $form->{invnumber};
1393   $form->{rowcount}++;
1394
1395   post();
1396   $main::lxdebug->leave_sub();
1397 }
1398
1399 sub preview {
1400   $main::lxdebug->enter_sub();
1401
1402   my $form     = $main::form;
1403
1404   $main::auth->assert('invoice_edit');
1405
1406   $form->{preview} = 1;
1407   my $old_form = new Form;
1408   for (keys %$form) { $old_form->{$_} = $form->{$_} }
1409
1410   &print_form($old_form);
1411   $main::lxdebug->leave_sub();
1412
1413 }
1414
1415 sub delete {
1416   $main::lxdebug->enter_sub();
1417
1418   my $form     = $main::form;
1419   my $locale   = $main::locale;
1420
1421   $main::auth->assert('invoice_edit');
1422
1423   if ($form->{second_run}) {
1424     $form->{print_and_post} = 0;
1425   }
1426   $form->header;
1427
1428   print qq|
1429 <body>
1430
1431 <form method="post" action="$form->{script}">
1432 |;
1433
1434   # delete action variable
1435   map { delete $form->{$_} } qw(action header);
1436
1437   foreach my $key (keys %$form) {
1438     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
1439     $form->{$key} =~ s/\"/&quot;/g;
1440     print qq|<input type="hidden" name="$key" value="$form->{$key}">\n|;
1441   }
1442
1443   print qq|
1444 <h2 class="confirm">| . $locale->text('Confirm!') . qq|</h2>
1445
1446 <h4>|
1447     . $locale->text('Are you sure you want to delete Invoice Number')
1448     . qq| $form->{invnumber}
1449 </h4>
1450
1451 <p>
1452 <input name="action" class="submit" type="submit" value="|
1453     . $locale->text('Yes') . qq|">
1454 </form>
1455 |;
1456
1457   $main::lxdebug->leave_sub();
1458 }
1459
1460 sub credit_note {
1461   $main::lxdebug->enter_sub();
1462
1463   my $form     = $main::form;
1464   my %myconfig = %main::myconfig;
1465   my $locale   = $main::locale;
1466
1467   $main::auth->assert('invoice_edit');
1468
1469   $form->{transdate} = $form->{invdate} = $form->current_date(\%myconfig);
1470   $form->{duedate} =
1471     $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
1472
1473   $form->{id}     = '';
1474   $form->{rowcount}--;
1475   $form->{shipto} = 1;
1476
1477
1478   $form->{title}  = $locale->text('Add Credit Note');
1479   $form->{script} = 'is.pl';
1480   our $script         = "is";
1481   our $buysell        = 'buy';
1482
1483
1484   # bo creates the id, reset it
1485   map { delete $form->{$_} }
1486     qw(id invnumber subject message cc bcc printed emailed queued);
1487   $form->{ $form->{vc} } =~ s/--.*//g;
1488   $form->{type} = "credit_note";
1489
1490
1491   map { $form->{"select$_"} = "" } ($form->{vc}, 'currency');
1492
1493   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
1494     qw(creditlimit creditremaining);
1495
1496   my $currency = $form->{currency};
1497   &invoice_links;
1498
1499   $form->{currency}     = $currency;
1500   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, $buysell);
1501   $form->{exchangerate} = $form->{forex} || '';
1502
1503   $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
1504
1505   &prepare_invoice;
1506
1507
1508   &display_form;
1509
1510   $main::lxdebug->leave_sub();
1511 }
1512
1513 sub yes {
1514   $main::lxdebug->enter_sub();
1515
1516   my $form     = $main::form;
1517   my %myconfig = %main::myconfig;
1518   my $locale   = $main::locale;
1519
1520   $main::auth->assert('invoice_edit');
1521
1522   if (IS->delete_invoice(\%myconfig, \%$form, $main::spool)) {
1523     # saving the history
1524         if(!exists $form->{addition}) {
1525     $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1526           $form->{addition} = "DELETED";
1527           $form->save_history($form->dbconnect(\%myconfig));
1528     }
1529     # /saving the history
1530     $form->redirect($locale->text('Invoice deleted!'));
1531   }
1532   $form->error($locale->text('Cannot delete invoice!'));
1533
1534   $main::lxdebug->leave_sub();
1535 }
1536
1537 sub e_mail {
1538   $main::lxdebug->enter_sub();
1539
1540   my $form     = $main::form;
1541
1542   $main::auth->assert('invoice_edit');
1543
1544   if (!$form->{id}) {
1545     $print_post = 1;
1546
1547     my $saved_form = save_form();
1548
1549     post();
1550
1551     restore_form($saved_form, 0, qw(id invnumber));
1552   }
1553
1554   edit_e_mail();
1555
1556   $main::lxdebug->leave_sub();
1557 }