Prüfung ob nach einer Buchung noch ein Beleg erfasst werden soll
[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::BankTransactionAccTrans;
39 use SL::DB::Default;
40 use SL::DB::Department;
41 use SL::DB::Project;
42 use SL::DB::PurchaseInvoice;
43 use SL::DB::Vendor;
44 use List::MoreUtils qw(uniq);
45 use List::Util qw(max sum);
46 use List::UtilsBy qw(sort_by);
47
48 require "bin/mozilla/io.pl";
49 require "bin/mozilla/common.pl";
50
51 use strict;
52
53 1;
54
55 # end of main
56
57 sub _may_view_or_edit_this_invoice {
58   return 1 if  $::auth->assert('ap_transactions', 1); # may edit all invoices
59   return 0 if !$::form->{id};                         # creating new invoices isn't allowed without invoice_edit
60   return 0 if !$::form->{globalproject_id};           # existing records without a project ID are not allowed
61   return SL::DB::Project->new(id => $::form->{globalproject_id})->load->may_employee_view_project_invoices(SL::DB::Manager::Employee->current);
62 }
63
64 sub _assert_access {
65   my $cache = $::request->cache('ap.pl::_assert_access');
66
67   $cache->{_may_view_or_edit_this_invoice} = _may_view_or_edit_this_invoice()                              if !exists $cache->{_may_view_or_edit_this_invoice};
68   $::form->show_generic_error($::locale->text("You do not have the permissions to access this function.")) if !       $cache->{_may_view_or_edit_this_invoice};
69 }
70
71 sub add {
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   if (!$::instance_conf->get_allow_new_purchase_invoice) {
80     $::form->show_generic_error($::locale->text("You do not have the permissions to access this function."));
81   }
82
83   $form->{show_details} = $::myconfig{show_form_details};
84
85   $form->{title} = $locale->text('Record Vendor Invoice');
86
87   &invoice_links;
88   &prepare_invoice;
89   &display_form;
90
91   $main::lxdebug->leave_sub();
92 }
93
94 sub edit {
95   $main::lxdebug->enter_sub();
96
97   # Delay access check to after the invoice's been loaded in
98   # "create_links" so that project-specific invoice rights can be
99   # evaluated.
100
101   my $form     = $main::form;
102   my $locale   = $main::locale;
103
104   $form->{show_details} = $::myconfig{show_form_details};
105
106   # show history button
107   $form->{javascript} = qq|<script type=text/javascript src=js/show_history.js></script>|;
108   #/show hhistory button
109
110   $form->{title} = $locale->text('Edit Vendor Invoice');
111
112   &invoice_links;
113   &prepare_invoice;
114   &display_form;
115
116   $main::lxdebug->leave_sub();
117 }
118
119 sub invoice_links {
120   $main::lxdebug->enter_sub();
121
122   # Delay access check to after the invoice's been loaded so that
123   # project-specific invoice rights can be evaluated.
124
125   my $form     = $main::form;
126   my %myconfig = %main::myconfig;
127
128   $form->{vc} = 'vendor';
129
130   # create links
131   $form->create_links("AP", \%myconfig, "vendor");
132
133   _assert_access();
134
135   $form->backup_vars(qw(payment_id language_id taxzone_id
136                         currency delivery_term_id intnotes cp_id));
137
138   IR->get_vendor(\%myconfig, \%$form);
139   IR->retrieve_invoice(\%myconfig, \%$form);
140
141   $form->restore_vars(qw(payment_id language_id taxzone_id
142                          currency delivery_term_id intnotes cp_id));
143
144   my @curr = $form->get_all_currencies();
145   map { $form->{selectcurrency} .= "<option>$_\n" } @curr;
146
147   # forex
148   $form->{forex} = $form->{exchangerate};
149   my $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
150
151   foreach my $key (keys %{ $form->{AP_links} }) {
152
153     foreach my $ref (@{ $form->{AP_links}{$key} }) {
154       $form->{"select$key"} .= "<option>$ref->{accno}--$ref->{description}</option>";
155     }
156
157     next unless $form->{acc_trans}{$key};
158
159     if ($key eq "AP_paid") {
160       for my $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
161         $form->{"AP_paid_$i"} =
162           "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
163
164         $form->{"acc_trans_id_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
165         # reverse paid
166         $form->{"paid_$i"}     = $form->{acc_trans}{$key}->[$i - 1]->{amount};
167         $form->{"datepaid_$i"} =
168           $form->{acc_trans}{$key}->[$i - 1]->{transdate};
169         $form->{"gldate_$i"}   = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
170         $form->{"forex_$i"} = $form->{"exchangerate_$i"} =
171           $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
172         $form->{"source_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{source};
173         $form->{"memo_$i"}   = $form->{acc_trans}{$key}->[$i - 1]->{memo};
174
175         $form->{paidaccounts} = $i;
176       }
177     } else {
178       $form->{$key} =
179         "$form->{acc_trans}{$key}->[0]->{accno}--$form->{acc_trans}{$key}->[0]->{description}";
180     }
181
182   }
183
184   $form->{paidaccounts} = 1 unless (exists $form->{paidaccounts});
185
186   $form->{AP} = $form->{AP_1} unless $form->{id};
187
188   $form->{locked} =
189     ($form->datetonum($form->{invdate}, \%myconfig) <=
190      $form->datetonum($form->{closedto}, \%myconfig));
191
192   $main::lxdebug->leave_sub();
193 }
194
195 sub prepare_invoice {
196   $main::lxdebug->enter_sub();
197
198   _assert_access();
199
200   my $form     = $main::form;
201   my %myconfig = %main::myconfig;
202
203   $form->{type}     = "purchase_invoice";
204
205   if ($form->{id}) {
206
207     map { $form->{$_} =~ s/\"/&quot;/g } qw(invnumber ordnumber quonumber);
208
209     my $i = 0;
210     foreach my $ref (@{ $form->{invoice_details} }) {
211       $i++;
212       map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
213       # übernommen aus is.pl Fix für Bug 1642. Nebenwirkungen? jb 12.5.2011
214       # getestet: Lieferantenauftrag -> Rechnung i.O.
215       #           Lieferantenauftrag -> Lieferschein -> Rechnung i.O.
216       # Werte: 20% (Lieferantenrabatt), 12,4% individuell und 0,4 individuell s.a.
217       # Screenshot zu Bug 1642
218       $form->{"discount_$i"}   = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100);
219
220       my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
221       $dec           = length $dec;
222       my $decimalplaces = ($dec > 2) ? $dec : 2;
223
224       $form->{"sellprice_$i"} =
225         $form->format_amount(\%myconfig, $form->{"sellprice_$i"},
226                              $decimalplaces);
227
228       (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
229       $dec_qty = length $dec_qty;
230
231       $form->{"qty_$i"} =
232         $form->format_amount(\%myconfig, ($form->{"qty_$i"} * -1), $dec_qty);
233
234       $form->{rowcount} = $i;
235     }
236   }
237
238   $main::lxdebug->leave_sub();
239 }
240
241 sub setup_ir_action_bar {
242   my $form                    = $::form;
243   my $change_never            = $::instance_conf->get_ir_changeable == 0;
244   my $change_on_same_day_only = $::instance_conf->get_ir_changeable == 2 && ($form->current_date(\%::myconfig) ne $form->{gldate});
245   my $has_storno              = ($::form->{storno} && !$::form->{storno_id});
246   my $payments_balanced       = ($::form->{oldtotalpaid} == 0);
247   my $may_edit_create         = $::auth->assert('vendor_invoice_edit', 1);
248
249   my $has_sepa_exports;
250   if ($form->{id}) {
251     my $invoice = SL::DB::Manager::PurchaseInvoice->find_by(id => $form->{id});
252     $has_sepa_exports = 1 if ($invoice->find_sepa_export_items()->[0]);
253   }
254
255   my $is_linked_bank_transaction;
256   if ($::form->{id}
257       && SL::DB::Default->get->payments_changeable != 0
258       && SL::DB::Manager::BankTransactionAccTrans->find_by(ap_id => $::form->{id})) {
259
260     $is_linked_bank_transaction = 1;
261   }
262   for my $bar ($::request->layout->get('actionbar')) {
263     $bar->add(
264       action => [
265         t8('Update'),
266         submit    => [ '#form', { action => "update" } ],
267         id        => 'update_button',
268         accesskey => 'enter',
269         disabled  => !$may_edit_create ? t8('You must not change this invoice.') : undef,
270       ],
271
272       combobox => [
273         action => [
274           t8('Post'),
275           submit   => [ '#form', { action => "post" } ],
276           checks   => [ 'kivi.validate_form' ],
277           checks   => [ 'kivi.validate_form', 'kivi.AP.check_fields_before_posting', 'kivi.AP.check_duplicate_invnumber' ],
278           disabled => !$may_edit_create                         ? t8('You must not change this invoice.')
279                     : $form->{locked}                           ? t8('The billing period has already been locked.')
280                     : $form->{storno}                           ? t8('A canceled invoice cannot be posted.')
281                     : ($form->{id} && $change_never)            ? t8('Changing invoices has been disabled in the configuration.')
282                     : ($form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
283                     : $is_linked_bank_transaction               ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
284                     :                                             undef,
285         ],
286         action => [
287           t8('Post Payment'),
288           submit   => [ '#form', { action => "post_payment" } ],
289           checks   => [ 'kivi.validate_form' ],
290           disabled => !$may_edit_create           ? t8('You must not change this invoice.')
291                     : !$form->{id}                ? t8('This invoice has not been posted yet.')
292                     : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
293                     :                               undef,
294         ],
295         action => [
296           t8('Mark as paid'),
297           submit   => [ '#form', { action => "mark_as_paid" } ],
298           checks   => [ 'kivi.validate_form' ],
299           confirm  => t8('This will remove the invoice from showing as unpaid even if the unpaid amount does not match the amount. Proceed?'),
300           disabled => !$may_edit_create ? t8('You must not change this invoice.')
301                     : !$form->{id}      ? t8('This invoice has not been posted yet.')
302                     :                     undef,
303           only_if  => $::instance_conf->get_ir_show_mark_as_paid,
304         ],
305       ], # end of combobox "Post"
306
307       combobox => [
308         action => [ t8('Storno'),
309           submit   => [ '#form', { action => "storno" } ],
310           checks   => [ 'kivi.validate_form' ],
311           confirm  => t8('Do you really want to cancel this invoice?'),
312           disabled => !$may_edit_create   ? t8('You must not change this invoice.')
313                     : !$form->{id}        ? t8('This invoice has not been posted yet.')
314                     : $has_sepa_exports   ? t8('This invoice has been linked with a sepa export, undo this first.')
315                     : !$payments_balanced ? t8('Cancelling is disallowed. Either undo or balance the current payments until the open amount matches the invoice amount')
316                     : undef,
317         ],
318         action => [ t8('Delete'),
319           submit   => [ '#form', { action => "delete" } ],
320           checks   => [ 'kivi.validate_form' ],
321           confirm  => t8('Do you really want to delete this object?'),
322           disabled => !$may_edit_create           ? t8('You must not change this invoice.')
323                     : !$form->{id}                ? t8('This invoice has not been posted yet.')
324                     : $form->{locked}             ? t8('The billing period has already been locked.')
325                     : $change_never               ? t8('Changing invoices has been disabled in the configuration.')
326                     : $change_on_same_day_only    ? t8('Invoices can only be changed on the day they are posted.')
327                     : $has_sepa_exports           ? t8('This invoice has been linked with a sepa export, undo this first.')
328                     : $has_storno                 ? t8('Can only delete the "Storno zu" part of the cancellation pair.')
329                     : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
330                     :                            undef,
331         ],
332       ], # end of combobox "Storno"
333
334       'separator',
335
336       combobox => [
337         action => [ t8('Workflow') ],
338         action => [
339           t8('Use As New'),
340           submit   => [ '#form', { action => "use_as_new" } ],
341           checks   => [ 'kivi.validate_form' ],
342           disabled => !$may_edit_create ? t8('You must not change this invoice.')
343                     : !$form->{id}      ? t8('This invoice has not been posted yet.')
344                     :                     undef,
345         ],
346        ], # end of combobox "Workflow"
347
348       combobox => [
349         action => [ t8('more') ],
350         action => [
351           t8('History'),
352           call     => [ 'set_history_window', $::form->{id} * 1, 'glid' ],
353           disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
354         ],
355         action => [
356           t8('Follow-Up'),
357           call     => [ 'follow_up_window' ],
358           disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
359         ],
360         action => [
361           t8('Drafts'),
362           call     => [ 'kivi.Draft.popup', 'ir', 'invoice', $::form->{draft_id}, $::form->{draft_description} ],
363           disabled => !$may_edit_create ? t8('You must not change this invoice.')
364                     : $form->{id}       ? t8('This invoice has already been posted.')
365                     : $form->{locked}   ? t8('The billing period has already been locked.')
366                     :                     undef,
367         ],
368       ], # end of combobox "more"
369     );
370   }
371   $::request->layout->add_javascripts('kivi.Validator.js', 'kivi.AP.js');
372
373 }
374
375 sub form_header {
376   $main::lxdebug->enter_sub();
377
378   _assert_access();
379
380   my $form     = $main::form;
381   my %myconfig = %main::myconfig;
382   my $locale   = $main::locale;
383   my $cgi      = $::request->{cgi};
384
385   my %TMPL_VAR = ();
386   my @custom_hiddens;
387
388   $TMPL_VAR{invoice_obj} = SL::DB::PurchaseInvoice->load_cached($form->{id}) if $form->{id};
389   $TMPL_VAR{vendor_obj}  = SL::DB::Vendor->load_cached($form->{vendor_id})   if $form->{vendor_id};
390   my $current_employee   = SL::DB::Manager::Employee->current;
391   $form->{employee_id}   = $form->{old_employee_id} if $form->{old_employee_id};
392   $form->{salesman_id}   = $form->{old_salesman_id} if $form->{old_salesman_id};
393   $form->{employee_id} ||= $current_employee->id;
394   $form->{salesman_id} ||= $current_employee->id;
395
396   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
397
398   my @old_project_ids     = uniq grep { $_ } map { $_ * 1 } ($form->{"globalproject_id"}, map { $form->{"project_id_$_"} } 1..$form->{"rowcount"});
399   my @conditions          = @old_project_ids ? (id => \@old_project_ids) : ();
400   $TMPL_VAR{ALL_PROJECTS} = SL::DB::Manager::Project->get_all_sorted(query => [ or => [ active => 1, @conditions ]]);
401   $form->{ALL_PROJECTS}   = $TMPL_VAR{ALL_PROJECTS}; # make projects available for second row drop-down in io.pl
402
403   $form->get_lists("taxzones"      => ($form->{id} ? "ALL_TAXZONES" : "ALL_ACTIVE_TAXZONES"),
404                    "currencies"    => "ALL_CURRENCIES",
405                    "price_factors" => "ALL_PRICE_FACTORS");
406
407   $TMPL_VAR{ALL_DEPARTMENTS}       = SL::DB::Manager::Department->get_all_sorted;
408   $TMPL_VAR{ALL_EMPLOYEES}         = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{employee_id},  deleted => 0 ] ]);
409   $TMPL_VAR{ALL_CONTACTS}          = SL::DB::Manager::Contact->get_all_sorted(query => [
410     or => [
411       cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
412       and      => [
413         cp_cv_id => undef,
414         cp_id    => $::form->{cp_id} * 1
415       ]
416     ]
417   ]);
418
419   # currencies and exchangerate
420   my @values = map { $_       } @{ $form->{ALL_CURRENCIES} };
421   my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
422   $form->{currency}            = $form->{defaultcurrency} unless $form->{currency};
423   # show_exchangerate is also later needed in another template
424   $form->{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
425   $TMPL_VAR{currencies}        = NTI($cgi->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
426                                                       '-values' => \@values, '-labels' => \%labels,
427                                                       '-onchange' => "document.getElementById('update_button').click();"
428                                      )) if scalar @values;
429   push @custom_hiddens, "forex";
430   push @custom_hiddens, "exchangerate" if $form->{forex};
431
432   $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
433   $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
434
435 # set option selected
436   foreach my $item (qw(AP)) {
437     $form->{"select$item"} =~ s/ selected//;
438     $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
439   }
440
441   $TMPL_VAR{is_format_html}      = $form->{format} eq 'html';
442   $TMPL_VAR{dateformat}          = $myconfig{dateformat};
443   $TMPL_VAR{numberformat}        = $myconfig{numberformat};
444
445   # hiddens
446   $TMPL_VAR{HIDDENS} = [qw(
447     id type queued printed emailed title vc discount
448     title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
449     max_dunning_level dunning_amount
450     shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptogln shiptocontact shiptophone shiptofax
451     shiptoemail shiptodepartment_1 shiptodepartment_2 message email subject cc bcc taxaccounts cursor_fokus
452     convert_from_do_ids convert_from_oe_ids convert_from_ap_ids show_details gldate useasnew
453   ), @custom_hiddens,
454   map { $_.'_rate', $_.'_description', $_.'_taxnumber', $_.'_tax_id' } split / /, $form->{taxaccounts}];
455
456   $TMPL_VAR{payment_terms_obj} = get_payment_terms_for_invoice();
457   $form->{duedate}             = $TMPL_VAR{payment_terms_obj}->calc_date(reference_date => $form->{invdate}, due_date => $form->{duedate})->to_kivitendo if $TMPL_VAR{payment_terms_obj};
458
459   $::request->{layout}->use_javascript(map { "${_}.js" } qw(kivi.Draft kivi.File kivi.SalesPurchase kivi.Part kivi.CustomerVendor kivi.Validator ckeditor/ckeditor ckeditor/adapters/jquery kivi.io autocomplete_project client_js));
460
461   setup_ir_action_bar();
462
463   $form->header();
464
465   print $form->parse_html_template("ir/form_header", \%TMPL_VAR);
466
467   $main::lxdebug->leave_sub();
468 }
469
470 sub _sort_payments {
471   my @fields   = qw(acc_trans_id gldate datepaid source memo paid AP_paid);
472   my @payments =
473     grep { $_->{paid} != 0 }
474     map  {
475       my $idx = $_;
476       +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
477     } (1..$::form->{paidaccounts});
478
479   @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
480
481   $::form->{paidaccounts} = max scalar(@payments), 1;
482
483   foreach my $idx (1 .. scalar(@payments)) {
484     my $payment = $payments[$idx - 1];
485     $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
486   }
487 }
488
489 sub form_footer {
490   $main::lxdebug->enter_sub();
491
492   _assert_access();
493
494   my $form     = $main::form;
495   my %myconfig = %main::myconfig;
496   my $locale   = $main::locale;
497
498   $form->{invtotal}    = $form->{invsubtotal};
499   $form->{oldinvtotal} = $form->{invtotal};
500
501   # tax, total and subtotal calculations
502   my ($tax, $subtotal);
503   $form->{taxaccounts_array} = [ split / /, $form->{taxaccounts} ];
504
505   foreach my $item (@{ $form->{taxaccounts_array} }) {
506     if ($form->{"${item}_base"}) {
507       if ($form->{taxincluded}) {
508         $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
509                                                                                  / (1 + $form->{"${item}_rate"})), 2);
510         $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
511       } else {
512         $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
513         $form->{invtotal} += $form->{"${item}_total"};
514       }
515     }
516   }
517
518   # follow ups
519   if ($form->{id}) {
520     $form->{follow_ups}            = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1) || [];
521     $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
522   }
523
524   # payments
525   _sort_payments();
526
527   my $totalpaid = 0;
528   $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
529   $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
530
531   # Standard Konto für Umlaufvermögen
532   my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
533
534   for my $i (1 .. $form->{paidaccounts}) {
535     $form->{"changeable_$i"} = 1;
536     if (SL::DB::Default->get->payments_changeable == 0) {
537       # never
538       $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
539     } elsif (SL::DB::Default->get->payments_changeable == 2) {
540       # on the same day
541       $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
542                                   ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
543     }
544
545     $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
546       if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
547
548     #deaktivieren von Zahlungen ausserhalb der Bücherkontrolle
549     if ($form->date_closed($form->{"gldate_$i"})) {
550       $form->{"changeable_$i"} = 0;
551     }
552
553     $form->{"selectAP_paid_$i"} = $form->{selectAP_paid};
554     if (!$form->{"AP_paid_$i"}) {
555       $form->{"selectAP_paid_$i"} =~ s/option>$accno_arap--(.*?)>/option selected>$accno_arap--$1>/;
556     } else {
557       $form->{"selectAP_paid_$i"} =~ s/option>\Q$form->{"AP_paid_$i"}\E/option selected>$form->{"AP_paid_$i"}/;
558     }
559
560     $totalpaid += $form->{"paid_$i"};
561   }
562
563   $form->{ALL_DELIVERY_TERMS} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
564
565   print $form->parse_html_template('ir/form_footer', {
566     totalpaid           => $totalpaid,
567     paid_missing        => $form->{invtotal} - $totalpaid,
568     show_storno         => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ap") && !$totalpaid,
569     show_delete         => ($::instance_conf->get_ir_changeable == 2)
570                              ? ($form->current_date(\%myconfig) eq $form->{gldate})
571                              : ($::instance_conf->get_ir_changeable == 1),
572     today               => DateTime->today,
573   });
574 ##print $form->parse_html_template('ir/_payments'); # parser
575 ##print $form->parse_html_template('webdav/_list'); # parser
576
577   $main::lxdebug->leave_sub();
578 }
579
580 sub mark_as_paid {
581   $::auth->assert('vendor_invoice_edit');
582
583   SL::DB::PurchaseInvoice->new(id => $::form->{id})->load->mark_as_paid;
584
585   $::form->redirect($::locale->text("Marked as paid"));
586 }
587
588 sub show_draft {
589   update();
590 }
591
592 sub update {
593   $main::lxdebug->enter_sub();
594
595   my $form     = $main::form;
596   my %myconfig = %main::myconfig;
597
598   $main::auth->assert('vendor_invoice_edit');
599
600   if (($form->{previous_vendor_id} || $form->{vendor_id}) != $form->{vendor_id}) {
601     IR->get_vendor(\%myconfig, $form);
602   }
603
604   if (!$form->{forex}) {        # read exchangerate from input field (not hidden)
605     $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate});
606   }
607   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'sell');
608   $form->{exchangerate} = $form->{forex} if $form->{forex};
609
610   for my $i (1 .. $form->{paidaccounts}) {
611     next unless $form->{"paid_$i"};
612     map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
613     $form->{"forex_$i"}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
614     $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
615   }
616
617   my $i            = $form->{rowcount};
618   my $exchangerate = ($form->{exchangerate} * 1) || 1;
619
620   if (   ($form->{"partnumber_$i"} eq "")
621       && ($form->{"description_$i"} eq "")
622       && ($form->{"partsgroup_$i"} eq "")) {
623     $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
624     &check_form;
625
626   } else {
627
628     IR->retrieve_item(\%myconfig, \%$form);
629
630     my $rows = scalar @{ $form->{item_list} };
631
632     $form->{"discount_$i"}   = $form->parse_amount(\%myconfig, $form->{"discount_$i"}) / 100.0;
633     $form->{"discount_$i"} ||= $form->{vendor_discount};
634
635     if ($rows) {
636       $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
637       if( !$form->{"qty_$i"} ) {
638         $form->{"qty_$i"} = 1;
639       }
640
641       if ($rows > 1) {
642
643         select_item(mode => 'IR', pre_entered_qty => $form->{"qty_$i"});
644         $::dispatcher->end_request;
645
646       } else {
647
648         # override sellprice if there is one entered
649         my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
650
651         map { $form->{item_list}[$i]{$_} =~ s/\"/&quot;/g } qw(partnumber description unit);
652         map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
653
654         $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
655
656         ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
657         my $dec_qty       = length $1;
658         my $decimalplaces = max 2, $dec_qty;
659
660         if ($sellprice) {
661           $form->{"sellprice_$i"} = $sellprice;
662         } else {
663           my $record        = _make_record();
664           my $price_source  = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
665           my $best_price    = $price_source->best_price;
666           my $best_discount = $price_source->best_discount;
667
668           if ($best_price) {
669             $::form->{"sellprice_$i"}           = $best_price->price;
670             $::form->{"active_price_source_$i"} = $best_price->source;
671           }
672           if ($best_discount) {
673             $::form->{"discount_$i"}               = $best_discount->discount;
674             $::form->{"active_discount_source_$i"} = $best_discount->source;
675           }
676
677           # if there is an exchange rate adjust sellprice
678           $form->{"sellprice_$i"} /= $exchangerate;
679         }
680
681         my $amount                = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"});
682         $form->{creditremaining} -= $amount;
683         $form->{"sellprice_$i"}   = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
684         $form->{"qty_$i"}         = $form->format_amount(\%myconfig, $form->{"qty_$i"},       $dec_qty);
685         $form->{"discount_$i"}    = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
686       }
687
688       &display_form;
689
690     } else {
691
692       # ok, so this is a new part
693       # ask if it is a part or service item
694
695       if (   $form->{"partsgroup_$i"}
696           && ($form->{"partsnumber_$i"} eq "")
697           && ($form->{"description_$i"} eq "")) {
698         $form->{rowcount}--;
699         $form->{"discount_$i"} = "";
700         display_form();
701
702       } else {
703         $form->{"id_$i"}   = 0;
704         new_item();
705       }
706     }
707   }
708   $main::lxdebug->leave_sub();
709 }
710
711 sub storno {
712   $main::lxdebug->enter_sub();
713
714   my $form     = $main::form;
715   my %myconfig = %main::myconfig;
716   my $locale   = $main::locale;
717
718   $main::auth->assert('vendor_invoice_edit');
719
720   if ($form->{storno}) {
721     $form->error($locale->text('Cannot storno storno invoice!'));
722   }
723
724   if (IS->has_storno(\%myconfig, $form, "ap")) {
725     $form->error($locale->text("Invoice has already been storno'd!"));
726   }
727
728   $form->error($locale->text('Cannot post storno for a closed period!'))
729     if ( $form->date_closed($form->{invdate}, \%myconfig));
730
731   my $employee_id = $form->{employee_id};
732   invoice_links();
733   prepare_invoice();
734   relink_accounts();
735
736   # Payments must not be recorded for the new storno invoice.
737   $form->{paidaccounts} = 0;
738   map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
739   # set new ids for storno invoice
740   # set new persistent ids for storno invoice items
741   $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
742
743   # saving the history
744   if(!exists $form->{addition} && $form->{id} ne "") {
745     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
746     $form->{what_done} = "invoice";
747     $form->{addition}  = "CANCELED";
748     $form->save_history;
749   }
750   # /saving the history
751
752   # record link invoice to storno
753   $form->{convert_from_ap_ids} = $form->{id};
754   $form->{storno_id} = $form->{id};
755   $form->{storno} = 1;
756   $form->{id} = "";
757   $form->{invnumber} = "Storno zu " . $form->{invnumber};
758   $form->{rowcount}++;
759   $form->{employee_id} = $employee_id;
760   post();
761   $main::lxdebug->leave_sub();
762
763 }
764
765 sub use_as_new {
766   $main::lxdebug->enter_sub();
767
768   my $form     = $main::form;
769   my %myconfig = %main::myconfig;
770
771   $main::auth->assert('vendor_invoice_edit');
772
773   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);
774   $form->{paidaccounts} = 1;
775   $form->{rowcount}--;
776   $form->{invdate} = $form->current_date(\%myconfig);
777
778   $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
779
780   $form->{useasnew} = 1;
781   &display_form;
782
783   $main::lxdebug->leave_sub();
784 }
785
786 sub post_payment {
787   $main::lxdebug->enter_sub();
788
789   my $form     = $main::form;
790   my %myconfig = %main::myconfig;
791   my $locale   = $main::locale;
792
793   $main::auth->assert('vendor_invoice_edit');
794
795   $form->mtime_ischanged('ap') ;
796   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
797   for my $i (1 .. $form->{paidaccounts}) {
798     if ($form->{"paid_$i"}) {
799       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
800
801       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
802
803       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
804         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
805
806       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
807       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
808       $form->error($locale->text('Cannot post payment for a closed period!'))
809         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
810
811       if ($form->{currency} ne $form->{defaultcurrency}) {
812 #        $form->{"exchangerate_$i"} = $form->{exchangerate} if ($invdate == $datepaid); # invdate isn't set here
813         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
814       }
815     }
816   }
817
818   ($form->{AP})      = split /--/, $form->{AP};
819   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
820   if (IR->post_payment(\%myconfig, \%$form)){
821     if (!exists $form->{addition} && $form->{id} ne "") {
822       # saving the history
823       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
824       $form->{addition}  = "PAYMENT POSTED";
825       $form->{what_done} = "invoice";
826       $form->save_history;
827       # /saving the history
828     }
829
830     $form->redirect($locale->text('Payment posted!'));
831   }
832
833   $form->error($locale->text('Cannot post payment!'));
834
835   $main::lxdebug->leave_sub();
836 }
837
838 sub _max_datepaid {
839   my $form  =  $main::form;
840
841   my @dates = sort { $b->[1] cmp $a->[1] }
842               map  { [ $_, $main::locale->reformat_date(\%main::myconfig, $_, 'yyyy-mm-dd') ] }
843               grep { $_ }
844               map  { $form->{"datepaid_${_}"} }
845               (1..$form->{rowcount});
846
847   return @dates ? $dates[0]->[0] : undef;
848 }
849
850
851 sub post {
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   $form->mtime_ischanged('ap');
861   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
862
863   $form->isblank("invdate",   $locale->text('Invoice Date missing!'));
864   $form->isblank("vendor_id", $locale->text('Vendor missing!'));
865   $form->isblank("invnumber", $locale->text('Invnumber missing!'));
866
867   $form->{invnumber} =~ s/^\s*//g;
868   $form->{invnumber} =~ s/\s*$//g;
869
870   # if the vendor changed get new values
871   if (($form->{previous_vendor_id} || $form->{vendor_id}) != $form->{vendor_id}) {
872     &update;
873     $::dispatcher->end_request;
874   }
875
876   if ($myconfig{mandatory_departments} && !$form->{department_id}) {
877     $form->{saved_message} = $::locale->text('You have to specify a department.');
878     update();
879     exit;
880   }
881
882   remove_emptied_rows();
883   &validate_items;
884
885   my $closedto     = $form->datetonum($form->{closedto}, \%myconfig);
886   my $invdate      = $form->datetonum($form->{invdate},  \%myconfig);
887   my $max_datepaid = _max_datepaid();
888
889   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
890     if ($form->date_max_future($invdate, \%myconfig));
891   $form->error($locale->text('Cannot post invoice for a closed period!'))
892     if ($invdate <= $closedto);
893
894   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
895     if ($form->{currency} ne $form->{defaultcurrency});
896
897   my $i;
898   for $i (1 .. $form->{paidaccounts}) {
899     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
900       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
901
902       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
903
904       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
905         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
906
907       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
908       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
909       $form->error($locale->text('Cannot post payment for a closed period!'))
910         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
911
912       if ($form->{currency} ne $form->{defaultcurrency}) {
913         $form->{"exchangerate_$i"} = $form->{exchangerate}
914           if ($invdate == $datepaid);
915         $form->isblank("exchangerate_$i",
916                        $locale->text('Exchangerate for payment missing!'));
917       }
918     }
919   }
920
921   ($form->{AP})      = split /--/, $form->{AP};
922   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
923   $form->{storno}  ||= 0;
924
925   $form->{id} = 0 if $form->{postasnew};
926
927
928   relink_accounts();
929   if (IR->post_invoice(\%myconfig, \%$form)){
930     # saving the history
931     if(!exists $form->{addition} && $form->{id} ne "") {
932       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
933       $form->{addition}  = "POSTED";
934       $form->{what_done} = 'invoice';
935       $form->save_history;
936     }
937     # /saving the history
938     # I keep the old default / comment for refactorer, pls check instance_conf:
939     #if ($::instance_conf->get_ir_add_doc && $::instance_conf->get_doc_storage) {
940     #  my $add_doc_url = build_std_url("script=ir.pl", 'action=edit', 'id=' . E($form->{id}));
941     #  print $form->redirect_header($add_doc_url);
942     #}
943     $form->{callback} = 'ir.pl?action=edit&id=' . $form->{id};
944     $form->redirect(  $locale->text('Invoice')
945                   . " $form->{invnumber} "
946                   . ", " . $locale->text('ID')
947                   . ': ' . $form->{id} . ' '
948                   . $locale->text('posted!'));
949   }
950   $form->error($locale->text('Cannot post invoice!'));
951
952   $main::lxdebug->leave_sub();
953 }
954
955 sub delete {
956   $main::lxdebug->enter_sub();
957
958   my $form     = $main::form;
959   my $locale   = $main::locale;
960
961   $main::auth->assert('vendor_invoice_edit');
962
963   $form->header;
964   print qq|
965 <form method=post action=$form->{script}>
966 |;
967
968   # delete action variable
969   map { delete $form->{$_} } qw(action header);
970
971   foreach my $key (keys %$form) {
972     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
973     $form->{$key} =~ s/\"/&quot;/g;
974     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
975   }
976
977   print qq|
978 <h2 class=confirm>| . $locale->text('Confirm!') . qq|</h2>
979
980 <h4>|
981     . $locale->text('Are you sure you want to delete Invoice Number')
982     . qq| $form->{invnumber}</h4>
983 <p>
984 <input name=action class=submit type=submit value="|
985     . $locale->text('Yes') . qq|">
986 </form>
987 |;
988
989   $main::lxdebug->leave_sub();
990 }
991
992 sub display_form {
993   $::lxdebug->enter_sub;
994
995   _assert_access();
996
997   relink_accounts();
998
999   my $new_rowcount = $::form->{"rowcount"} * 1 + 1;
1000   $::form->{"project_id_${new_rowcount}"} = $::form->{"globalproject_id"};
1001
1002   $::form->language_payment(\%::myconfig);
1003
1004   Common::webdav_folder($::form);
1005
1006   form_header();
1007   display_row(++$::form->{rowcount});
1008   form_footer();
1009
1010   $::lxdebug->leave_sub;
1011 }
1012
1013 sub yes {
1014   $main::lxdebug->enter_sub();
1015
1016   my $form     = $main::form;
1017   my %myconfig = %main::myconfig;
1018   my $locale   = $main::locale;
1019
1020   $main::auth->assert('vendor_invoice_edit');
1021
1022   if (IR->delete_invoice(\%myconfig, \%$form)) {
1023     # saving the history
1024     if(!exists $form->{addition}) {
1025       $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1026       $form->{addition} = "DELETED";
1027       $form->save_history;
1028     }
1029     # /saving the history
1030     $form->redirect($locale->text('Invoice deleted!'));
1031   }
1032   $form->error($locale->text('Cannot delete invoice!'));
1033
1034   $main::lxdebug->leave_sub();
1035 }
1036
1037 sub get_duedate_vendor {
1038   $::lxdebug->enter_sub;
1039
1040   my $result = IR->get_duedate(
1041     vendor_id => $::form->{vendor_id},
1042     invdate   => $::form->{invdate},
1043     default   => $::form->{old_duedate},
1044   );
1045
1046   print $::form->ajax_response_header, $result;
1047   $::lxdebug->leave_sub;
1048 }