2f2f0437464487380c7acf04c1166c09f2fa9f81
[kivitendo-erp.git] / bin / mozilla / ir.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 received module
31 #
32 #======================================================================
33
34 use SL::FU;
35 use SL::IR;
36 use SL::IS;
37 use SL::PE;
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/common.pl";
44 require "bin/mozilla/drafts.pl";
45
46 use strict;
47
48 1;
49
50 # end of main
51
52 sub add {
53   $main::lxdebug->enter_sub();
54
55   my $form     = $main::form;
56   my $locale   = $main::locale;
57
58   $main::auth->assert('vendor_invoice_edit');
59
60   return $main::lxdebug->leave_sub() if (load_draft_maybe());
61
62   $form->{title} = $locale->text('Add Vendor Invoice');
63
64   &invoice_links;
65   &prepare_invoice;
66   &display_form;
67
68   $main::lxdebug->leave_sub();
69 }
70
71 sub edit {
72   $main::lxdebug->enter_sub();
73
74   my $form     = $main::form;
75   my $locale   = $main::locale;
76
77   $main::auth->assert('vendor_invoice_edit');
78
79   # show history button
80   $form->{javascript} = qq|<script type=text/javascript src=js/show_history.js></script>|;
81   #/show hhistory button
82
83   $form->{title} = $locale->text('Edit Vendor Invoice');
84
85   &invoice_links;
86   &prepare_invoice;
87   &display_form;
88
89   $main::lxdebug->leave_sub();
90 }
91
92 sub invoice_links {
93   $main::lxdebug->enter_sub();
94
95   my $form     = $main::form;
96   my %myconfig = %main::myconfig;
97
98   $main::auth->assert('vendor_invoice_edit');
99
100   $form->{vc} = 'vendor';
101
102   # create links
103   $form->{webdav}   = $main::webdav;
104   $form->{jsscript} = 1;
105
106   $form->create_links("AP", \%myconfig, "vendor");
107
108   #quote all_vendor Bug 133
109   foreach my $ref (@{ $form->{all_vendor} }) {
110     $ref->{name} = $form->quote($ref->{name});
111   }
112
113   if ($form->{all_vendor}) {
114     unless ($form->{vendor_id}) {
115       $form->{vendor_id} = $form->{all_vendor}->[0]->{id};
116     }
117   }
118
119   my ($payment_id, $language_id, $taxzone_id);
120   if ($form->{payment_id}) {
121     $payment_id = $form->{payment_id};
122   }
123   if ($form->{language_id}) {
124     $language_id = $form->{language_id};
125   }
126   if ($form->{taxzone_id}) {
127     $taxzone_id = $form->{taxzone_id};
128   }
129
130   my $cp_id = $form->{cp_id};
131   IR->get_vendor(\%myconfig, \%$form);
132   IR->retrieve_invoice(\%myconfig, \%$form);
133   $form->{cp_id} = $cp_id;
134
135   if ($payment_id) {
136     $form->{payment_id} = $payment_id;
137   }
138   if ($language_id) {
139     $form->{language_id} = $language_id;
140   }
141   if ($taxzone_id) {
142     $form->{taxzone_id} = $taxzone_id;
143   }
144
145   my @curr = split(/:/, $form->{currencies}); #seems to be missing
146   map { $form->{selectcurrency} .= "<option>$_\n" } @curr;
147
148   $form->{oldvendor} = "$form->{vendor}--$form->{vendor_id}";
149
150   # build vendor/customer drop down comatibility... don't ask
151   if (@{ $form->{"all_vendor"} || [] }) {
152     $form->{"selectvendor"} = 1;
153     $form->{vendor}         = qq|$form->{vendor}--$form->{vendor_id}|;
154   }
155
156   # departments
157   if ($form->{all_departments}) {
158     $form->{selectdepartment} = "<option>\n";
159     $form->{department}       = "$form->{department}--$form->{department_id}";
160
161     map {
162       $form->{selectdepartment} .=
163         "<option>$_->{description}--$_->{id}\n"
164     } (@{ $form->{all_departments} || [] });
165   }
166
167   # forex
168   $form->{forex} = $form->{exchangerate};
169   my $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
170
171   foreach my $key (keys %{ $form->{AP_links} }) {
172
173     foreach my $ref (@{ $form->{AP_links}{$key} }) {
174       $form->{"select$key"} .= "<option>$ref->{accno}--$ref->{description}\n";
175     }
176
177     next unless $form->{acc_trans}{$key};
178
179     if ($key eq "AP_paid") {
180       for my $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
181         $form->{"AP_paid_$i"} =
182           "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
183
184         # reverse paid
185         $form->{"paid_$i"}     = $form->{acc_trans}{$key}->[$i - 1]->{amount};
186         $form->{"datepaid_$i"} =
187           $form->{acc_trans}{$key}->[$i - 1]->{transdate};
188         $form->{"forex_$i"} = $form->{"exchangerate_$i"} =
189           $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
190         $form->{"source_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{source};
191         $form->{"memo_$i"}   = $form->{acc_trans}{$key}->[$i - 1]->{memo};
192
193         $form->{paidaccounts} = $i;
194       }
195     } else {
196       $form->{$key} =
197         "$form->{acc_trans}{$key}->[0]->{accno}--$form->{acc_trans}{$key}->[0]->{description}";
198     }
199
200   }
201
202   $form->{paidaccounts} = 1 unless (exists $form->{paidaccounts});
203
204   $form->{AP} = $form->{AP_1} unless $form->{id};
205
206   $form->{locked} =
207     ($form->datetonum($form->{invdate}, \%myconfig) <=
208      $form->datetonum($form->{closedto}, \%myconfig));
209
210   $main::lxdebug->leave_sub();
211 }
212
213 sub prepare_invoice {
214   $main::lxdebug->enter_sub();
215
216   my $form     = $main::form;
217   my %myconfig = %main::myconfig;
218
219   $main::auth->assert('vendor_invoice_edit');
220
221   if ($form->{id}) {
222
223     map { $form->{$_} =~ s/\"/&quot;/g } qw(invnumber ordnumber quonumber);
224
225     my $i = 0;
226     foreach my $ref (@{ $form->{invoice_details} }) {
227       $i++;
228       map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
229
230       my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
231       $dec           = length $dec;
232       my $decimalplaces = ($dec > 2) ? $dec : 2;
233
234       $form->{"sellprice_$i"} =
235         $form->format_amount(\%myconfig, $form->{"sellprice_$i"},
236                              $decimalplaces);
237
238       (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
239       $dec_qty = length $dec_qty;
240
241       $form->{"qty_$i"} =
242         $form->format_amount(\%myconfig, ($form->{"qty_$i"} * -1), $dec_qty);
243
244       $form->{rowcount} = $i;
245     }
246   }
247
248   $main::lxdebug->leave_sub();
249 }
250
251 sub form_header {
252   $main::lxdebug->enter_sub();
253
254   my $form     = $main::form;
255   my %myconfig = %main::myconfig;
256   my $locale   = $main::locale;
257   my $cgi      = $main::cgi;
258
259   $main::auth->assert('invoice_edit');
260
261   our %TMPL_VAR = ();
262   my @custom_hiddens;
263
264   $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
265   $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
266
267   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
268   $form->{radier}          = ($form->current_date(\%myconfig) eq $form->{gldate}) ? 1 : 0;
269
270   my $set_duedate_url = "$form->{script}?action=set_duedate";
271
272   push @ { $form->{AJAX} }, new CGI::Ajax( 'set_duedate' => $set_duedate_url );
273
274   my @old_project_ids = ($form->{"globalproject_id"});
275   map { push @old_project_ids, $form->{"project_id_$_"} if $form->{"project_id_$_"}; } 1..$form->{"rowcount"};
276
277   $form->get_lists("contacts"      => "ALL_CONTACTS",
278                    "shipto"        => "ALL_SHIPTO",
279                    "projects"      => { "key"    => "ALL_PROJECTS",
280                                         "all"    => 0,
281                                         "old_id" => \@old_project_ids },
282                    "employees"     => "ALL_EMPLOYEES",
283                    "taxzones"      => "ALL_TAXZONES",
284                    "currencies"    => "ALL_CURRENCIES",
285                    "vendors"       => "ALL_VENDORS",
286                    "departments"   => "all_departments",
287                    "price_factors" => "ALL_PRICE_FACTORS");
288
289   $TMPL_VAR{sales_employee_labels} = sub { $_[0]->{name} || $_[0]->{login} };
290 #  $TMPL_VAR{shipto_labels}         = sub { join "; ", grep { $_ } map { $_[0]->{"shipto${_}" } } qw(name department_1 street city) };
291   $TMPL_VAR{contact_labels}        = sub { join(', ', $_[0]->{"cp_name"}, $_[0]->{"cp_givenname"}) . ($_[0]->{cp_abteilung} ? " ($_[0]->{cp_abteilung})" : "") };
292   $TMPL_VAR{department_labels}     = sub { "$_[0]->{description}--$_[0]->{id}" };
293
294   # customer
295   $TMPL_VAR{vc_keys} = sub { "$_[0]->{name}--$_[0]->{id}" };
296   $TMPL_VAR{vclimit} = $myconfig{vclimit};
297   $TMPL_VAR{vc_select} = "customer_or_vendor_selection_window('vendor', '', 1, 0)";
298   push @custom_hiddens, "vendor_id";
299   push @custom_hiddens, "oldvendor";
300   push @custom_hiddens, "selectvendor";
301
302   # currencies and exchangerate
303   my @values = map { $_       } @{ $form->{ALL_CURRENCIES} };
304   my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
305   $form->{currency}            = $form->{defaultcurrency} unless $form->{currency};
306   $TMPL_VAR{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
307   $TMPL_VAR{currencies}        = NTI($cgi->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
308                                                       '-values' => \@values, '-labels' => \%labels)) if scalar @values;
309   push @custom_hiddens, "forex";
310   push @custom_hiddens, "exchangerate" if $form->{forex};
311
312   $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
313   $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
314
315   $form->{fokus} = "invoice.vendor";
316
317   my $follow_up_vc         =  $form->{vendor};
318   $follow_up_vc            =~ s/--\d*\s*$//;
319   $TMPL_VAR{vendor_name} = $follow_up_vc;
320
321 # set option selected
322   foreach my $item (qw(AP)) {
323     $form->{"select$item"} =~ s/ selected//;
324     $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
325   }
326
327   $TMPL_VAR{is_type_credit_note} = $form->{type}   eq "credit_note";
328   $TMPL_VAR{is_format_html}      = $form->{format} eq 'html';
329   $TMPL_VAR{dateformat}          = $myconfig{dateformat};
330   $TMPL_VAR{numberformat}        = $myconfig{numberformat};
331
332   # hiddens
333   $TMPL_VAR{HIDDENS} = [qw(
334     id action type media format queued printed emailed title vc discount
335     title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
336     max_dunning_level dunning_amount
337     shiptoname shiptostreet shiptozipcode shiptocity shiptocountry  shiptocontact shiptophone shiptofax
338     shiptoemail shiptodepartment_1 shiptodepartment_2 message email subject cc bcc taxaccounts cursor_fokus
339     convert_from_do_ids convert_from_oe_ids
340   ), @custom_hiddens,
341   map { $_.'_rate', $_.'_description', $_.'_taxnumber' } split / /, $form->{taxaccounts}];
342
343   $form->{jsscript} = 1;
344   $form->header();
345
346   print $form->parse_html_template("ir/form_header", \%TMPL_VAR);
347
348   $main::lxdebug->leave_sub();
349 }
350
351 sub form_footer {
352   $main::lxdebug->enter_sub();
353
354   my $form     = $main::form;
355   my %myconfig = %main::myconfig;
356   my $locale   = $main::locale;
357   my $cgi      = $main::cgi;
358
359   $main::auth->assert('vendor_invoice_edit');
360
361   $form->{invtotal} = $form->{invsubtotal};
362
363   my ($rows, $introws);
364   if (($rows = $form->numtextrows($form->{notes}, 25, 8)) < 2) {
365     $rows = 2;
366   }
367   if (($introws = $form->numtextrows($form->{intnotes}, 35, 8)) < 2) {
368     $introws = 2;
369   }
370   $rows = ($rows > $introws) ? $rows : $introws;
371   my $notes =
372     qq|<textarea name=notes rows=$rows cols=25 wrap=soft>$form->{notes}</textarea>|;
373   my $intnotes =
374     qq|<textarea name=intnotes rows=$rows cols=35 wrap=soft>$form->{intnotes}</textarea>|;
375
376   $form->{taxincluded} = ($form->{taxincluded}) ? "checked" : "";
377
378   my $taxincluded = "";
379   if ($form->{taxaccounts}) {
380     $taxincluded = qq|
381                 <input name=taxincluded class=checkbox type=checkbox value=1 $form->{taxincluded}> <b>|
382       . $locale->text('Tax Included') . qq|</b>
383 |;
384   }
385
386   my ($tax, $subtotal);
387   if (!$form->{taxincluded}) {
388
389     foreach my $item (split / /, $form->{taxaccounts}) {
390       if ($form->{"${item}_base"}) {
391         $form->{invtotal} += $form->{"${item}_total"} =
392           $form->round_amount(
393                              $form->{"${item}_base"} * $form->{"${item}_rate"},
394                              2);
395         $form->{"${item}_total"} =
396           $form->format_amount(\%myconfig, $form->{"${item}_total"}, 2);
397
398         $tax .= qq|
399                 <tr>
400                   <th align=right>$form->{"${item}_description"}&nbsp;|
401                     . $form->{"${item}_rate"} * 100 .qq|%</th>
402                   <td align=right>$form->{"${item}_total"}</td>
403                 </tr>
404 |;
405       }
406     }
407
408     $form->{invsubtotal} =
409       $form->format_amount(\%myconfig, $form->{invsubtotal}, 2, 0);
410
411     $subtotal = qq|
412               <tr>
413                 <th align=right>| . $locale->text('Subtotal') . qq|</th>
414                 <td align=right>$form->{invsubtotal}</td>
415               </tr>
416 |;
417
418   }
419
420   if ($form->{taxincluded}) {
421     foreach my $item (split / /, $form->{taxaccounts}) {
422       if ($form->{"${item}_base"}) {
423         $form->{"${item}_total"} =
424           $form->round_amount(
425                            ($form->{"${item}_base"} * $form->{"${item}_rate"} /
426                               (1 + $form->{"${item}_rate"})
427                            ),
428                            2);
429         $form->{"${item}_base"} =
430           $form->round_amount($form->{"${item}_base"}, 2);
431         $form->{"${item}_netto"} =
432           $form->round_amount(
433                           ($form->{"${item}_base"} - $form->{"${item}_total"}),
434                           2);
435         $form->{"${item}_netto"} =
436           $form->format_amount(\%myconfig, $form->{"${item}_netto"}, 2);
437         $form->{"${item}_total"} =
438           $form->format_amount(\%myconfig, $form->{"${item}_total"}, 2);
439
440         $tax .= qq|
441               <tr>
442                 <th align=right>Enthaltene $form->{"${item}_description"}&nbsp;|
443                                     . $form->{"${item}_rate"} * 100 .qq|%</th>
444                 <td align=right>$form->{"${item}_total"}</td>
445               </tr>
446               <tr>
447                 <th align=right>Nettobetrag</th>
448                 <td align=right>$form->{"${item}_netto"}</td>
449               </tr>
450 |;
451       }
452     }
453
454   }
455
456   $form->{oldinvtotal} = $form->{invtotal};
457   $form->{invtotal}    =
458     $form->format_amount(\%myconfig, $form->{invtotal}, 2, 0);
459
460   my $follow_ups_block;
461   if ($form->{id}) {
462     my $follow_ups = FU->follow_ups('trans_id' => $form->{id});
463
464     if (@{ $follow_ups} ) {
465       my $num_due       = sum map { $_->{due} * 1 } @{ $follow_ups };
466       $follow_ups_block = qq|
467       <tr>
468         <td colspan="2">| . $locale->text("There are #1 unfinished follow-ups of which #2 are due.", scalar @{ $follow_ups }, $num_due) . qq|</td>
469       </tr>
470 |;
471     }
472   }
473
474   our $colspan;
475   print qq|
476   <tr>
477     <td colspan=$colspan>
478       <table cellspacing="0">
479         <tr valign=bottom>
480           <td>
481             <table>
482               <tr>
483                 <th align=left>| . $locale->text('Notes') . qq|</th>
484                 <th align=left>| . $locale->text('Internal Notes') . qq|</th>
485               </tr>
486               <tr valign=top>
487                 <td>$notes</td>
488                 <td>$intnotes</td>
489               </tr>
490         $follow_ups_block
491             </table>
492           </td>
493           <td colspan=2 align=right width=100%>
494             $taxincluded
495             <br>
496             <table width=100%>
497               $subtotal
498               $tax
499               <tr>
500                 <th align=right>| . $locale->text('Total') . qq|</th>
501                 <td align=right>$form->{invtotal}</td>
502               </tr>
503             </table>
504           </td>
505         </tr>
506       </table>
507     </td>
508   </tr>
509 |;
510   my $webdav_list;
511   if ($main::webdav) {
512     $webdav_list = qq|
513   <tr>
514     <td><hr size=3 noshade></td>
515   </tr>
516   <tr>
517     <th class=listtop align=left>Dokumente im Webdav-Repository</th>
518   </tr>
519     <table width=100%>
520       <td align=left width=30%><b>Dateiname</b></td>
521       <td align=left width=70%><b>Webdavlink</b></td>
522 |;
523     foreach my $file (@{ $form->{WEBDAV} }) {
524       $webdav_list .= qq|
525       <tr>
526         <td align="left">$file->{name}</td>
527         <td align="left"><a href="$file->{link}">$file->{type}</a></td>
528       </tr>
529 |;
530     }
531     $webdav_list .= qq|
532     </table>
533   </tr>
534 |;
535
536     print $webdav_list;
537   }
538   print qq|
539   <tr>
540     <td colspan=$colspan>
541       <table width=100%>
542         <tr>
543           <th colspan=6 class=listheading>| . $locale->text('Payments') . qq|</th>
544         </tr>
545 |;
546
547   my @column_index;
548   if ($form->{currency} eq $form->{defaultcurrency}) {
549     @column_index = qw(datepaid source memo paid AP_paid);
550   } else {
551     @column_index = qw(datepaid source memo paid exchangerate AP_paid);
552   }
553
554   my %column_data;
555   $column_data{datepaid}     = "<th>" . $locale->text('Date') . "</th>";
556   $column_data{paid}         = "<th>" . $locale->text('Amount') . "</th>";
557   $column_data{exchangerate} = "<th>" . $locale->text('Exch') . "</th>";
558   $column_data{AP_paid}      = "<th>" . $locale->text('Account') . "</th>";
559   $column_data{source}       = "<th>" . $locale->text('Source') . "</th>";
560   $column_data{memo}         = "<th>" . $locale->text('Memo') . "</th>";
561
562   print qq|
563         <tr>
564 |;
565   map { print "$column_data{$_}\n" } @column_index;
566   print qq|
567         </tr>
568 |;
569
570   my @triggers  = ();
571   my $totalpaid = 0;
572
573   $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
574   for my $i (1 .. $form->{paidaccounts}) {
575
576     print qq|
577         <tr>
578 |;
579
580     $form->{"selectAP_paid_$i"} = $form->{selectAP_paid};
581     $form->{"selectAP_paid_$i"} =~
582       s/option>\Q$form->{"AP_paid_$i"}\E/option selected>$form->{"AP_paid_$i"}/;
583
584     $totalpaid += $form->{"paid_$i"};
585
586     # format amounts
587     if ($form->{"paid_$i"}) {
588       $form->{"paid_$i"} =
589         $form->format_amount(\%myconfig, $form->{"paid_$i"}, 2);
590     }
591     $form->{"exchangerate_$i"} =
592       $form->format_amount(\%myconfig, $form->{"exchangerate_$i"});
593
594     my $exchangerate = qq|&nbsp;|;
595     if ($form->{currency} ne $form->{defaultcurrency}) {
596       if ($form->{"forex_$i"}) {
597         $exchangerate =
598           qq|<input type=hidden name="exchangerate_$i" value=$form->{"exchangerate_$i"}>$form->{"exchangerate_$i"}|;
599       } else {
600         $exchangerate =
601           qq|<input name="exchangerate_$i" size=10 value=$form->{"exchangerate_$i"}>|;
602       }
603     }
604     $exchangerate .= qq|
605 <input type=hidden name="forex_$i" value=$form->{"forex_$i"}>
606 |;
607
608     $column_data{"paid_$i"} =
609       qq|<td align=center><input name="paid_$i" size=11 value="$form->{"paid_$i"}" onBlur=\"check_right_number_format(this)\"></td>|;
610     $column_data{"exchangerate_$i"} = qq|<td align=center>$exchangerate</td>|;
611     $column_data{"AP_paid_$i"}      =
612       qq|<td align=center><select name="AP_paid_$i">$form->{"selectAP_paid_$i"}</select></td>|;
613     $column_data{"datepaid_$i"} =
614       qq|<td align=center><input name="datepaid_$i" id="datepaid_$i" size=11 title="$myconfig{dateformat}" value="$form->{"datepaid_$i"}" onBlur=\"check_right_date_format(this)\">
615          <input type="button" name="datepaid_$i" id="trigger_datepaid_$i" value="?"></td>|;
616     $column_data{"source_$i"} =
617       qq|<td align=center><input name="source_$i" size=11 value="$form->{"source_$i"}"></td>|;
618     $column_data{"memo_$i"} =
619       qq|<td align=center><input name="memo_$i" size=11 value="$form->{"memo_$i"}"></td>|;
620
621     map { print qq|$column_data{"${_}_$i"}\n| } @column_index;
622
623     print qq|
624         </tr>
625 |;
626     push(@triggers, "datepaid_$i", "BL", "trigger_datepaid_$i");
627   }
628
629   my $paid_missing = $form->{oldinvtotal} - $totalpaid;
630
631   print qq|
632         <tr>
633           <td></td>
634           <td></td>
635           <td align="center">| . $locale->text('Total') . qq|</td>
636           <td align="center">| . H($form->format_amount(\%myconfig, $totalpaid, 2)) . qq|</td>
637         </tr>
638         <tr>
639           <td></td>
640           <td></td>
641           <td align="center">| . $locale->text('Missing amount') . qq|</td>
642           <td align="center">| . H($form->format_amount(\%myconfig, $paid_missing, 2)) . qq|</td>
643         </tr>
644
645             <input type=hidden name=oldinvtotal value=$form->{oldinvtotal}>
646             <input type=hidden name=paidaccounts value=$form->{paidaccounts}>
647             <input type=hidden name=selectAP_paid value="$form->{selectAP_paid}">
648       </table>
649     </td>
650   </tr>
651   <tr>
652     <td><hr size=3 noshade></td>
653   </tr>
654 </table>
655 <br>
656 |;
657
658   my $invdate  = $form->datetonum($form->{invdate},  \%myconfig);
659   my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
660
661   print qq|<input class=submit type=submit name=action id=update_button value="|
662     . $locale->text('Update') . qq|">
663 |;
664
665   if ($form->{id}) {
666     my $show_storno = !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ap") && (($totalpaid == 0) || ($totalpaid eq ""));
667
668     print qq|<input class=submit type=submit name=action value="|
669       . $locale->text('Post Payment') . qq|">
670 |;
671     print qq|<input class=submit type=submit name=action value="|
672       . $locale->text('Storno') . qq|">
673 | if ($show_storno);
674     if ($form->{radier}) {
675     print qq|
676     <input class=submit type=submit name=action value="|
677       . $locale->text('Delete') . qq|">
678 |;
679   }
680     print qq|<input class=submit type=submit name=action value="|
681       . $locale->text('Use As Template') . qq|">
682         <input type="button" class="submit" onclick="follow_up_window()" value="|
683       . $locale->text('Follow-Up')
684       . qq|">
685 |;
686
687   }
688
689   if (!$form->{id} && ($invdate > $closedto)) {
690     print qq| <input class=submit type=submit name=action value="|
691       . $locale->text('Post') . qq|"> | .
692       NTI($cgi->submit('-name' => 'action', '-value' => $locale->text('Save draft'),
693                        '-class' => 'submit'));
694   }
695
696   print $form->write_trigger(\%myconfig, scalar(@triggers) / 3, @triggers);
697   $form->hide_form(qw(rowcount callback draft_id draft_description vendor_discount));
698
699   # button for saving history
700   if($form->{id} ne "") {
701     print qq|
702           <input type="button" class="submit" onclick="set_history_window(|
703           . Q($form->{id})
704           . qq|);" name="history" id="history" value="|
705           . $locale->text('history')
706           . qq|">|;
707   }
708   # /button for saving history
709   # mark_as_paid button
710   if($form->{id} ne "") {
711     print qq| <input type="submit" class="submit" name="action" value="|
712           . $locale->text('mark as paid') . qq|">|;
713   }
714   # /mark_as_paid button
715 print qq|</form>
716 </body>
717 </html>
718 |;
719
720   $main::lxdebug->leave_sub();
721 }
722
723 sub mark_as_paid {
724   $main::lxdebug->enter_sub();
725
726   my $form     = $main::form;
727   my %myconfig = %main::myconfig;
728
729   $main::auth->assert('vendor_invoice_edit');
730
731   &mark_as_paid_common(\%myconfig,"ap");
732
733   $main::lxdebug->leave_sub();
734 }
735
736 sub update {
737   $main::lxdebug->enter_sub();
738
739   my $form     = $main::form;
740   my %myconfig = %main::myconfig;
741
742   $main::auth->assert('vendor_invoice_edit');
743
744 #  map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) } qw(exchangerate creditlimit creditremaining);
745
746   &check_name('vendor');
747
748   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'sell');
749   $form->{exchangerate} = $form->{forex} if $form->{forex};
750
751   for my $i (1 .. $form->{paidaccounts}) {
752     next unless $form->{"paid_$i"};
753     map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
754     $form->{"forex_$i"}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
755     $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
756   }
757
758   my $i            = $form->{rowcount};
759   my $exchangerate = ($form->{exchangerate} * 1) || 1;
760
761   if (   ($form->{"partnumber_$i"} eq "")
762       && ($form->{"description_$i"} eq "")
763       && ($form->{"partsgroup_$i"} eq "")) {
764     $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
765     &check_form;
766
767   } else {
768
769     IR->retrieve_item(\%myconfig, \%$form);
770
771     my $rows = scalar @{ $form->{item_list} };
772
773     if ($rows) {
774       $form->{"qty_$i"} = 1 unless ($form->{"qty_$i"});
775
776       if ($rows > 1) {
777
778         &select_item;
779         exit;
780
781       } else {
782
783         # override sellprice if there is one entered
784         my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
785
786         # ergaenzung fuer bug 736 Lieferanten-Rabatt auch in Einkaufsrechnungen vorbelegen jb
787         $form->{"discount_$i"} = $form->format_amount(\%myconfig,
788                                                       $form->{vendor_discount} * 100 );
789         map { $form->{item_list}[$i]{$_} =~ s/\"/&quot;/g } qw(partnumber description unit);
790         map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
791
792         $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
793
794         ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
795         my $dec_qty       = length $1;
796         my $decimalplaces = max 2, $dec_qty;
797
798         if ($sellprice) {
799           $form->{"sellprice_$i"} = $sellprice;
800         } else {
801           # if there is an exchange rate adjust sellprice
802           $form->{"sellprice_$i"} /= $exchangerate;
803         }
804
805         my $amount                   = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"} / 100);
806         $form->{creditremaining} -= $amount;
807         $form->{"sellprice_$i"}   = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
808         $form->{"qty_$i"}         = $form->format_amount(\%myconfig, $form->{"qty_$i"},       $dec_qty);
809       }
810
811       &display_form;
812
813     } else {
814
815       # ok, so this is a new part
816       # ask if it is a part or service item
817
818       if (   $form->{"partsgroup_$i"}
819           && ($form->{"partsnumber_$i"} eq "")
820           && ($form->{"description_$i"} eq "")) {
821         $form->{rowcount}--;
822         $form->{"discount_$i"} = "";
823         display_form();
824
825       } else {
826         $form->{"id_$i"}   = 0;
827         new_item();
828       }
829     }
830   }
831   $main::lxdebug->leave_sub();
832 }
833
834 sub storno {
835   $main::lxdebug->enter_sub();
836
837   my $form     = $main::form;
838   my %myconfig = %main::myconfig;
839   my $locale   = $main::locale;
840
841   $main::auth->assert('vendor_invoice_edit');
842
843   if ($form->{storno}) {
844     $form->error($locale->text('Cannot storno storno invoice!'));
845   }
846
847   if (IS->has_storno(\%myconfig, $form, "ap")) {
848     $form->error($locale->text("Invoice has already been storno'd!"));
849   }
850
851   my $employee_id = $form->{employee_id};
852   invoice_links();
853   prepare_invoice();
854   relink_accounts();
855
856   # Payments must not be recorded for the new storno invoice.
857   $form->{paidaccounts} = 0;
858   map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
859
860   # saving the history
861   if(!exists $form->{addition} && $form->{id} ne "") {
862     $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
863     $form->{addition} = "CANCELED";
864     $form->save_history($form->dbconnect(\%myconfig));
865   }
866   # /saving the history
867
868   $form->{storno_id} = $form->{id};
869   $form->{storno} = 1;
870   $form->{id} = "";
871   $form->{invnumber} = "Storno zu " . $form->{invnumber};
872   $form->{rowcount}++;
873   $form->{employee_id} = $employee_id;
874   post();
875   $main::lxdebug->leave_sub();
876
877 }
878
879 sub use_as_template {
880   $main::lxdebug->enter_sub();
881
882   my $form     = $main::form;
883   my %myconfig = %main::myconfig;
884
885   $main::auth->assert('vendor_invoice_edit');
886
887   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);
888   $form->{paidaccounts} = 1;
889   $form->{rowcount}--;
890   $form->{invdate} = $form->current_date(\%myconfig);
891   &display_form;
892
893   $main::lxdebug->leave_sub();
894 }
895
896 sub post_payment {
897   $main::lxdebug->enter_sub();
898
899   my $form     = $main::form;
900   my %myconfig = %main::myconfig;
901   my $locale   = $main::locale;
902
903   $main::auth->assert('vendor_invoice_edit');
904
905   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
906   for my $i (1 .. $form->{paidaccounts}) {
907     if ($form->{"paid_$i"}) {
908       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
909
910       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
911
912       $form->error($locale->text('Cannot post payment for a closed period!'))
913         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
914
915       if ($form->{currency} ne $form->{defaultcurrency}) {
916 #        $form->{"exchangerate_$i"} = $form->{exchangerate} if ($invdate == $datepaid); # invdate isn't set here
917         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
918       }
919     }
920   }
921
922   ($form->{AP})      = split /--/, $form->{AP};
923   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
924   if (IR->post_payment(\%myconfig, \%$form)){
925         if (!exists $form->{addition} && $form->{id} ne "") {
926                 # saving the history
927       $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
928                 $form->{addition} = "PAYMENT POSTED";
929       $form->{what_done} = $form->{currency} . qq| | . $form->{paid} . qq| | . $locale->text("POSTED");
930                 $form->save_history($form->dbconnect(\%myconfig));
931                 # /saving the history
932         }
933
934     $form->redirect($locale->text('Payment posted!'));
935   }
936
937   $form->error($locale->text('Cannot post payment!'));
938
939   $main::lxdebug->leave_sub();
940 }
941
942 sub _max_datepaid {
943   my $form  =  $main::form;
944
945   my @dates = sort { $b->[1] cmp $a->[1] }
946               map  { [ $_, $main::locale->reformat_date(\%main::myconfig, $_, 'yyyy-mm-dd') ] }
947               grep { $_ }
948               map  { $form->{"datepaid_${_}"} }
949               (1..$form->{rowcount});
950
951   return @dates ? $dates[0]->[0] : undef;
952 }
953
954
955 sub post {
956   $main::lxdebug->enter_sub();
957
958   my $form     = $main::form;
959   my %myconfig = %main::myconfig;
960   my $locale   = $main::locale;
961
962   $main::auth->assert('vendor_invoice_edit');
963
964   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
965
966   $form->isblank("invdate",   $locale->text('Invoice Date missing!'));
967   $form->isblank("vendor",    $locale->text('Vendor missing!'));
968   $form->isblank("invnumber", $locale->text('Invnumber missing!'));
969
970   $form->{invnumber} =~ s/^\s*//g;
971   $form->{invnumber} =~ s/\s*$//g;
972
973   # if the vendor changed get new values
974   if (&check_name('vendor')) {
975     &update;
976     exit;
977   }
978
979   &validate_items;
980
981   my $closedto     = $form->datetonum($form->{closedto}, \%myconfig);
982   my $invdate      = $form->datetonum($form->{invdate},  \%myconfig);
983   my $max_datepaid = _max_datepaid();
984
985   $form->error($locale->text('Cannot post invoice for a closed period!')) if $max_datepaid && $form->date_closed($max_datepaid, \%myconfig);
986
987   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
988     if ($form->{currency} ne $form->{defaultcurrency});
989
990   my $i;
991   for $i (1 .. $form->{paidaccounts}) {
992     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
993       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
994
995       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
996
997       $form->error($locale->text('Cannot post payment for a closed period!'))
998         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
999
1000       if ($form->{currency} ne $form->{defaultcurrency}) {
1001         $form->{"exchangerate_$i"} = $form->{exchangerate}
1002           if ($invdate == $datepaid);
1003         $form->isblank("exchangerate_$i",
1004                        $locale->text('Exchangerate for payment missing!'));
1005       }
1006     }
1007   }
1008
1009   ($form->{AP})      = split /--/, $form->{AP};
1010   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
1011   $form->{storno}  ||= 0;
1012
1013   $form->{id} = 0 if $form->{postasnew};
1014
1015
1016   relink_accounts();
1017   if (IR->post_invoice(\%myconfig, \%$form)){
1018         # saving the history
1019         if(!exists $form->{addition} && $form->{id} ne "") {
1020       $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1021       $form->{addition} = "POSTED";
1022                 #$form->{what_done} = $locale->text("Rechnungsnummer") . qq| | . $form->{invnumber};
1023                 $form->save_history($form->dbconnect(\%myconfig));
1024         }
1025         # /saving the history
1026     remove_draft() if $form->{remove_draft};
1027         $form->redirect(  $locale->text('Invoice')
1028                   . " $form->{invnumber} "
1029                   . $locale->text('posted!'));
1030   }
1031   $form->error($locale->text('Cannot post invoice!'));
1032
1033   $main::lxdebug->leave_sub();
1034 }
1035
1036 sub delete {
1037   $main::lxdebug->enter_sub();
1038
1039   my $form     = $main::form;
1040   my $locale   = $main::locale;
1041
1042   $main::auth->assert('vendor_invoice_edit');
1043
1044   $form->header;
1045   print qq|
1046 <body>
1047
1048 <form method=post action=$form->{script}>
1049 |;
1050
1051   # delete action variable
1052   map { delete $form->{$_} } qw(action header);
1053
1054   foreach my $key (keys %$form) {
1055     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
1056     $form->{$key} =~ s/\"/&quot;/g;
1057     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
1058   }
1059
1060   print qq|
1061 <h2 class=confirm>| . $locale->text('Confirm!') . qq|</h2>
1062
1063 <h4>|
1064     . $locale->text('Are you sure you want to delete Invoice Number')
1065     . qq| $form->{invnumber}</h4>
1066 <p>
1067 <input name=action class=submit type=submit value="|
1068     . $locale->text('Yes') . qq|">
1069 </form>
1070 |;
1071
1072   $main::lxdebug->leave_sub();
1073 }
1074
1075 sub yes {
1076   $main::lxdebug->enter_sub();
1077
1078   my $form     = $main::form;
1079   my %myconfig = %main::myconfig;
1080   my $locale   = $main::locale;
1081
1082   $main::auth->assert('vendor_invoice_edit');
1083
1084   if (IR->delete_invoice(\%myconfig, \%$form)) {
1085     # saving the history
1086     if(!exists $form->{addition}) {
1087       $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1088           $form->{addition} = "DELETED";
1089           $form->save_history($form->dbconnect(\%myconfig));
1090     }
1091     # /saving the history
1092     $form->redirect($locale->text('Invoice deleted!'));
1093   }
1094   $form->error($locale->text('Cannot delete invoice!'));
1095
1096   $main::lxdebug->leave_sub();
1097 }
1098
1099 sub set_duedate_vendor {
1100   $main::lxdebug->enter_sub();
1101
1102   my $form     = $main::form;
1103
1104   print $form->ajax_response_header(), IR->get_duedate('vendor_id' => $form->{vendor_id},
1105                                                        'invdate'   => $form->{invdate},
1106                                                        'default'   => $form->{old_duedate});
1107
1108   $main::lxdebug->leave_sub();
1109 }