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