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