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