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