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