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