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