16eb69eca01f86d6e838dee4e16b25ae0aeeae1c
[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., 51 Franklin Street, Fifth Floor, Boston,
28 # MA 02110-1335, USA.
29 #======================================================================
30 #
31 # Inventory received module
32 #
33 #======================================================================
34
35 use SL::FU;
36 use SL::IR;
37 use SL::IS;
38 use SL::DB::Default;
39 use SL::DB::Department;
40 use SL::DB::PurchaseInvoice;
41 use SL::DB::Vendor;
42 use List::Util qw(max sum);
43 use List::UtilsBy qw(sort_by);
44
45 require "bin/mozilla/io.pl";
46 require "bin/mozilla/arap.pl";
47 require "bin/mozilla/common.pl";
48
49 use strict;
50
51 1;
52
53 # end of main
54
55 sub add {
56   $main::lxdebug->enter_sub();
57
58   my $form     = $main::form;
59   my $locale   = $main::locale;
60
61   $main::auth->assert('vendor_invoice_edit');
62
63   if (!$::instance_conf->get_allow_new_purchase_invoice) {
64     $::form->show_generic_error($::locale->text("You do not have the permissions to access this function."));
65   }
66
67   $form->{show_details} = $::myconfig{show_form_details};
68
69   $form->{title} = $locale->text('Record Vendor Invoice');
70
71   &invoice_links;
72   &prepare_invoice;
73   &display_form;
74
75   $main::lxdebug->leave_sub();
76 }
77
78 sub edit {
79   $main::lxdebug->enter_sub();
80
81   my $form     = $main::form;
82   my $locale   = $main::locale;
83
84   $main::auth->assert('vendor_invoice_edit');
85
86   $form->{show_details} = $::myconfig{show_form_details};
87
88   # show history button
89   $form->{javascript} = qq|<script type=text/javascript src=js/show_history.js></script>|;
90   #/show hhistory button
91
92   $form->{title} = $locale->text('Edit Vendor Invoice');
93
94   &invoice_links;
95   &prepare_invoice;
96   &display_form;
97
98   $main::lxdebug->leave_sub();
99 }
100
101 sub invoice_links {
102   $main::lxdebug->enter_sub();
103
104   my $form     = $main::form;
105   my %myconfig = %main::myconfig;
106
107   $main::auth->assert('vendor_invoice_edit');
108
109   $form->{vc} = 'vendor';
110
111   # create links
112   $form->create_links("AP", \%myconfig, "vendor");
113
114   $form->backup_vars(qw(payment_id language_id taxzone_id
115                         currency delivery_term_id intnotes cp_id));
116
117   IR->get_vendor(\%myconfig, \%$form);
118   IR->retrieve_invoice(\%myconfig, \%$form);
119
120   $form->restore_vars(qw(payment_id language_id taxzone_id
121                          currency delivery_term_id intnotes cp_id));
122
123   my @curr = $form->get_all_currencies();
124   map { $form->{selectcurrency} .= "<option>$_\n" } @curr;
125
126   # forex
127   $form->{forex} = $form->{exchangerate};
128   my $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
129
130   foreach my $key (keys %{ $form->{AP_links} }) {
131
132     foreach my $ref (@{ $form->{AP_links}{$key} }) {
133       $form->{"select$key"} .= "<option>$ref->{accno}--$ref->{description}</option>";
134     }
135
136     next unless $form->{acc_trans}{$key};
137
138     if ($key eq "AP_paid") {
139       for my $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
140         $form->{"AP_paid_$i"} =
141           "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
142
143         $form->{"acc_trans_id_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
144         # reverse paid
145         $form->{"paid_$i"}     = $form->{acc_trans}{$key}->[$i - 1]->{amount};
146         $form->{"datepaid_$i"} =
147           $form->{acc_trans}{$key}->[$i - 1]->{transdate};
148         $form->{"gldate_$i"}   = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
149         $form->{"forex_$i"} = $form->{"exchangerate_$i"} =
150           $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
151         $form->{"source_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{source};
152         $form->{"memo_$i"}   = $form->{acc_trans}{$key}->[$i - 1]->{memo};
153
154         $form->{paidaccounts} = $i;
155       }
156     } else {
157       $form->{$key} =
158         "$form->{acc_trans}{$key}->[0]->{accno}--$form->{acc_trans}{$key}->[0]->{description}";
159     }
160
161   }
162
163   $form->{paidaccounts} = 1 unless (exists $form->{paidaccounts});
164
165   $form->{AP} = $form->{AP_1} unless $form->{id};
166
167   $form->{locked} =
168     ($form->datetonum($form->{invdate}, \%myconfig) <=
169      $form->datetonum($form->{closedto}, \%myconfig));
170
171   $main::lxdebug->leave_sub();
172 }
173
174 sub prepare_invoice {
175   $main::lxdebug->enter_sub();
176
177   my $form     = $main::form;
178   my %myconfig = %main::myconfig;
179
180   $main::auth->assert('vendor_invoice_edit');
181
182   $form->{type}     = "purchase_invoice";
183
184   if ($form->{id}) {
185
186     map { $form->{$_} =~ s/\"/&quot;/g } qw(invnumber ordnumber quonumber);
187
188     my $i = 0;
189     foreach my $ref (@{ $form->{invoice_details} }) {
190       $i++;
191       map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
192       # übernommen aus is.pl Fix für Bug 1642. Nebenwirkungen? jb 12.5.2011
193       # getestet: Lieferantenauftrag -> Rechnung i.O.
194       #           Lieferantenauftrag -> Lieferschein -> Rechnung i.O.
195       # Werte: 20% (Lieferantenrabatt), 12,4% individuell und 0,4 individuell s.a.
196       # Screenshot zu Bug 1642
197       $form->{"discount_$i"}   = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100);
198
199       my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
200       $dec           = length $dec;
201       my $decimalplaces = ($dec > 2) ? $dec : 2;
202
203       $form->{"sellprice_$i"} =
204         $form->format_amount(\%myconfig, $form->{"sellprice_$i"},
205                              $decimalplaces);
206
207       (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
208       $dec_qty = length $dec_qty;
209
210       $form->{"qty_$i"} =
211         $form->format_amount(\%myconfig, ($form->{"qty_$i"} * -1), $dec_qty);
212
213       $form->{rowcount} = $i;
214     }
215   }
216
217   $main::lxdebug->leave_sub();
218 }
219
220 sub form_header {
221   $main::lxdebug->enter_sub();
222
223   my $form     = $main::form;
224   my %myconfig = %main::myconfig;
225   my $locale   = $main::locale;
226   my $cgi      = $::request->{cgi};
227
228   $main::auth->assert('vendor_invoice_edit');
229
230   my %TMPL_VAR = ();
231   my @custom_hiddens;
232
233   $TMPL_VAR{invoice_obj} = SL::DB::PurchaseInvoice->load_cached($form->{id}) if $form->{id};
234   $TMPL_VAR{vendor_obj}  = SL::DB::Vendor->load_cached($form->{vendor_id})   if $form->{vendor_id};
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
238   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
239
240   my @old_project_ids = ($form->{"globalproject_id"});
241   map { push @old_project_ids, $form->{"project_id_$_"} if $form->{"project_id_$_"}; } 1..$form->{"rowcount"};
242
243   $form->get_lists("taxzones"      => ($form->{id} ? "ALL_TAXZONES" : "ALL_ACTIVE_TAXZONES"),
244                    "currencies"    => "ALL_CURRENCIES",
245                    "price_factors" => "ALL_PRICE_FACTORS");
246
247   $TMPL_VAR{ALL_DEPARTMENTS}       = SL::DB::Manager::Department->get_all_sorted;
248   $TMPL_VAR{ALL_EMPLOYEES}         = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{employee_id},  deleted => 0 ] ]);
249   $TMPL_VAR{ALL_CONTACTS}          = SL::DB::Manager::Contact->get_all_sorted(query => [
250     or => [
251       cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
252       and      => [
253         cp_cv_id => undef,
254         cp_id    => $::form->{cp_id} * 1
255       ]
256     ]
257   ]);
258
259   # currencies and exchangerate
260   my @values = map { $_       } @{ $form->{ALL_CURRENCIES} };
261   my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
262   $form->{currency}            = $form->{defaultcurrency} unless $form->{currency};
263   # show_exchangerate is also later needed in another template
264   $form->{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
265   $TMPL_VAR{currencies}        = NTI($cgi->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
266                                                       '-values' => \@values, '-labels' => \%labels,
267                                                       '-onchange' => "document.getElementById('update_button').click();"
268                                      )) if scalar @values;
269   push @custom_hiddens, "forex";
270   push @custom_hiddens, "exchangerate" if $form->{forex};
271
272   $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
273   $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
274
275 # set option selected
276   foreach my $item (qw(AP)) {
277     $form->{"select$item"} =~ s/ selected//;
278     $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
279   }
280
281   $TMPL_VAR{is_type_credit_note} = $form->{type}   eq "credit_note";
282   $TMPL_VAR{is_format_html}      = $form->{format} eq 'html';
283   $TMPL_VAR{dateformat}          = $myconfig{dateformat};
284   $TMPL_VAR{numberformat}        = $myconfig{numberformat};
285
286   # hiddens
287   $TMPL_VAR{HIDDENS} = [qw(
288     id action type media format queued printed emailed title vc discount
289     title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
290     max_dunning_level dunning_amount
291     shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptogln shiptocontact shiptophone shiptofax
292     shiptoemail shiptodepartment_1 shiptodepartment_2 message email subject cc bcc taxaccounts cursor_fokus
293     convert_from_do_ids convert_from_oe_ids convert_from_ap_ids show_details gldate useasnew
294   ), @custom_hiddens,
295   map { $_.'_rate', $_.'_description', $_.'_taxnumber' } split / /, $form->{taxaccounts}];
296
297   $TMPL_VAR{payment_terms_obj} = get_payment_terms_for_invoice();
298   $form->{duedate}             = $TMPL_VAR{payment_terms_obj}->calc_date(reference_date => $form->{invdate}, due_date => $form->{due_due})->to_kivitendo if $TMPL_VAR{payment_terms_obj};
299
300   $::request->{layout}->use_javascript(map { "${_}.js" } qw(kivi.Draft kivi.SalesPurchase ckeditor/ckeditor ckeditor/adapters/jquery kivi.io autocomplete_customer autocomplete_part autocomplete_project client_js));
301
302   $form->header();
303
304   print $form->parse_html_template("ir/form_header", \%TMPL_VAR);
305
306   $main::lxdebug->leave_sub();
307 }
308
309 sub _sort_payments {
310   my @fields   = qw(acc_trans_id gldate datepaid source memo paid AP_paid);
311   my @payments =
312     grep { $_->{paid} != 0 }
313     map  {
314       my $idx = $_;
315       +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
316     } (1..$::form->{paidaccounts});
317
318   @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
319
320   $::form->{paidaccounts} = max scalar(@payments), 1;
321
322   foreach my $idx (1 .. scalar(@payments)) {
323     my $payment = $payments[$idx - 1];
324     $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
325   }
326 }
327
328 sub form_footer {
329   $main::lxdebug->enter_sub();
330
331   my $form     = $main::form;
332   my %myconfig = %main::myconfig;
333   my $locale   = $main::locale;
334
335   $main::auth->assert('vendor_invoice_edit');
336
337   $form->{invtotal}    = $form->{invsubtotal};
338   $form->{oldinvtotal} = $form->{invtotal};
339
340   # note rows
341   $form->{rows} = max 2,
342     $form->numtextrows($form->{notes},    26, 8),
343     $form->numtextrows($form->{intnotes}, 35, 8);
344
345
346   # tax, total and subtotal calculations
347   my ($tax, $subtotal);
348   $form->{taxaccounts_array} = [ split / /, $form->{taxaccounts} ];
349
350   foreach my $item (@{ $form->{taxaccounts_array} }) {
351     if ($form->{"${item}_base"}) {
352       if ($form->{taxincluded}) {
353         $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
354                                                                                  / (1 + $form->{"${item}_rate"})), 2);
355         $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
356       } else {
357         $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
358         $form->{invtotal} += $form->{"${item}_total"};
359       }
360     }
361   }
362
363   # follow ups
364   if ($form->{id}) {
365     $form->{follow_ups}            = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1) || [];
366     $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
367   }
368
369   # payments
370   _sort_payments();
371
372   my $totalpaid = 0;
373   $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
374   $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
375
376   # Standard Konto für Umlaufvermögen
377   my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
378
379   for my $i (1 .. $form->{paidaccounts}) {
380     $form->{"changeable_$i"} = 1;
381     if (SL::DB::Default->get->payments_changeable == 0) {
382       # never
383       $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
384     } elsif (SL::DB::Default->get->payments_changeable == 2) {
385       # on the same day
386       $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
387                                   ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
388     }
389
390     $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
391       if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
392
393     #deaktivieren von Zahlungen ausserhalb der Bücherkontrolle
394     if ($form->date_closed($form->{"gldate_$i"})) {
395       $form->{"changeable_$i"} = 0;
396     }
397
398     $form->{"selectAP_paid_$i"} = $form->{selectAP_paid};
399     if (!$form->{"AP_paid_$i"}) {
400       $form->{"selectAP_paid_$i"} =~ s/option>$accno_arap--(.*?)>/option selected>$accno_arap--$1>/;
401     } else {
402       $form->{"selectAP_paid_$i"} =~ s/option>\Q$form->{"AP_paid_$i"}\E/option selected>$form->{"AP_paid_$i"}/;
403     }
404
405     $totalpaid += $form->{"paid_$i"};
406   }
407
408   $form->{ALL_DELIVERY_TERMS} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
409
410   print $form->parse_html_template('ir/form_footer', {
411     is_type_credit_note => ($form->{type} eq "credit_note"),
412     totalpaid           => $totalpaid,
413     paid_missing        => $form->{invtotal} - $totalpaid,
414     show_storno         => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ap") && !$totalpaid,
415     show_delete         => ($::instance_conf->get_ir_changeable == 2)
416                              ? ($form->current_date(\%myconfig) eq $form->{gldate})
417                              : ($::instance_conf->get_ir_changeable == 1),
418     today               => DateTime->today,
419   });
420 ##print $form->parse_html_template('ir/_payments'); # parser
421 ##print $form->parse_html_template('webdav/_list'); # parser
422
423   $main::lxdebug->leave_sub();
424 }
425
426 sub mark_as_paid {
427   $::auth->assert('vendor_invoice_edit');
428
429   SL::DB::PurchaseInvoice->new(id => $::form->{id})->load->mark_as_paid;
430
431   $::form->redirect($::locale->text("Marked as paid"));
432 }
433
434 sub show_draft {
435   update();
436 }
437
438 sub update {
439   $main::lxdebug->enter_sub();
440
441   my $form     = $main::form;
442   my %myconfig = %main::myconfig;
443
444   $main::auth->assert('vendor_invoice_edit');
445
446   if (($form->{previous_vendor_id} || $form->{vendor_id}) != $form->{vendor_id}) {
447     IR->get_vendor(\%myconfig, $form);
448   }
449
450   if (!$form->{forex}) {        # read exchangerate from input field (not hidden)
451     $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate});
452   }
453   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'sell');
454   $form->{exchangerate} = $form->{forex} if $form->{forex};
455
456   for my $i (1 .. $form->{paidaccounts}) {
457     next unless $form->{"paid_$i"};
458     map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
459     $form->{"forex_$i"}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
460     $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
461   }
462
463   my $i            = $form->{rowcount};
464   my $exchangerate = ($form->{exchangerate} * 1) || 1;
465
466   if (   ($form->{"partnumber_$i"} eq "")
467       && ($form->{"description_$i"} eq "")
468       && ($form->{"partsgroup_$i"} eq "")) {
469     $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
470     &check_form;
471
472   } else {
473
474     IR->retrieve_item(\%myconfig, \%$form);
475
476     my $rows = scalar @{ $form->{item_list} };
477
478     $form->{"discount_$i"}   = $form->parse_amount(\%myconfig, $form->{"discount_$i"}) / 100.0;
479     $form->{"discount_$i"} ||= $form->{vendor_discount};
480
481     if ($rows) {
482       $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
483       if( !$form->{"qty_$i"} ) {
484         $form->{"qty_$i"} = 1;
485       }
486
487       if ($rows > 1) {
488
489         select_item(mode => 'IR', pre_entered_qty => $form->{"qty_$i"});
490         $::dispatcher->end_request;
491
492       } else {
493
494         # override sellprice if there is one entered
495         my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
496
497         map { $form->{item_list}[$i]{$_} =~ s/\"/&quot;/g } qw(partnumber description unit);
498         map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
499
500         $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
501
502         ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
503         my $dec_qty       = length $1;
504         my $decimalplaces = max 2, $dec_qty;
505
506         if ($sellprice) {
507           $form->{"sellprice_$i"} = $sellprice;
508         } else {
509           my $record        = _make_record();
510           my $price_source  = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
511           my $best_price    = $price_source->best_price;
512           my $best_discount = $price_source->best_discount;
513
514           if ($best_price) {
515             $::form->{"sellprice_$i"}           = $best_price->price;
516             $::form->{"active_price_source_$i"} = $best_price->source;
517           }
518           if ($best_discount) {
519             $::form->{"discount_$i"}               = $best_discount->discount;
520             $::form->{"active_discount_source_$i"} = $best_discount->source;
521           }
522
523           # if there is an exchange rate adjust sellprice
524           $form->{"sellprice_$i"} /= $exchangerate;
525         }
526
527         my $amount                = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"});
528         $form->{creditremaining} -= $amount;
529         $form->{"sellprice_$i"}   = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
530         $form->{"qty_$i"}         = $form->format_amount(\%myconfig, $form->{"qty_$i"},       $dec_qty);
531         $form->{"discount_$i"}    = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
532       }
533
534       &display_form;
535
536     } else {
537
538       # ok, so this is a new part
539       # ask if it is a part or service item
540
541       if (   $form->{"partsgroup_$i"}
542           && ($form->{"partsnumber_$i"} eq "")
543           && ($form->{"description_$i"} eq "")) {
544         $form->{rowcount}--;
545         $form->{"discount_$i"} = "";
546         display_form();
547
548       } else {
549         $form->{"id_$i"}   = 0;
550         new_item();
551       }
552     }
553   }
554   $main::lxdebug->leave_sub();
555 }
556
557 sub storno {
558   $main::lxdebug->enter_sub();
559
560   my $form     = $main::form;
561   my %myconfig = %main::myconfig;
562   my $locale   = $main::locale;
563
564   $main::auth->assert('vendor_invoice_edit');
565
566   if ($form->{storno}) {
567     $form->error($locale->text('Cannot storno storno invoice!'));
568   }
569
570   if (IS->has_storno(\%myconfig, $form, "ap")) {
571     $form->error($locale->text("Invoice has already been storno'd!"));
572   }
573
574   $form->error($locale->text('Cannot post storno for a closed period!'))
575     if ( $form->date_closed($form->{invdate}, \%myconfig));
576
577   my $employee_id = $form->{employee_id};
578   invoice_links();
579   prepare_invoice();
580   relink_accounts();
581
582   # Payments must not be recorded for the new storno invoice.
583   $form->{paidaccounts} = 0;
584   map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
585   # set new ids for storno invoice
586   # set new persistent ids for storno invoice items
587   $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
588
589   # saving the history
590   if(!exists $form->{addition} && $form->{id} ne "") {
591     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
592     $form->{what_done} = "invoice";
593     $form->{addition}  = "CANCELED";
594     $form->save_history;
595   }
596   # /saving the history
597
598   # record link invoice to storno
599   $form->{convert_from_ap_ids} = $form->{id};
600   $form->{storno_id} = $form->{id};
601   $form->{storno} = 1;
602   $form->{id} = "";
603   $form->{invnumber} = "Storno zu " . $form->{invnumber};
604   $form->{rowcount}++;
605   $form->{employee_id} = $employee_id;
606   post();
607   $main::lxdebug->leave_sub();
608
609 }
610
611 sub use_as_new {
612   $main::lxdebug->enter_sub();
613
614   my $form     = $main::form;
615   my %myconfig = %main::myconfig;
616
617   $main::auth->assert('vendor_invoice_edit');
618
619   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);
620   $form->{paidaccounts} = 1;
621   $form->{rowcount}--;
622   $form->{invdate} = $form->current_date(\%myconfig);
623
624   $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
625
626   $form->{useasnew} = 1;
627   &display_form;
628
629   $main::lxdebug->leave_sub();
630 }
631
632 sub post_payment {
633   $main::lxdebug->enter_sub();
634
635   my $form     = $main::form;
636   my %myconfig = %main::myconfig;
637   my $locale   = $main::locale;
638
639   $main::auth->assert('vendor_invoice_edit');
640
641   $form->mtime_ischanged('ap') ;
642   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
643   for my $i (1 .. $form->{paidaccounts}) {
644     if ($form->{"paid_$i"}) {
645       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
646
647       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
648
649       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
650         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
651
652       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
653       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
654       $form->error($locale->text('Cannot post payment for a closed period!'))
655         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
656
657       if ($form->{currency} ne $form->{defaultcurrency}) {
658 #        $form->{"exchangerate_$i"} = $form->{exchangerate} if ($invdate == $datepaid); # invdate isn't set here
659         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
660       }
661     }
662   }
663
664   ($form->{AP})      = split /--/, $form->{AP};
665   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
666   if (IR->post_payment(\%myconfig, \%$form)){
667     if (!exists $form->{addition} && $form->{id} ne "") {
668       # saving the history
669       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
670       $form->{addition}  = "PAYMENT POSTED";
671       $form->{what_done} = "invoice";
672       $form->save_history;
673       # /saving the history
674     }
675
676     $form->redirect($locale->text('Payment posted!'));
677   }
678
679   $form->error($locale->text('Cannot post payment!'));
680
681   $main::lxdebug->leave_sub();
682 }
683
684 sub _max_datepaid {
685   my $form  =  $main::form;
686
687   my @dates = sort { $b->[1] cmp $a->[1] }
688               map  { [ $_, $main::locale->reformat_date(\%main::myconfig, $_, 'yyyy-mm-dd') ] }
689               grep { $_ }
690               map  { $form->{"datepaid_${_}"} }
691               (1..$form->{rowcount});
692
693   return @dates ? $dates[0]->[0] : undef;
694 }
695
696
697 sub post {
698   $main::lxdebug->enter_sub();
699
700   my $form     = $main::form;
701   my %myconfig = %main::myconfig;
702   my $locale   = $main::locale;
703
704   $main::auth->assert('vendor_invoice_edit');
705
706   $form->mtime_ischanged('ap');
707   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
708
709   $form->isblank("invdate",   $locale->text('Invoice Date missing!'));
710   $form->isblank("vendor_id", $locale->text('Vendor missing!'));
711   $form->isblank("invnumber", $locale->text('Invnumber missing!'));
712
713   $form->{invnumber} =~ s/^\s*//g;
714   $form->{invnumber} =~ s/\s*$//g;
715
716   # if the vendor changed get new values
717   if (($form->{previous_vendor_id} || $form->{vendor_id}) != $form->{vendor_id}) {
718     &update;
719     $::dispatcher->end_request;
720   }
721
722   if ($myconfig{mandatory_departments} && !$form->{department_id}) {
723     $form->{saved_message} = $::locale->text('You have to specify a department.');
724     update();
725     exit;
726   }
727
728   remove_emptied_rows();
729   &validate_items;
730
731   my $closedto     = $form->datetonum($form->{closedto}, \%myconfig);
732   my $invdate      = $form->datetonum($form->{invdate},  \%myconfig);
733   my $max_datepaid = _max_datepaid();
734
735   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
736     if ($form->date_max_future($invdate, \%myconfig));
737   $form->error($locale->text('Cannot post invoice for a closed period!'))
738     if ($invdate <= $closedto);
739
740   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
741     if ($form->{currency} ne $form->{defaultcurrency});
742
743   my $i;
744   for $i (1 .. $form->{paidaccounts}) {
745     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
746       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
747
748       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
749
750       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
751         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
752
753       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
754       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
755       $form->error($locale->text('Cannot post payment for a closed period!'))
756         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
757
758       if ($form->{currency} ne $form->{defaultcurrency}) {
759         $form->{"exchangerate_$i"} = $form->{exchangerate}
760           if ($invdate == $datepaid);
761         $form->isblank("exchangerate_$i",
762                        $locale->text('Exchangerate for payment missing!'));
763       }
764     }
765   }
766
767   ($form->{AP})      = split /--/, $form->{AP};
768   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
769   $form->{storno}  ||= 0;
770
771   $form->{id} = 0 if $form->{postasnew};
772
773
774   relink_accounts();
775   if (IR->post_invoice(\%myconfig, \%$form)){
776     # saving the history
777     if(!exists $form->{addition} && $form->{id} ne "") {
778       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
779       $form->{addition}  = "POSTED";
780       $form->{what_done} = 'invoice';
781       $form->save_history;
782     }
783     # /saving the history
784     $form->redirect(  $locale->text('Invoice')
785                   . " $form->{invnumber} "
786                   . $locale->text('posted!'));
787   }
788   $form->error($locale->text('Cannot post invoice!'));
789
790   $main::lxdebug->leave_sub();
791 }
792
793 sub delete {
794   $main::lxdebug->enter_sub();
795
796   my $form     = $main::form;
797   my $locale   = $main::locale;
798
799   $main::auth->assert('vendor_invoice_edit');
800
801   $form->header;
802   print qq|
803 <form method=post action=$form->{script}>
804 |;
805
806   # delete action variable
807   map { delete $form->{$_} } qw(action header);
808
809   foreach my $key (keys %$form) {
810     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
811     $form->{$key} =~ s/\"/&quot;/g;
812     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
813   }
814
815   print qq|
816 <h2 class=confirm>| . $locale->text('Confirm!') . qq|</h2>
817
818 <h4>|
819     . $locale->text('Are you sure you want to delete Invoice Number')
820     . qq| $form->{invnumber}</h4>
821 <p>
822 <input name=action class=submit type=submit value="|
823     . $locale->text('Yes') . qq|">
824 </form>
825 |;
826
827   $main::lxdebug->leave_sub();
828 }
829
830 sub display_form {
831   $::lxdebug->enter_sub;
832
833   $::auth->assert('vendor_invoice_edit');
834
835   relink_accounts();
836
837   my $new_rowcount = $::form->{"rowcount"} * 1 + 1;
838   $::form->{"project_id_${new_rowcount}"} = $::form->{"globalproject_id"};
839
840   $::form->language_payment(\%::myconfig);
841
842   Common::webdav_folder($::form);
843
844   form_header();
845   display_row(++$::form->{rowcount});
846   form_footer();
847
848   $::lxdebug->leave_sub;
849 }
850
851 sub yes {
852   $main::lxdebug->enter_sub();
853
854   my $form     = $main::form;
855   my %myconfig = %main::myconfig;
856   my $locale   = $main::locale;
857
858   $main::auth->assert('vendor_invoice_edit');
859
860   if (IR->delete_invoice(\%myconfig, \%$form)) {
861     # saving the history
862     if(!exists $form->{addition}) {
863       $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
864       $form->{addition} = "DELETED";
865       $form->save_history;
866     }
867     # /saving the history
868     $form->redirect($locale->text('Invoice deleted!'));
869   }
870   $form->error($locale->text('Cannot delete invoice!'));
871
872   $main::lxdebug->leave_sub();
873 }
874
875 sub get_duedate_vendor {
876   $::lxdebug->enter_sub;
877
878   my $result = IR->get_duedate(
879     vendor_id => $::form->{vendor_id},
880     invdate   => $::form->{invdate},
881     default   => $::form->{old_duedate},
882   );
883
884   print $::form->ajax_response_header, $result;
885   $::lxdebug->leave_sub;
886 }