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