01adc735e621c96da8335840596d3e9e37326177
[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                    "price_factors" => "ALL_PRICE_FACTORS");
287
288   $TMPL_VAR{sales_employee_labels} = sub { $_[0]->{name} || $_[0]->{login} };
289 #  $TMPL_VAR{shipto_labels}         = sub { join "; ", grep { $_ } map { $_[0]->{"shipto${_}" } } qw(name department_1 street city) };
290   $TMPL_VAR{contact_labels}        = sub { join(', ', $_[0]->{"cp_name"}, $_[0]->{"cp_givenname"}) . ($_[0]->{cp_abteilung} ? " ($_[0]->{cp_abteilung})" : "") };
291   $TMPL_VAR{department_labels}     = sub { "$_[0]->{description}--$_[0]->{id}" };
292
293   # customer
294   $TMPL_VAR{vc_keys} = sub { "$_[0]->{name}--$_[0]->{id}" };
295   $TMPL_VAR{vclimit} = $myconfig{vclimit};
296   $TMPL_VAR{vc_select} = "customer_or_vendor_selection_window('vendor', '', 1, 0)";
297   push @custom_hiddens, "vendor_id";
298   push @custom_hiddens, "oldvendor";
299   push @custom_hiddens, "selectvendor";
300
301   # currencies and exchangerate
302   my @values = map { $_       } @{ $form->{ALL_CURRENCIES} };
303   my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
304   $form->{currency}            = $form->{defaultcurrency} unless $form->{currency};
305   $TMPL_VAR{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
306   $TMPL_VAR{currencies}        = NTI($cgi->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
307                                                       '-values' => \@values, '-labels' => \%labels)) if scalar @values;
308   push @custom_hiddens, "forex";
309   push @custom_hiddens, "exchangerate" if $form->{forex};
310
311   $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
312   $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
313
314   $form->{fokus} = "invoice.vendor";
315
316   my $follow_up_vc         =  $form->{vendor};
317   $follow_up_vc            =~ s/--\d*\s*$//;
318   $TMPL_VAR{vendor_name} = $follow_up_vc;
319
320 # set option selected
321   foreach my $item (qw(AP)) {
322     $form->{"select$item"} =~ s/ selected//;
323     $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
324   }
325
326   $TMPL_VAR{is_type_credit_note} = $form->{type}   eq "credit_note";
327   $TMPL_VAR{is_format_html}      = $form->{format} eq 'html';
328   $TMPL_VAR{dateformat}          = $myconfig{dateformat};
329   $TMPL_VAR{numberformat}        = $myconfig{numberformat};
330
331   # hiddens
332   $TMPL_VAR{HIDDENS} = [qw(
333     id action type media format queued printed emailed title vc discount
334     title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
335     max_dunning_level dunning_amount
336     shiptoname shiptostreet shiptozipcode shiptocity shiptocountry  shiptocontact shiptophone shiptofax
337     shiptoemail shiptodepartment_1 shiptodepartment_2 message email subject cc bcc taxaccounts cursor_fokus
338     convert_from_do_ids convert_from_oe_ids
339   ), @custom_hiddens,
340   map { $_.'_rate', $_.'_description', $_.'_taxnumber' } split / /, $form->{taxaccounts}];
341
342   $form->{jsscript} = 1;
343   $form->header();
344
345   print $form->parse_html_template("ir/form_header", \%TMPL_VAR);
346
347   $main::lxdebug->leave_sub();
348 }
349
350 sub form_footer {
351   $main::lxdebug->enter_sub();
352
353   my $form     = $main::form;
354   my %myconfig = %main::myconfig;
355   my $locale   = $main::locale;
356   my $cgi      = $main::cgi;
357
358   $main::auth->assert('vendor_invoice_edit');
359
360   $form->{invtotal} = $form->{invsubtotal};
361
362   my ($rows, $introws);
363   if (($rows = $form->numtextrows($form->{notes}, 25, 8)) < 2) {
364     $rows = 2;
365   }
366   if (($introws = $form->numtextrows($form->{intnotes}, 35, 8)) < 2) {
367     $introws = 2;
368   }
369   $rows = ($rows > $introws) ? $rows : $introws;
370   my $notes =
371     qq|<textarea name=notes rows=$rows cols=25 wrap=soft>$form->{notes}</textarea>|;
372   my $intnotes =
373     qq|<textarea name=intnotes rows=$rows cols=35 wrap=soft>$form->{intnotes}</textarea>|;
374
375   $form->{taxincluded} = ($form->{taxincluded}) ? "checked" : "";
376
377   my $taxincluded = "";
378   if ($form->{taxaccounts}) {
379     $taxincluded = qq|
380                 <input name=taxincluded class=checkbox type=checkbox value=1 $form->{taxincluded}> <b>|
381       . $locale->text('Tax Included') . qq|</b>
382 |;
383   }
384
385   my ($tax, $subtotal);
386   if (!$form->{taxincluded}) {
387
388     foreach my $item (split / /, $form->{taxaccounts}) {
389       if ($form->{"${item}_base"}) {
390         $form->{invtotal} += $form->{"${item}_total"} =
391           $form->round_amount(
392                              $form->{"${item}_base"} * $form->{"${item}_rate"},
393                              2);
394         $form->{"${item}_total"} =
395           $form->format_amount(\%myconfig, $form->{"${item}_total"}, 2);
396
397         $tax .= qq|
398                 <tr>
399                   <th align=right>$form->{"${item}_description"}&nbsp;|
400                     . $form->{"${item}_rate"} * 100 .qq|%</th>
401                   <td align=right>$form->{"${item}_total"}</td>
402                 </tr>
403 |;
404       }
405     }
406
407     $form->{invsubtotal} =
408       $form->format_amount(\%myconfig, $form->{invsubtotal}, 2, 0);
409
410     $subtotal = qq|
411               <tr>
412                 <th align=right>| . $locale->text('Subtotal') . qq|</th>
413                 <td align=right>$form->{invsubtotal}</td>
414               </tr>
415 |;
416
417   }
418
419   if ($form->{taxincluded}) {
420     foreach my $item (split / /, $form->{taxaccounts}) {
421       if ($form->{"${item}_base"}) {
422         $form->{"${item}_total"} =
423           $form->round_amount(
424                            ($form->{"${item}_base"} * $form->{"${item}_rate"} /
425                               (1 + $form->{"${item}_rate"})
426                            ),
427                            2);
428         $form->{"${item}_base"} =
429           $form->round_amount($form->{"${item}_base"}, 2);
430         $form->{"${item}_netto"} =
431           $form->round_amount(
432                           ($form->{"${item}_base"} - $form->{"${item}_total"}),
433                           2);
434         $form->{"${item}_netto"} =
435           $form->format_amount(\%myconfig, $form->{"${item}_netto"}, 2);
436         $form->{"${item}_total"} =
437           $form->format_amount(\%myconfig, $form->{"${item}_total"}, 2);
438
439         $tax .= qq|
440               <tr>
441                 <th align=right>Enthaltene $form->{"${item}_description"}&nbsp;|
442                                     . $form->{"${item}_rate"} * 100 .qq|%</th>
443                 <td align=right>$form->{"${item}_total"}</td>
444               </tr>
445               <tr>
446                 <th align=right>Nettobetrag</th>
447                 <td align=right>$form->{"${item}_netto"}</td>
448               </tr>
449 |;
450       }
451     }
452
453   }
454
455   $form->{oldinvtotal} = $form->{invtotal};
456   $form->{invtotal}    =
457     $form->format_amount(\%myconfig, $form->{invtotal}, 2, 0);
458
459   my $follow_ups_block;
460   if ($form->{id}) {
461     my $follow_ups = FU->follow_ups('trans_id' => $form->{id});
462
463     if (@{ $follow_ups} ) {
464       my $num_due       = sum map { $_->{due} * 1 } @{ $follow_ups };
465       $follow_ups_block = qq|
466       <tr>
467         <td colspan="2">| . $locale->text("There are #1 unfinished follow-ups of which #2 are due.", scalar @{ $follow_ups }, $num_due) . qq|</td>
468       </tr>
469 |;
470     }
471   }
472
473   our $colspan;
474   print qq|
475   <tr>
476     <td colspan=$colspan>
477       <table cellspacing="0">
478         <tr valign=bottom>
479           <td>
480             <table>
481               <tr>
482                 <th align=left>| . $locale->text('Notes') . qq|</th>
483                 <th align=left>| . $locale->text('Internal Notes') . qq|</th>
484               </tr>
485               <tr valign=top>
486                 <td>$notes</td>
487                 <td>$intnotes</td>
488               </tr>
489         $follow_ups_block
490             </table>
491           </td>
492           <td colspan=2 align=right width=100%>
493             $taxincluded
494             <br>
495             <table width=100%>
496               $subtotal
497               $tax
498               <tr>
499                 <th align=right>| . $locale->text('Total') . qq|</th>
500                 <td align=right>$form->{invtotal}</td>
501               </tr>
502             </table>
503           </td>
504         </tr>
505       </table>
506     </td>
507   </tr>
508 |;
509   my $webdav_list;
510   if ($main::webdav) {
511     $webdav_list = qq|
512   <tr>
513     <td><hr size=3 noshade></td>
514   </tr>
515   <tr>
516     <th class=listtop align=left>Dokumente im Webdav-Repository</th>
517   </tr>
518     <table width=100%>
519       <td align=left width=30%><b>Dateiname</b></td>
520       <td align=left width=70%><b>Webdavlink</b></td>
521 |;
522     foreach my $file (@{ $form->{WEBDAV} }) {
523       $webdav_list .= qq|
524       <tr>
525         <td align="left">$file->{name}</td>
526         <td align="left"><a href="$file->{link}">$file->{type}</a></td>
527       </tr>
528 |;
529     }
530     $webdav_list .= qq|
531     </table>
532   </tr>
533 |;
534
535     print $webdav_list;
536   }
537   print qq|
538   <tr>
539     <td colspan=$colspan>
540       <table width=100%>
541         <tr>
542           <th colspan=6 class=listheading>| . $locale->text('Payments') . qq|</th>
543         </tr>
544 |;
545
546   my @column_index;
547   if ($form->{currency} eq $form->{defaultcurrency}) {
548     @column_index = qw(datepaid source memo paid AP_paid);
549   } else {
550     @column_index = qw(datepaid source memo paid exchangerate AP_paid);
551   }
552
553   my %column_data;
554   $column_data{datepaid}     = "<th>" . $locale->text('Date') . "</th>";
555   $column_data{paid}         = "<th>" . $locale->text('Amount') . "</th>";
556   $column_data{exchangerate} = "<th>" . $locale->text('Exch') . "</th>";
557   $column_data{AP_paid}      = "<th>" . $locale->text('Account') . "</th>";
558   $column_data{source}       = "<th>" . $locale->text('Source') . "</th>";
559   $column_data{memo}         = "<th>" . $locale->text('Memo') . "</th>";
560
561   print qq|
562         <tr>
563 |;
564   map { print "$column_data{$_}\n" } @column_index;
565   print qq|
566         </tr>
567 |;
568
569   my @triggers  = ();
570   my $totalpaid = 0;
571
572   $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
573   for my $i (1 .. $form->{paidaccounts}) {
574
575     print qq|
576         <tr>
577 |;
578
579     $form->{"selectAP_paid_$i"} = $form->{selectAP_paid};
580     $form->{"selectAP_paid_$i"} =~
581       s/option>\Q$form->{"AP_paid_$i"}\E/option selected>$form->{"AP_paid_$i"}/;
582
583     $totalpaid += $form->{"paid_$i"};
584
585     # format amounts
586     if ($form->{"paid_$i"}) {
587       $form->{"paid_$i"} =
588         $form->format_amount(\%myconfig, $form->{"paid_$i"}, 2);
589     }
590     $form->{"exchangerate_$i"} =
591       $form->format_amount(\%myconfig, $form->{"exchangerate_$i"});
592
593     my $exchangerate = qq|&nbsp;|;
594     if ($form->{currency} ne $form->{defaultcurrency}) {
595       if ($form->{"forex_$i"}) {
596         $exchangerate =
597           qq|<input type=hidden name="exchangerate_$i" value=$form->{"exchangerate_$i"}>$form->{"exchangerate_$i"}|;
598       } else {
599         $exchangerate =
600           qq|<input name="exchangerate_$i" size=10 value=$form->{"exchangerate_$i"}>|;
601       }
602     }
603     $exchangerate .= qq|
604 <input type=hidden name="forex_$i" value=$form->{"forex_$i"}>
605 |;
606
607     $column_data{"paid_$i"} =
608       qq|<td align=center><input name="paid_$i" size=11 value="$form->{"paid_$i"}" onBlur=\"check_right_number_format(this)\"></td>|;
609     $column_data{"exchangerate_$i"} = qq|<td align=center>$exchangerate</td>|;
610     $column_data{"AP_paid_$i"}      =
611       qq|<td align=center><select name="AP_paid_$i">$form->{"selectAP_paid_$i"}</select></td>|;
612     $column_data{"datepaid_$i"} =
613       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)\">
614          <input type="button" name="datepaid_$i" id="trigger_datepaid_$i" value="?"></td>|;
615     $column_data{"source_$i"} =
616       qq|<td align=center><input name="source_$i" size=11 value="$form->{"source_$i"}"></td>|;
617     $column_data{"memo_$i"} =
618       qq|<td align=center><input name="memo_$i" size=11 value="$form->{"memo_$i"}"></td>|;
619
620     map { print qq|$column_data{"${_}_$i"}\n| } @column_index;
621
622     print qq|
623         </tr>
624 |;
625     push(@triggers, "datepaid_$i", "BL", "trigger_datepaid_$i");
626   }
627
628   my $paid_missing = $form->{oldinvtotal} - $totalpaid;
629
630   print qq|
631         <tr>
632           <td></td>
633           <td></td>
634           <td align="center">| . $locale->text('Total') . qq|</td>
635           <td align="center">| . H($form->format_amount(\%myconfig, $totalpaid, 2)) . qq|</td>
636         </tr>
637         <tr>
638           <td></td>
639           <td></td>
640           <td align="center">| . $locale->text('Missing amount') . qq|</td>
641           <td align="center">| . H($form->format_amount(\%myconfig, $paid_missing, 2)) . qq|</td>
642         </tr>
643
644             <input type=hidden name=oldinvtotal value=$form->{oldinvtotal}>
645             <input type=hidden name=paidaccounts value=$form->{paidaccounts}>
646             <input type=hidden name=selectAP_paid value="$form->{selectAP_paid}">
647       </table>
648     </td>
649   </tr>
650   <tr>
651     <td><hr size=3 noshade></td>
652   </tr>
653 </table>
654 <br>
655 |;
656
657   my $invdate  = $form->datetonum($form->{invdate},  \%myconfig);
658   my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
659
660   print qq|<input class=submit type=submit name=action id=update_button value="|
661     . $locale->text('Update') . qq|">
662 |;
663
664   if ($form->{id}) {
665     my $show_storno = !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ap") && (($totalpaid == 0) || ($totalpaid eq ""));
666
667     print qq|<input class=submit type=submit name=action value="|
668       . $locale->text('Post Payment') . qq|">
669 |;
670     print qq|<input class=submit type=submit name=action value="|
671       . $locale->text('Storno') . qq|">
672 | if ($show_storno);
673     if ($form->{radier}) {
674     print qq|
675     <input class=submit type=submit name=action value="|
676       . $locale->text('Delete') . qq|">
677 |;
678   }
679     print qq|<input class=submit type=submit name=action value="|
680       . $locale->text('Use As Template') . qq|">
681         <input type="button" class="submit" onclick="follow_up_window()" value="|
682       . $locale->text('Follow-Up')
683       . qq|">
684 |;
685
686   }
687
688   if (!$form->{id} && ($invdate > $closedto)) {
689     print qq| <input class=submit type=submit name=action value="|
690       . $locale->text('Post') . qq|"> | .
691       NTI($cgi->submit('-name' => 'action', '-value' => $locale->text('Save draft'),
692                        '-class' => 'submit'));
693   }
694
695   print $form->write_trigger(\%myconfig, scalar(@triggers) / 3, @triggers);
696   $form->hide_form(qw(rowcount callback draft_id draft_description vendor_discount));
697
698   # button for saving history
699   if($form->{id} ne "") {
700     print qq|
701           <input type="button" class="submit" onclick="set_history_window(|
702           . Q($form->{id})
703           . qq|);" name="history" id="history" value="|
704           . $locale->text('history')
705           . qq|">|;
706   }
707   # /button for saving history
708   # mark_as_paid button
709   if($form->{id} ne "") {
710     print qq| <input type="submit" class="submit" name="action" value="|
711           . $locale->text('mark as paid') . qq|">|;
712   }
713   # /mark_as_paid button
714 print qq|</form>
715 </body>
716 </html>
717 |;
718
719   $main::lxdebug->leave_sub();
720 }
721
722 sub mark_as_paid {
723   $main::lxdebug->enter_sub();
724
725   my $form     = $main::form;
726   my %myconfig = %main::myconfig;
727
728   $main::auth->assert('vendor_invoice_edit');
729
730   &mark_as_paid_common(\%myconfig,"ap");
731
732   $main::lxdebug->leave_sub();
733 }
734
735 sub update {
736   $main::lxdebug->enter_sub();
737
738   my $form     = $main::form;
739   my %myconfig = %main::myconfig;
740
741   $main::auth->assert('vendor_invoice_edit');
742
743   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) } qw(exchangerate creditlimit creditremaining);
744
745   &check_name('vendor');
746
747   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'sell');
748   $form->{exchangerate} = $form->{forex} if $form->{forex};
749
750   for my $i (1 .. $form->{paidaccounts}) {
751     next unless $form->{"paid_$i"};
752     map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
753     $form->{"forex_$i"}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
754     $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
755   }
756
757   my $i            = $form->{rowcount};
758   my $exchangerate = ($form->{exchangerate} * 1) || 1;
759
760   if (   ($form->{"partnumber_$i"} eq "")
761       && ($form->{"description_$i"} eq "")
762       && ($form->{"partsgroup_$i"} eq "")) {
763     $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
764     &check_form;
765
766   } else {
767
768     IR->retrieve_item(\%myconfig, \%$form);
769
770     my $rows = scalar @{ $form->{item_list} };
771
772     if ($rows) {
773       $form->{"qty_$i"} = 1 unless ($form->{"qty_$i"});
774
775       if ($rows > 1) {
776
777         &select_item;
778         exit;
779
780       } else {
781
782         # override sellprice if there is one entered
783         my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
784
785         # ergaenzung fuer bug 736 Lieferanten-Rabatt auch in Einkaufsrechnungen vorbelegen jb
786         $form->{"discount_$i"} = $form->format_amount(\%myconfig,
787                                                       $form->{vendor_discount} * 100 );
788         map { $form->{item_list}[$i]{$_} =~ s/\"/&quot;/g } qw(partnumber description unit);
789         map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
790
791         $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
792
793         ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
794         my $dec_qty       = length $1;
795         my $decimalplaces = max 2, $dec_qty;
796
797         if ($sellprice) {
798           $form->{"sellprice_$i"} = $sellprice;
799         } else {
800           # if there is an exchange rate adjust sellprice
801           $form->{"sellprice_$i"} /= $exchangerate;
802         }
803
804         my $amount                   = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"} / 100);
805         $form->{creditremaining} -= $amount;
806         $form->{"sellprice_$i"}   = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
807         $form->{"qty_$i"}         = $form->format_amount(\%myconfig, $form->{"qty_$i"},       $dec_qty);
808       }
809
810       &display_form;
811
812     } else {
813
814       # ok, so this is a new part
815       # ask if it is a part or service item
816
817       if (   $form->{"partsgroup_$i"}
818           && ($form->{"partsnumber_$i"} eq "")
819           && ($form->{"description_$i"} eq "")) {
820         $form->{rowcount}--;
821         $form->{"discount_$i"} = "";
822         display_form();
823
824       } else {
825         $form->{"id_$i"}   = 0;
826         new_item();
827       }
828     }
829   }
830   $main::lxdebug->leave_sub();
831 }
832
833 sub storno {
834   $main::lxdebug->enter_sub();
835
836   my $form     = $main::form;
837   my %myconfig = %main::myconfig;
838   my $locale   = $main::locale;
839
840   $main::auth->assert('vendor_invoice_edit');
841
842   if ($form->{storno}) {
843     $form->error($locale->text('Cannot storno storno invoice!'));
844   }
845
846   if (IS->has_storno(\%myconfig, $form, "ap")) {
847     $form->error($locale->text("Invoice has already been storno'd!"));
848   }
849
850   my $employee_id = $form->{employee_id};
851   invoice_links();
852   prepare_invoice();
853   relink_accounts();
854
855   # Payments must not be recorded for the new storno invoice.
856   $form->{paidaccounts} = 0;
857   map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
858
859   # saving the history
860   if(!exists $form->{addition} && $form->{id} ne "") {
861     $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
862     $form->{addition} = "CANCELED";
863     $form->save_history($form->dbconnect(\%myconfig));
864   }
865   # /saving the history
866
867   $form->{storno_id} = $form->{id};
868   $form->{storno} = 1;
869   $form->{id} = "";
870   $form->{invnumber} = "Storno zu " . $form->{invnumber};
871   $form->{rowcount}++;
872   $form->{employee_id} = $employee_id;
873   post();
874   $main::lxdebug->leave_sub();
875
876 }
877
878 sub use_as_template {
879   $main::lxdebug->enter_sub();
880
881   my $form     = $main::form;
882   my %myconfig = %main::myconfig;
883
884   $main::auth->assert('vendor_invoice_edit');
885
886   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);
887   $form->{paidaccounts} = 1;
888   $form->{rowcount}--;
889   $form->{invdate} = $form->current_date(\%myconfig);
890   &display_form;
891
892   $main::lxdebug->leave_sub();
893 }
894
895 sub post_payment {
896   $main::lxdebug->enter_sub();
897
898   my $form     = $main::form;
899   my %myconfig = %main::myconfig;
900   my $locale   = $main::locale;
901
902   $main::auth->assert('vendor_invoice_edit');
903
904   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
905   for my $i (1 .. $form->{paidaccounts}) {
906     if ($form->{"paid_$i"}) {
907       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
908
909       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
910
911       $form->error($locale->text('Cannot post payment for a closed period!'))
912         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
913
914       if ($form->{currency} ne $form->{defaultcurrency}) {
915 #        $form->{"exchangerate_$i"} = $form->{exchangerate} if ($invdate == $datepaid); # invdate isn't set here
916         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
917       }
918     }
919   }
920
921   ($form->{AP})      = split /--/, $form->{AP};
922   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
923   if (IR->post_payment(\%myconfig, \%$form)){
924         if (!exists $form->{addition} && $form->{id} ne "") {
925                 # saving the history
926       $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
927                 $form->{addition} = "PAYMENT POSTED";
928       $form->{what_done} = $form->{currency} . qq| | . $form->{paid} . qq| | . $locale->text("POSTED");
929                 $form->save_history($form->dbconnect(\%myconfig));
930                 # /saving the history
931         }
932
933     $form->redirect($locale->text('Payment posted!'));
934   }
935
936   $form->error($locale->text('Cannot post payment!'));
937
938   $main::lxdebug->leave_sub();
939 }
940
941 sub _max_datepaid {
942   my $form  =  $main::form;
943
944   my @dates = sort { $b->[1] cmp $a->[1] }
945               map  { [ $_, $main::locale->reformat_date(\%main::myconfig, $_, 'yyyy-mm-dd') ] }
946               grep { $_ }
947               map  { $form->{"datepaid_${_}"} }
948               (1..$form->{rowcount});
949
950   return @dates ? $dates[0]->[0] : undef;
951 }
952
953
954 sub post {
955   $main::lxdebug->enter_sub();
956
957   my $form     = $main::form;
958   my %myconfig = %main::myconfig;
959   my $locale   = $main::locale;
960
961   $main::auth->assert('vendor_invoice_edit');
962
963   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
964
965   $form->isblank("invdate",   $locale->text('Invoice Date missing!'));
966   $form->isblank("vendor",    $locale->text('Vendor missing!'));
967   $form->isblank("invnumber", $locale->text('Invnumber missing!'));
968
969   $form->{invnumber} =~ s/^\s*//g;
970   $form->{invnumber} =~ s/\s*$//g;
971
972   # if the vendor changed get new values
973   if (&check_name('vendor')) {
974     &update;
975     exit;
976   }
977
978   &validate_items;
979
980   my $closedto     = $form->datetonum($form->{closedto}, \%myconfig);
981   my $invdate      = $form->datetonum($form->{invdate},  \%myconfig);
982   my $max_datepaid = _max_datepaid();
983
984   $form->error($locale->text('Cannot post invoice for a closed period!')) if $max_datepaid && $form->date_closed($max_datepaid, \%myconfig);
985
986   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
987     if ($form->{currency} ne $form->{defaultcurrency});
988
989   my $i;
990   for $i (1 .. $form->{paidaccounts}) {
991     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
992       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
993
994       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
995
996       $form->error($locale->text('Cannot post payment for a closed period!'))
997         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
998
999       if ($form->{currency} ne $form->{defaultcurrency}) {
1000         $form->{"exchangerate_$i"} = $form->{exchangerate}
1001           if ($invdate == $datepaid);
1002         $form->isblank("exchangerate_$i",
1003                        $locale->text('Exchangerate for payment missing!'));
1004       }
1005     }
1006   }
1007
1008   ($form->{AP})      = split /--/, $form->{AP};
1009   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
1010   $form->{storno}  ||= 0;
1011
1012   $form->{id} = 0 if $form->{postasnew};
1013
1014
1015   relink_accounts();
1016   if (IR->post_invoice(\%myconfig, \%$form)){
1017         # saving the history
1018         if(!exists $form->{addition} && $form->{id} ne "") {
1019       $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1020       $form->{addition} = "POSTED";
1021                 #$form->{what_done} = $locale->text("Rechnungsnummer") . qq| | . $form->{invnumber};
1022                 $form->save_history($form->dbconnect(\%myconfig));
1023         }
1024         # /saving the history
1025     remove_draft() if $form->{remove_draft};
1026         $form->redirect(  $locale->text('Invoice')
1027                   . " $form->{invnumber} "
1028                   . $locale->text('posted!'));
1029   }
1030   $form->error($locale->text('Cannot post invoice!'));
1031
1032   $main::lxdebug->leave_sub();
1033 }
1034
1035 sub delete {
1036   $main::lxdebug->enter_sub();
1037
1038   my $form     = $main::form;
1039   my $locale   = $main::locale;
1040
1041   $main::auth->assert('vendor_invoice_edit');
1042
1043   $form->header;
1044   print qq|
1045 <body>
1046
1047 <form method=post action=$form->{script}>
1048 |;
1049
1050   # delete action variable
1051   map { delete $form->{$_} } qw(action header);
1052
1053   foreach my $key (keys %$form) {
1054     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
1055     $form->{$key} =~ s/\"/&quot;/g;
1056     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
1057   }
1058
1059   print qq|
1060 <h2 class=confirm>| . $locale->text('Confirm!') . qq|</h2>
1061
1062 <h4>|
1063     . $locale->text('Are you sure you want to delete Invoice Number')
1064     . qq| $form->{invnumber}</h4>
1065 <p>
1066 <input name=action class=submit type=submit value="|
1067     . $locale->text('Yes') . qq|">
1068 </form>
1069 |;
1070
1071   $main::lxdebug->leave_sub();
1072 }
1073
1074 sub yes {
1075   $main::lxdebug->enter_sub();
1076
1077   my $form     = $main::form;
1078   my %myconfig = %main::myconfig;
1079   my $locale   = $main::locale;
1080
1081   $main::auth->assert('vendor_invoice_edit');
1082
1083   if (IR->delete_invoice(\%myconfig, \%$form)) {
1084     # saving the history
1085     if(!exists $form->{addition}) {
1086       $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1087           $form->{addition} = "DELETED";
1088           $form->save_history($form->dbconnect(\%myconfig));
1089     }
1090     # /saving the history
1091     $form->redirect($locale->text('Invoice deleted!'));
1092   }
1093   $form->error($locale->text('Cannot delete invoice!'));
1094
1095   $main::lxdebug->leave_sub();
1096 }
1097
1098 sub set_duedate_vendor {
1099   $main::lxdebug->enter_sub();
1100
1101   my $form     = $main::form;
1102
1103   print $form->ajax_response_header(), IR->get_duedate('vendor_id' => $form->{vendor_id},
1104                                                        'invdate'   => $form->{invdate},
1105                                                        'default'   => $form->{old_duedate});
1106
1107   $main::lxdebug->leave_sub();
1108 }