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