Merge branch 'curr_workflow'
[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('Record 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}   = $::lx_office_conf{features}->{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, $currency);
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   if ($form->{currency}) {
130     $currency = $form->{currency};
131   }
132
133   my $cp_id = $form->{cp_id};
134   IR->get_vendor(\%myconfig, \%$form);
135   IR->retrieve_invoice(\%myconfig, \%$form);
136   $form->{cp_id} = $cp_id;
137
138   if ($payment_id) {
139     $form->{payment_id} = $payment_id;
140   }
141   if ($language_id) {
142     $form->{language_id} = $language_id;
143   }
144   if ($taxzone_id) {
145     $form->{taxzone_id} = $taxzone_id;
146   }
147   if ($currency) {
148     $form->{currency} = $currency;
149   }
150
151   my @curr = split(/:/, $form->{currencies}); #seems to be missing
152   map { $form->{selectcurrency} .= "<option>$_\n" } @curr;
153
154   $form->{oldvendor} = "$form->{vendor}--$form->{vendor_id}";
155
156   # build vendor/customer drop down comatibility... don't ask
157   if (@{ $form->{"all_vendor"} || [] }) {
158     $form->{"selectvendor"} = 1;
159     $form->{vendor}         = qq|$form->{vendor}--$form->{vendor_id}|;
160   }
161
162   # departments
163   if ($form->{all_departments}) {
164     $form->{selectdepartment} = "<option>\n";
165     $form->{department}       = "$form->{department}--$form->{department_id}";
166
167     map {
168       $form->{selectdepartment} .=
169         "<option>$_->{description}--$_->{id}\n"
170     } (@{ $form->{all_departments} || [] });
171   }
172
173   # forex
174   $form->{forex} = $form->{exchangerate};
175   my $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
176
177   foreach my $key (keys %{ $form->{AP_links} }) {
178
179     foreach my $ref (@{ $form->{AP_links}{$key} }) {
180       $form->{"select$key"} .= "<option>$ref->{accno}--$ref->{description}</option>";
181     }
182
183     next unless $form->{acc_trans}{$key};
184
185     if ($key eq "AP_paid") {
186       for my $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
187         $form->{"AP_paid_$i"} =
188           "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
189
190         $form->{"acc_trans_id_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
191         # reverse paid
192         $form->{"paid_$i"}     = $form->{acc_trans}{$key}->[$i - 1]->{amount};
193         $form->{"datepaid_$i"} =
194           $form->{acc_trans}{$key}->[$i - 1]->{transdate};
195         $form->{"gldate_$i"}   = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
196         $form->{"forex_$i"} = $form->{"exchangerate_$i"} =
197           $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
198         $form->{"source_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{source};
199         $form->{"memo_$i"}   = $form->{acc_trans}{$key}->[$i - 1]->{memo};
200
201         $form->{paidaccounts} = $i;
202       }
203     } else {
204       $form->{$key} =
205         "$form->{acc_trans}{$key}->[0]->{accno}--$form->{acc_trans}{$key}->[0]->{description}";
206     }
207
208   }
209
210   $form->{paidaccounts} = 1 unless (exists $form->{paidaccounts});
211
212   $form->{AP} = $form->{AP_1} unless $form->{id};
213
214   $form->{locked} =
215     ($form->datetonum($form->{invdate}, \%myconfig) <=
216      $form->datetonum($form->{closedto}, \%myconfig));
217
218   $main::lxdebug->leave_sub();
219 }
220
221 sub prepare_invoice {
222   $main::lxdebug->enter_sub();
223
224   my $form     = $main::form;
225   my %myconfig = %main::myconfig;
226
227   $main::auth->assert('vendor_invoice_edit');
228
229   if ($form->{id}) {
230
231     map { $form->{$_} =~ s/\"/&quot;/g } qw(invnumber ordnumber quonumber);
232
233     my $i = 0;
234     foreach my $ref (@{ $form->{invoice_details} }) {
235       $i++;
236       map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
237       # übernommen aus is.pl Fix für Bug 1642. Nebenwirkungen? jb 12.5.2011
238       # getestet: Lieferantenauftrag -> Rechnung i.O.
239       #           Lieferantenauftrag -> Lieferschein -> Rechnung i.O.
240       # Werte: 20% (Lieferantenrabatt), 12,4% individuell und 0,4 individuell s.a.
241       # Screenshot zu Bug 1642
242       $form->{"discount_$i"}   = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100);
243
244       my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
245       $dec           = length $dec;
246       my $decimalplaces = ($dec > 2) ? $dec : 2;
247
248       $form->{"sellprice_$i"} =
249         $form->format_amount(\%myconfig, $form->{"sellprice_$i"},
250                              $decimalplaces);
251
252       (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
253       $dec_qty = length $dec_qty;
254
255       $form->{"qty_$i"} =
256         $form->format_amount(\%myconfig, ($form->{"qty_$i"} * -1), $dec_qty);
257
258       $form->{rowcount} = $i;
259     }
260   }
261
262   $main::lxdebug->leave_sub();
263 }
264
265 sub form_header {
266   $main::lxdebug->enter_sub();
267
268   my $form     = $main::form;
269   my %myconfig = %main::myconfig;
270   my $locale   = $main::locale;
271   my $cgi      = $::request->{cgi};
272
273   $main::auth->assert('vendor_invoice_edit');
274
275   my %TMPL_VAR = ();
276   my @custom_hiddens;
277
278   $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
279   $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
280
281   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
282
283   my @old_project_ids = ($form->{"globalproject_id"});
284   map { push @old_project_ids, $form->{"project_id_$_"} if $form->{"project_id_$_"}; } 1..$form->{"rowcount"};
285
286   $form->get_lists("contacts"      => "ALL_CONTACTS",
287                    "shipto"        => "ALL_SHIPTO",
288                    "projects"      => { "key"    => "ALL_PROJECTS",
289                                         "all"    => 0,
290                                         "old_id" => \@old_project_ids },
291                    "employees"     => "ALL_EMPLOYEES",
292                    "taxzones"      => "ALL_TAXZONES",
293                    "currencies"    => "ALL_CURRENCIES",
294                    "vendors"       => "ALL_VENDORS",
295                    "departments"   => "all_departments",
296                    "price_factors" => "ALL_PRICE_FACTORS");
297
298   $TMPL_VAR{sales_employee_labels} = sub { $_[0]->{name} || $_[0]->{login} };
299 #  $TMPL_VAR{shipto_labels}         = sub { join "; ", grep { $_ } map { $_[0]->{"shipto${_}" } } qw(name department_1 street city) };
300   $TMPL_VAR{contact_labels}        = sub { join(', ', $_[0]->{"cp_name"}, $_[0]->{"cp_givenname"}) . ($_[0]->{cp_abteilung} ? " ($_[0]->{cp_abteilung})" : "") };
301   $TMPL_VAR{department_labels}     = sub { "$_[0]->{description}--$_[0]->{id}" };
302
303   # customer
304   $TMPL_VAR{vc_keys} = sub { "$_[0]->{name}--$_[0]->{id}" };
305   $TMPL_VAR{vclimit} = $myconfig{vclimit};
306   $TMPL_VAR{vc_select} = "customer_or_vendor_selection_window('vendor', '', 1, 0)";
307   push @custom_hiddens, "vendor_id";
308   push @custom_hiddens, "oldvendor";
309   push @custom_hiddens, "selectvendor";
310
311   # currencies and exchangerate
312   my @values = map { $_       } @{ $form->{ALL_CURRENCIES} };
313   my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
314   $form->{currency}            = $form->{defaultcurrency} unless $form->{currency};
315   $TMPL_VAR{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
316   $TMPL_VAR{currencies}        = NTI($cgi->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
317                                                       '-values' => \@values, '-labels' => \%labels,
318                                                       '-onchange' => "document.getElementById('update_button').click();"
319                                      )) if scalar @values;
320   push @custom_hiddens, "forex";
321   push @custom_hiddens, "exchangerate" if $form->{forex};
322
323   $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
324   $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
325
326   $form->{fokus} = "invoice.vendor";
327
328   my $follow_up_vc         =  $form->{vendor};
329   $follow_up_vc            =~ s/--\d*\s*$//;
330   $TMPL_VAR{vendor_name} = $follow_up_vc;
331
332 # set option selected
333   foreach my $item (qw(AP)) {
334     $form->{"select$item"} =~ s/ selected//;
335     $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
336   }
337
338   $TMPL_VAR{is_type_credit_note} = $form->{type}   eq "credit_note";
339   $TMPL_VAR{is_format_html}      = $form->{format} eq 'html';
340   $TMPL_VAR{dateformat}          = $myconfig{dateformat};
341   $TMPL_VAR{numberformat}        = $myconfig{numberformat};
342
343   # hiddens
344   $TMPL_VAR{HIDDENS} = [qw(
345     id action type media format queued printed emailed title vc discount
346     title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
347     max_dunning_level dunning_amount
348     shiptoname shiptostreet shiptozipcode shiptocity shiptocountry  shiptocontact shiptophone shiptofax
349     shiptoemail shiptodepartment_1 shiptodepartment_2 message email subject cc bcc taxaccounts cursor_fokus
350     convert_from_do_ids convert_from_oe_ids
351   ), @custom_hiddens,
352   map { $_.'_rate', $_.'_description', $_.'_taxnumber' } split / /, $form->{taxaccounts}];
353
354   $form->{jsscript} = 1;
355   $form->header();
356
357   print $form->parse_html_template("ir/form_header", \%TMPL_VAR);
358
359   $main::lxdebug->leave_sub();
360 }
361
362 sub form_footer {
363   $main::lxdebug->enter_sub();
364
365   my $form     = $main::form;
366   my %myconfig = %main::myconfig;
367   my $locale   = $main::locale;
368
369   $main::auth->assert('vendor_invoice_edit');
370
371   $form->{invtotal}    = $form->{invsubtotal};
372   $form->{oldinvtotal} = $form->{invtotal};
373
374   # note rows
375   $form->{rows} = max 2,
376     $form->numtextrows($form->{notes},    26, 8),
377     $form->numtextrows($form->{intnotes}, 35, 8);
378
379
380   # tax, total and subtotal calculations
381   my ($tax, $subtotal);
382   $form->{taxaccounts_array} = [ split / /, $form->{taxaccounts} ];
383
384   foreach my $item (@{ $form->{taxaccounts_array} }) {
385     if ($form->{"${item}_base"}) {
386       if ($form->{taxincluded}) {
387         $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
388                                                                                  / (1 + $form->{"${item}_rate"})), 2);
389         $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
390       } else {
391         $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
392         $form->{invtotal} += $form->{"${item}_total"};
393       }
394     }
395   }
396
397   # follow ups
398   if ($form->{id}) {
399     $form->{follow_ups}            = FU->follow_ups('trans_id' => $form->{id}) || [];
400     $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
401   }
402
403   # payments
404   my $totalpaid = 0;
405   $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
406   $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
407
408   # Standard Konto für Umlaufvermögen
409   my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
410
411   for my $i (1 .. $form->{paidaccounts}) {
412     $form->{"changeable_$i"} = 1;
413     if ($::lx_office_conf{features}->{payments_changeable} == 0) {
414       # never
415       $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
416     } elsif ($::lx_office_conf{features}->{payments_changeable} == 2) {
417       # on the same day
418       $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
419                                   ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
420     }
421
422     $form->{"selectAP_paid_$i"} = $form->{selectAP_paid};
423     if (!$form->{"AP_paid_$i"}) {
424       $form->{"selectAP_paid_$i"} =~ s/option>$accno_arap--(.*?)>/option selected>$accno_arap--$1>/;
425     } else {
426       $form->{"selectAP_paid_$i"} =~ s/option>\Q$form->{"AP_paid_$i"}\E/option selected>$form->{"AP_paid_$i"}/;
427     }
428
429     $totalpaid += $form->{"paid_$i"};
430   }
431
432   print $form->parse_html_template('ir/form_footer', {
433     is_type_credit_note => ($form->{type} eq "credit_note"),
434     totalpaid           => $totalpaid,
435     paid_missing        => $form->{invtotal} - $totalpaid,
436     show_storno         => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ap") && !$totalpaid,
437     show_delete         => ($form->current_date(\%myconfig) eq $form->{gldate}),
438   });
439 ##print $form->parse_html_template('ir/_payments'); # parser
440 ##print $form->parse_html_template('webdav/_list'); # parser
441
442   $main::lxdebug->leave_sub();
443 }
444
445 sub mark_as_paid {
446   $main::lxdebug->enter_sub();
447
448   my $form     = $main::form;
449   my %myconfig = %main::myconfig;
450
451   $main::auth->assert('vendor_invoice_edit');
452
453   &mark_as_paid_common(\%myconfig,"ap");
454
455   $main::lxdebug->leave_sub();
456 }
457
458 sub update {
459   $main::lxdebug->enter_sub();
460
461   my $form     = $main::form;
462   my %myconfig = %main::myconfig;
463
464   $main::auth->assert('vendor_invoice_edit');
465
466 #  map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) } qw(exchangerate creditlimit creditremaining);
467
468   &check_name('vendor');
469
470   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'sell');
471   $form->{exchangerate} = $form->{forex} if $form->{forex};
472
473   for my $i (1 .. $form->{paidaccounts}) {
474     next unless $form->{"paid_$i"};
475     map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
476     $form->{"forex_$i"}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
477     $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
478   }
479
480   my $i            = $form->{rowcount};
481   my $exchangerate = ($form->{exchangerate} * 1) || 1;
482
483   if (   ($form->{"partnumber_$i"} eq "")
484       && ($form->{"description_$i"} eq "")
485       && ($form->{"partsgroup_$i"} eq "")) {
486     $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
487     &check_form;
488
489   } else {
490
491     IR->retrieve_item(\%myconfig, \%$form);
492
493     my $rows = scalar @{ $form->{item_list} };
494
495     if ($rows) {
496       $form->{"qty_$i"} = 1 unless $form->parse_amount(\%myconfig, $form->{"qty_$i"});
497
498       if ($rows > 1) {
499
500         select_item(mode => 'IR');
501         ::end_of_request();
502
503       } else {
504
505         # override sellprice if there is one entered
506         my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
507
508         # ergaenzung fuer bug 736 Lieferanten-Rabatt auch in Einkaufsrechnungen vorbelegen jb
509         $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{vendor_discount} * 100 );
510         map { $form->{item_list}[$i]{$_} =~ s/\"/&quot;/g } qw(partnumber description unit);
511         map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
512
513         $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
514
515         ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
516         my $dec_qty       = length $1;
517         my $decimalplaces = max 2, $dec_qty;
518
519         if ($sellprice) {
520           $form->{"sellprice_$i"} = $sellprice;
521         } else {
522           # if there is an exchange rate adjust sellprice
523           $form->{"sellprice_$i"} /= $exchangerate;
524         }
525
526         my $amount                   = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"} / 100);
527         $form->{creditremaining} -= $amount;
528         $form->{"sellprice_$i"}   = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
529         $form->{"qty_$i"}         = $form->format_amount(\%myconfig, $form->{"qty_$i"},       $dec_qty);
530       }
531
532       &display_form;
533
534     } else {
535
536       # ok, so this is a new part
537       # ask if it is a part or service item
538
539       if (   $form->{"partsgroup_$i"}
540           && ($form->{"partsnumber_$i"} eq "")
541           && ($form->{"description_$i"} eq "")) {
542         $form->{rowcount}--;
543         $form->{"discount_$i"} = "";
544         display_form();
545
546       } else {
547         $form->{"id_$i"}   = 0;
548         new_item();
549       }
550     }
551   }
552   $main::lxdebug->leave_sub();
553 }
554
555 sub storno {
556   $main::lxdebug->enter_sub();
557
558   my $form     = $main::form;
559   my %myconfig = %main::myconfig;
560   my $locale   = $main::locale;
561
562   $main::auth->assert('vendor_invoice_edit');
563
564   if ($form->{storno}) {
565     $form->error($locale->text('Cannot storno storno invoice!'));
566   }
567
568   if (IS->has_storno(\%myconfig, $form, "ap")) {
569     $form->error($locale->text("Invoice has already been storno'd!"));
570   }
571
572   my $employee_id = $form->{employee_id};
573   invoice_links();
574   prepare_invoice();
575   relink_accounts();
576
577   # Payments must not be recorded for the new storno invoice.
578   $form->{paidaccounts} = 0;
579   map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
580
581   # saving the history
582   if(!exists $form->{addition} && $form->{id} ne "") {
583     $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
584     $form->{addition} = "CANCELED";
585     $form->save_history;
586   }
587   # /saving the history
588
589   $form->{storno_id} = $form->{id};
590   $form->{storno} = 1;
591   $form->{id} = "";
592   $form->{invnumber} = "Storno zu " . $form->{invnumber};
593   $form->{rowcount}++;
594   $form->{employee_id} = $employee_id;
595   post();
596   $main::lxdebug->leave_sub();
597
598 }
599
600 sub use_as_template {
601   $main::lxdebug->enter_sub();
602
603   my $form     = $main::form;
604   my %myconfig = %main::myconfig;
605
606   $main::auth->assert('vendor_invoice_edit');
607
608   map { delete $form->{$_} } qw(printed emailed queued invnumber invdate deliverydate id datepaid_1 gldate_1 acc_trans_id_1 source_1 memo_1 paid_1 exchangerate_1 AP_paid_1 storno);
609   $form->{paidaccounts} = 1;
610   $form->{rowcount}--;
611   $form->{invdate} = $form->current_date(\%myconfig);
612   &display_form;
613
614   $main::lxdebug->leave_sub();
615 }
616
617 sub post_payment {
618   $main::lxdebug->enter_sub();
619
620   my $form     = $main::form;
621   my %myconfig = %main::myconfig;
622   my $locale   = $main::locale;
623
624   $main::auth->assert('vendor_invoice_edit');
625
626   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
627   for my $i (1 .. $form->{paidaccounts}) {
628     if ($form->{"paid_$i"}) {
629       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
630
631       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
632
633       $form->error($locale->text('Cannot post payment for a closed period!'))
634         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
635
636       if ($form->{currency} ne $form->{defaultcurrency}) {
637 #        $form->{"exchangerate_$i"} = $form->{exchangerate} if ($invdate == $datepaid); # invdate isn't set here
638         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
639       }
640     }
641   }
642
643   ($form->{AP})      = split /--/, $form->{AP};
644   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
645   if (IR->post_payment(\%myconfig, \%$form)){
646     if (!exists $form->{addition} && $form->{id} ne "") {
647       # saving the history
648       $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
649       $form->{addition} = "PAYMENT POSTED";
650       $form->{what_done} = $form->{currency} . qq| | . $form->{paid} . qq| | . $locale->text("POSTED");
651       $form->save_history;
652       # /saving the history
653     }
654
655     $form->redirect($locale->text('Payment posted!'));
656   }
657
658   $form->error($locale->text('Cannot post payment!'));
659
660   $main::lxdebug->leave_sub();
661 }
662
663 sub _max_datepaid {
664   my $form  =  $main::form;
665
666   my @dates = sort { $b->[1] cmp $a->[1] }
667               map  { [ $_, $main::locale->reformat_date(\%main::myconfig, $_, 'yyyy-mm-dd') ] }
668               grep { $_ }
669               map  { $form->{"datepaid_${_}"} }
670               (1..$form->{rowcount});
671
672   return @dates ? $dates[0]->[0] : undef;
673 }
674
675
676 sub post {
677   $main::lxdebug->enter_sub();
678
679   my $form     = $main::form;
680   my %myconfig = %main::myconfig;
681   my $locale   = $main::locale;
682
683   $main::auth->assert('vendor_invoice_edit');
684
685   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
686
687   $form->isblank("invdate",   $locale->text('Invoice Date missing!'));
688   $form->isblank("vendor",    $locale->text('Vendor missing!'));
689   $form->isblank("invnumber", $locale->text('Invnumber missing!'));
690
691   $form->{invnumber} =~ s/^\s*//g;
692   $form->{invnumber} =~ s/\s*$//g;
693
694   # if the vendor changed get new values
695   if (&check_name('vendor')) {
696     &update;
697     ::end_of_request();
698   }
699
700   if ($myconfig{mandatory_departments} && !$form->{department_id}) {
701     $form->{saved_message} = $::locale->text('You have to specify a department.');
702     update();
703     exit;
704   }
705
706   remove_emptied_rows();
707   &validate_items;
708
709   my $closedto     = $form->datetonum($form->{closedto}, \%myconfig);
710   my $invdate      = $form->datetonum($form->{invdate},  \%myconfig);
711   my $max_datepaid = _max_datepaid();
712
713   $form->error($locale->text('Cannot post invoice for a closed period!')) if $max_datepaid && $form->date_closed($max_datepaid, \%myconfig);
714
715   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
716     if ($form->{currency} ne $form->{defaultcurrency});
717
718   my $i;
719   for $i (1 .. $form->{paidaccounts}) {
720     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
721       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
722
723       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
724
725       $form->error($locale->text('Cannot post payment for a closed period!'))
726         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
727
728       if ($form->{currency} ne $form->{defaultcurrency}) {
729         $form->{"exchangerate_$i"} = $form->{exchangerate}
730           if ($invdate == $datepaid);
731         $form->isblank("exchangerate_$i",
732                        $locale->text('Exchangerate for payment missing!'));
733       }
734     }
735   }
736
737   ($form->{AP})      = split /--/, $form->{AP};
738   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
739   $form->{storno}  ||= 0;
740
741   $form->{id} = 0 if $form->{postasnew};
742
743
744   relink_accounts();
745   if (IR->post_invoice(\%myconfig, \%$form)){
746     # saving the history
747     if(!exists $form->{addition} && $form->{id} ne "") {
748       $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
749       $form->{addition} = "POSTED";
750       #$form->{what_done} = $locale->text("Rechnungsnummer") . qq| | . $form->{invnumber};
751       $form->save_history;
752     }
753     # /saving the history
754     remove_draft() if $form->{remove_draft};
755     $form->redirect(  $locale->text('Invoice')
756                   . " $form->{invnumber} "
757                   . $locale->text('posted!'));
758   }
759   $form->error($locale->text('Cannot post invoice!'));
760
761   $main::lxdebug->leave_sub();
762 }
763
764 sub delete {
765   $main::lxdebug->enter_sub();
766
767   my $form     = $main::form;
768   my $locale   = $main::locale;
769
770   $main::auth->assert('vendor_invoice_edit');
771
772   $form->header;
773   print qq|
774 <body>
775
776 <form method=post action=$form->{script}>
777 |;
778
779   # delete action variable
780   map { delete $form->{$_} } qw(action header);
781
782   foreach my $key (keys %$form) {
783     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
784     $form->{$key} =~ s/\"/&quot;/g;
785     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
786   }
787
788   print qq|
789 <h2 class=confirm>| . $locale->text('Confirm!') . qq|</h2>
790
791 <h4>|
792     . $locale->text('Are you sure you want to delete Invoice Number')
793     . qq| $form->{invnumber}</h4>
794 <p>
795 <input name=action class=submit type=submit value="|
796     . $locale->text('Yes') . qq|">
797 </form>
798 |;
799
800   $main::lxdebug->leave_sub();
801 }
802
803 sub yes {
804   $main::lxdebug->enter_sub();
805
806   my $form     = $main::form;
807   my %myconfig = %main::myconfig;
808   my $locale   = $main::locale;
809
810   $main::auth->assert('vendor_invoice_edit');
811
812   if (IR->delete_invoice(\%myconfig, \%$form)) {
813     # saving the history
814     if(!exists $form->{addition}) {
815       $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
816       $form->{addition} = "DELETED";
817       $form->save_history;
818     }
819     # /saving the history
820     $form->redirect($locale->text('Invoice deleted!'));
821   }
822   $form->error($locale->text('Cannot delete invoice!'));
823
824   $main::lxdebug->leave_sub();
825 }
826
827 sub get_duedate_vendor {
828   $::lxdebug->enter_sub;
829
830   my $result = IR->get_duedate(
831     vendor_id => $::form->{vendor_id},
832     invdate   => $::form->{invdate},
833     default   => $::form->{old_duedate},
834   );
835
836   print $::form->ajax_response_header, $result;
837   $::lxdebug->leave_sub;
838 }