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