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