arap.pl entfernt
[kivitendo-erp.git] / bin / mozilla / is.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 invoicing module
32 #
33 #======================================================================
34
35 use SL::FU;
36 use SL::IS;
37 use SL::OE;
38 use SL::MoreCommon qw(restore_form save_form);
39 use Data::Dumper;
40 use DateTime;
41 use List::MoreUtils qw(uniq);
42 use List::Util qw(max sum);
43 use List::UtilsBy qw(sort_by);
44 use English qw(-no_match_vars);
45
46 use SL::DB::Default;
47 use SL::DB::Customer;
48 use SL::DB::Department;
49 use SL::DB::Invoice;
50 use SL::DB::PaymentTerm;
51
52 require "bin/mozilla/common.pl";
53 require "bin/mozilla/io.pl";
54
55 use strict;
56
57 1;
58
59 # end of main
60
61 sub add {
62   $main::lxdebug->enter_sub();
63
64   my $form     = $main::form;
65   my $locale   = $main::locale;
66
67   $main::auth->assert('invoice_edit');
68
69   $form->{show_details} = $::myconfig{show_form_details};
70
71   if ($form->{type} eq "credit_note") {
72     $form->{title} = $locale->text('Add Credit Note');
73
74     if ($form->{storno}) {
75       $form->{title} = $locale->text('Add Storno Credit Note');
76     }
77   } else {
78     $form->{title} = $locale->text('Add Sales Invoice');
79
80   }
81
82
83   $form->{callback} = "$form->{script}?action=add&type=$form->{type}" unless $form->{callback};
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   my $form     = $main::form;
96   my $locale   = $main::locale;
97
98   $main::auth->assert('invoice_edit');
99
100   $form->{show_details}                = $::myconfig{show_form_details};
101   $form->{taxincluded_changed_by_user} = 1;
102
103   # show history button
104   $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
105
106   my ($language_id, $printer_id);
107   if ($form->{print_and_post}) {
108     $form->{action}   = "print";
109     $form->{resubmit} = 1;
110     $language_id = $form->{language_id};
111     $printer_id = $form->{printer_id};
112   }
113
114   &invoice_links;
115   if ($form->{type} eq "credit_note") {
116     $form->{title} = $locale->text('Edit Credit Note');
117     $form->{title} = $locale->text('Edit Storno Credit Note') if $form->{storno};
118   } else {
119     $form->{title} = $locale->text('Edit Sales Invoice');
120     $form->{title} = $locale->text('Edit Storno Invoice')     if $form->{storno};
121   }
122
123   &prepare_invoice;
124   if ($form->{print_and_post}) {
125     $form->{language_id} = $language_id;
126     $form->{printer_id} = $printer_id;
127   }
128
129   &display_form;
130
131   $main::lxdebug->leave_sub();
132 }
133
134 sub invoice_links {
135   $main::lxdebug->enter_sub();
136
137   my $form     = $main::form;
138   my %myconfig = %main::myconfig;
139
140   $main::auth->assert('invoice_edit');
141
142   $form->{vc} = 'customer';
143
144   # create links
145   $form->create_links("AR", \%myconfig, "customer");
146
147   my $editing = $form->{id};
148
149   $form->backup_vars(qw(payment_id language_id taxzone_id salesman_id
150                         taxincluded currency cp_id intnotes id shipto_id
151                         delivery_term_id));
152
153   IS->get_customer(\%myconfig, \%$form);
154
155   $form->restore_vars(qw(id));
156
157   IS->retrieve_invoice(\%myconfig, \%$form);
158   $form->restore_vars(qw(payment_id language_id taxzone_id currency intnotes
159                          cp_id shipto_id delivery_term_id));
160   $form->restore_vars(qw(taxincluded)) if $form->{id};
161   $form->restore_vars(qw(salesman_id)) if $editing;
162
163   $form->{employee} = "$form->{employee}--$form->{employee_id}";
164
165   # forex
166   $form->{forex} = $form->{exchangerate};
167   my $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
168
169   foreach my $key (keys %{ $form->{AR_links} }) {
170     foreach my $ref (@{ $form->{AR_links}{$key} }) {
171       $form->{"select$key"} .= "<option>$ref->{accno}--$ref->{description}</option>\n";
172     }
173
174     if ($key eq "AR_paid") {
175       next unless $form->{acc_trans}{$key};
176       for my $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
177         $form->{"AR_paid_$i"}      = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
178
179         $form->{"acc_trans_id_$i"}    = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
180         # reverse paid
181         $form->{"paid_$i"}         = $form->{acc_trans}{$key}->[$i - 1]->{amount} * -1;
182         $form->{"datepaid_$i"}     = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
183         $form->{"gldate_$i"}       = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
184         $form->{"exchangerate_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
185         $form->{"forex_$i"}        = $form->{"exchangerate_$i"};
186         $form->{"source_$i"}       = $form->{acc_trans}{$key}->[$i - 1]->{source};
187         $form->{"memo_$i"}         = $form->{acc_trans}{$key}->[$i - 1]->{memo};
188
189         $form->{paidaccounts} = $i;
190       }
191     } else {
192       $form->{$key} = "$form->{acc_trans}{$key}->[0]->{accno}--$form->{acc_trans}{$key}->[0]->{description}";
193     }
194   }
195
196   $form->{paidaccounts} = 1 unless (exists $form->{paidaccounts});
197
198   $form->{AR} = $form->{AR_1} unless $form->{id};
199
200   $form->{locked} = ($form->datetonum($form->{invdate},  \%myconfig)
201                   <= $form->datetonum($form->{closedto}, \%myconfig));
202
203   $main::lxdebug->leave_sub();
204 }
205
206 sub prepare_invoice {
207   $main::lxdebug->enter_sub();
208
209   my $form     = $main::form;
210   my %myconfig = %main::myconfig;
211
212   $main::auth->assert('invoice_edit');
213
214   if ($form->{type} eq "credit_note") {
215     $form->{type}     = "credit_note";
216     $form->{formname} = "credit_note";
217   } else {
218     $form->{type}     = "invoice";
219     $form->{formname} = "invoice";
220   }
221
222   if ($form->{id}) {
223
224     my $i = 0;
225
226     foreach my $ref (@{ $form->{invoice_details} }) {
227       $i++;
228
229       map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
230
231       $form->{"discount_$i"}   = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100);
232       my ($dec)                = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
233       $dec                     = length $dec;
234       my $decimalplaces        = ($dec > 2) ? $dec : 2;
235
236       $form->{"sellprice_$i"}  = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
237       (my $dec_qty)            = ($form->{"qty_$i"} =~ /\.(\d+)/);
238       $dec_qty                 = length $dec_qty;
239
240       $form->{"lastcost_$i"}  = $form->format_amount(\%myconfig, $form->{"lastcost_$i"}, $decimalplaces);
241
242       $form->{"qty_$i"}        = $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
243
244       $form->{"sellprice_pg_$i"} = join ('--', $form->{"sellprice_$i"}, $form->{"pricegroup_id_$i"});
245
246       $form->{rowcount}        = $i;
247
248     }
249   }
250   $main::lxdebug->leave_sub();
251 }
252
253 sub form_header {
254   $main::lxdebug->enter_sub();
255
256   my $form     = $main::form;
257   my %myconfig = %main::myconfig;
258   my $locale   = $main::locale;
259   my $cgi      = $::request->{cgi};
260
261   $main::auth->assert('invoice_edit');
262
263   my %TMPL_VAR = ();
264   my @custom_hiddens;
265
266   $TMPL_VAR{customer_obj} = SL::DB::Customer->load_cached($form->{customer_id}) if $form->{customer_id};
267   $TMPL_VAR{invoice_obj}  = SL::DB::Invoice->load_cached($form->{id})           if $form->{id};
268
269   $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
270   $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
271
272   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
273
274   $form->get_lists("taxzones"      => ($form->{id} ? "ALL_TAXZONES" : "ALL_ACTIVE_TAXZONES"),
275                    "currencies"    => "ALL_CURRENCIES",
276                    "price_factors" => "ALL_PRICE_FACTORS");
277
278   $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
279
280   # Projects
281   my @old_project_ids = uniq grep { $_ } map { $_ * 1 } ($form->{"globalproject_id"}, map { $form->{"project_id_$_"} } 1..$form->{"rowcount"});
282   my @old_ids_cond    = @old_project_ids ? (id => \@old_project_ids) : ();
283   my @customer_cond;
284   if ($::instance_conf->get_customer_projects_only_in_sales) {
285     @customer_cond = (
286       or => [
287         customer_id          => $::form->{customer_id},
288         billable_customer_id => $::form->{customer_id},
289       ]);
290   }
291   my @conditions = (
292     or => [
293       and => [ active => 1, @customer_cond ],
294       @old_ids_cond,
295     ]);
296
297   $TMPL_VAR{ALL_PROJECTS}          = SL::DB::Manager::Project->get_all_sorted(query => \@conditions);
298   $form->{ALL_PROJECTS}            = $TMPL_VAR{ALL_PROJECTS}; # make projects available for second row drop-down in io.pl
299   $TMPL_VAR{ALL_EMPLOYEES}         = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{employee_id},  deleted => 0 ] ]);
300   $TMPL_VAR{ALL_SALESMEN}          = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{salesman_id},  deleted => 0 ] ]);
301   $TMPL_VAR{ALL_SHIPTO}            = SL::DB::Manager::Shipto->get_all_sorted(query => [
302     or => [ trans_id  => $::form->{"$::form->{vc}_id"} * 1, and => [ shipto_id => $::form->{shipto_id} * 1, trans_id => undef ] ]
303   ]);
304   $TMPL_VAR{ALL_CONTACTS}          = SL::DB::Manager::Contact->get_all_sorted(query => [
305     or => [
306       cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
307       and      => [
308         cp_cv_id => undef,
309         cp_id    => $::form->{cp_id} * 1
310       ]
311     ]
312   ]);
313
314   # currencies and exchangerate
315   my @values = map { $_       } @{ $form->{ALL_CURRENCIES} };
316   my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
317   $form->{currency}            = $form->{defaultcurrency} unless $form->{currency};
318   $form->{show_exchangerate}   = $form->{currency} ne $form->{defaultcurrency};
319   $TMPL_VAR{currencies}        = NTI($::request->{cgi}->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
320                                                       '-values' => \@values, '-labels' => \%labels,
321                                                       '-onchange' => "document.getElementById('update_button').click();"
322                                      )) if scalar @values;
323   push @custom_hiddens, "forex";
324   push @custom_hiddens, "exchangerate" if $form->{forex};
325
326   $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
327   $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
328
329 # set option selected
330   foreach my $item (qw(AR)) {
331     $form->{"select$item"} =~ s/ selected//;
332     $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
333   }
334
335   $TMPL_VAR{is_type_credit_note} = $form->{type}   eq "credit_note";
336   $TMPL_VAR{is_format_html}      = $form->{format} eq 'html';
337   $TMPL_VAR{dateformat}          = $myconfig{dateformat};
338   $TMPL_VAR{numberformat}        = $myconfig{numberformat};
339
340   push @custom_hiddens, map { "shiptocvar_" . $_->name } @{ SL::DB::Manager::CustomVariableConfig->get_all(where => [ module => 'ShipTo' ]) };
341
342   # hiddens
343   $TMPL_VAR{HIDDENS} = [qw(
344     id type media format queued printed emailed title vc discount
345     title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
346     max_dunning_level dunning_amount dunning_description
347     shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptogln shiptocontact shiptophone shiptofax
348     shiptoemail shiptodepartment_1 shiptodepartment_2  shiptocp_gender message email subject cc bcc taxaccounts cursor_fokus
349     convert_from_do_ids convert_from_oe_ids convert_from_ar_ids useasnew
350     invoice_id
351     show_details
352   ), @custom_hiddens,
353   map { $_.'_rate', $_.'_description', $_.'_taxnumber' } split / /, $form->{taxaccounts}];
354
355   $::request->{layout}->use_javascript(map { "${_}.js" } qw(kivi.Draft kivi.SalesPurchase ckeditor/ckeditor ckeditor/adapters/jquery kivi.io autocomplete_customer autocomplete_part client_js));
356
357   $TMPL_VAR{payment_terms_obj} = get_payment_terms_for_invoice();
358   $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};
359
360   $form->header();
361
362   print $form->parse_html_template("is/form_header", \%TMPL_VAR);
363
364   $main::lxdebug->leave_sub();
365 }
366
367 sub _sort_payments {
368   my @fields   = qw(acc_trans_id gldate datepaid source memo paid AR_paid);
369   my @payments =
370     grep { $_->{paid} != 0 }
371     map  {
372       my $idx = $_;
373       +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
374     } (1..$::form->{paidaccounts});
375
376   @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
377
378   $::form->{paidaccounts} = max scalar(@payments), 1;
379
380   foreach my $idx (1 .. scalar(@payments)) {
381     my $payment = $payments[$idx - 1];
382     $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
383   }
384 }
385
386 sub form_footer {
387   $main::lxdebug->enter_sub();
388
389   my $form     = $main::form;
390   my %myconfig = %main::myconfig;
391   my $locale   = $main::locale;
392
393   $main::auth->assert('invoice_edit');
394
395   $form->{invtotal}    = $form->{invsubtotal};
396
397   # note rows
398   $form->{rows} = max 2,
399     $form->numtextrows($form->{notes},    26, 8),
400     $form->numtextrows($form->{intnotes}, 35, 8);
401
402
403   # tax, total and subtotal calculations
404   my ($tax, $subtotal);
405   $form->{taxaccounts_array} = [ split(/ /, $form->{taxaccounts}) ];
406
407   if( $form->{customer_id} && !$form->{taxincluded_changed_by_user} ) {
408     my $customer = SL::DB::Customer->load_cached($form->{customer_id});
409     $form->{taxincluded} = defined($customer->taxincluded_checked) ? $customer->taxincluded_checked : $myconfig{taxincluded_checked};
410   }
411
412   foreach my $item (@{ $form->{taxaccounts_array} }) {
413     if ($form->{"${item}_base"}) {
414       if ($form->{taxincluded}) {
415         $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
416                                                                                  / (1 + $form->{"${item}_rate"})), 2);
417         $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
418       } else {
419         $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
420         $form->{invtotal} += $form->{"${item}_total"};
421       }
422     }
423   }
424
425   my $grossamount = $form->{invtotal};
426   $form->{invtotal} = $form->round_amount( $form->{invtotal}, 2, 1 );
427   $form->{rounding} = $form->round_amount(
428     $form->{invtotal} - $form->round_amount($grossamount, 2),
429     2
430   );
431
432   # follow ups
433   if ($form->{id}) {
434     $form->{follow_ups}            = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1) || [];
435     $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
436   }
437
438   # payments
439   _sort_payments();
440
441   my $totalpaid = 0;
442   $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
443   $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
444
445   # Standard Konto für Umlaufvermögen
446   my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
447
448   for my $i (1 .. $form->{paidaccounts}) {
449     $form->{"changeable_$i"} = 1;
450     if (SL::DB::Default->get->payments_changeable == 0) {
451       # never
452       $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
453     } elsif (SL::DB::Default->get->payments_changeable == 2) {
454       # on the same day
455       $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
456                                   ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
457     }
458
459     #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
460     if ($form->date_closed($form->{"gldate_$i"})) {
461       $form->{"changeable_$i"} = 0;
462     }
463
464     $form->{"selectAR_paid_$i"} = $form->{selectAR_paid};
465     if (!$form->{"AR_paid_$i"}) {
466       $form->{"selectAR_paid_$i"} =~ s/option>$accno_arap--(.*?)</option selected>$accno_arap--$1</;
467     } else {
468       $form->{"selectAR_paid_$i"} =~ s/option>\Q$form->{"AR_paid_$i"}\E/option selected>$form->{"AR_paid_$i"}/;
469     }
470
471     $totalpaid += $form->{"paid_$i"};
472   }
473
474   $form->{oldinvtotal} = $form->{invtotal};
475
476   $form->{ALL_DELIVERY_TERMS} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
477
478   print $form->parse_html_template('is/form_footer', {
479     is_type_credit_note => ($form->{type} eq "credit_note"),
480     totalpaid           => $totalpaid,
481     paid_missing        => $form->{invtotal} - $totalpaid,
482     print_options       => print_options(inline => 1),
483     show_storno         => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ar") && !$totalpaid,
484     show_delete         => ($::instance_conf->get_is_changeable == 2)
485                              ? ($form->current_date(\%myconfig) eq $form->{gldate})
486                              : ($::instance_conf->get_is_changeable == 1),
487     today               => DateTime->today,
488   });
489 ##print $form->parse_html_template('is/_payments'); # parser
490 ##print $form->parse_html_template('webdav/_list'); # parser
491
492   $main::lxdebug->leave_sub();
493 }
494
495 sub mark_as_paid {
496   $::auth->assert('invoice_edit');
497
498   SL::DB::Invoice->new(id => $::form->{id})->load->mark_as_paid;
499
500   $::form->redirect($::locale->text("Marked as paid"));
501 }
502
503 sub show_draft {
504   update();
505 }
506
507 sub update {
508   $main::lxdebug->enter_sub();
509
510   my $form     = $main::form;
511   my %myconfig = %main::myconfig;
512
513   $main::auth->assert('invoice_edit');
514
515   my ($recursive_call) = @_;
516
517   $form->{print_and_post} = 0         if $form->{second_run};
518   my $taxincluded         = $form->{taxincluded} ? "checked" : '';
519   $form->{update} = 1;
520
521   if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
522     $::form->{salesman_id} = SL::DB::Manager::Employee->current->id if exists $::form->{salesman_id};
523
524     IS->get_customer(\%myconfig, $form);
525   }
526
527   $form->{taxincluded} ||= $taxincluded;
528
529   if (!$form->{forex}) {        # read exchangerate from input field (not hidden)
530     $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate}) unless $recursive_call;
531   }
532   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
533   $form->{exchangerate} = $form->{forex} if $form->{forex};
534
535   for my $i (1 .. $form->{paidaccounts}) {
536     next unless $form->{"paid_$i"};
537     map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
538     if (!$form->{"forex_$i"}) {   #read exchangerate from input field (not hidden)
539       $form->{exchangerate} = $form->{"exchangerate_$i"};
540     }
541     $form->{"forex_$i"}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
542     $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
543   }
544
545   my $i            = $form->{rowcount};
546   my $exchangerate = $form->{exchangerate} || 1;
547
548   # if last row empty, check the form otherwise retrieve new item
549   if (   ($form->{"partnumber_$i"} eq "")
550       && ($form->{"description_$i"} eq "")
551       && ($form->{"partsgroup_$i"}  eq "")) {
552
553     $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
554     &check_form;
555
556   } else {
557
558     IS->retrieve_item(\%myconfig, \%$form);
559
560     my $rows = scalar @{ $form->{item_list} };
561
562     $form->{"discount_$i"}   = $form->parse_amount(\%myconfig, $form->{"discount_$i"}) / 100.0;
563     $form->{"discount_$i"} ||= $form->{customer_discount};
564
565     if ($rows) {
566       $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
567       if( !$form->{"qty_$i"} ) {
568         $form->{"qty_$i"} = 1;
569       }
570
571       if ($rows > 1) {
572
573         select_item(mode => 'IS', pre_entered_qty => $form->{"qty_$i"});
574         $::dispatcher->end_request;
575
576       } else {
577
578         my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
579
580         map { $form->{item_list}[$i]{$_} =~ s/\"/&quot;/g } qw(partnumber description unit);
581         map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
582
583         $form->{payment_id}    = $form->{"part_payment_id_$i"} if $form->{"part_payment_id_$i"} ne "";
584         $form->{"discount_$i"} = 0                             if $form->{"not_discountable_$i"};
585
586         $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
587
588         ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
589         my $decimalplaces = max 2, length $1;
590
591         if ($sellprice) {
592           $form->{"sellprice_$i"} = $sellprice;
593         } else {
594           my $record        = _make_record();
595           my $price_source  = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
596           my $best_price    = $price_source->best_price;
597           my $best_discount = $price_source->best_discount;
598
599           if ($best_price) {
600             $::form->{"sellprice_$i"}           = $best_price->price;
601             $::form->{"active_price_source_$i"} = $best_price->source;
602           }
603           if ($best_discount) {
604             $::form->{"discount_$i"}               = $best_discount->discount;
605             $::form->{"active_discount_source_$i"} = $best_discount->source;
606           }
607
608           # if there is an exchange rate adjust sellprice
609           $form->{"sellprice_$i"} /= $exchangerate;
610         }
611
612         $form->{"listprice_$i"} /= $exchangerate;
613
614         my $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"});
615         map { $form->{"${_}_base"} = 0 }                                 split / /, $form->{taxaccounts};
616         map { $form->{"${_}_base"} += $amount }                          split / /, $form->{"taxaccounts_$i"};
617         map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{"taxaccounts_$i"} if !$form->{taxincluded};
618
619         $form->{creditremaining} -= $amount;
620
621         map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces) } qw(sellprice lastcost);
622
623         $form->{"qty_$i"}      = $form->format_amount(\%myconfig, $form->{"qty_$i"});
624         $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
625       }
626
627       &display_form;
628
629     } else {
630
631       # ok, so this is a new part
632       # ask if it is a part or service item
633
634       if (   $form->{"partsgroup_$i"}
635           && ($form->{"partsnumber_$i"} eq "")
636           && ($form->{"description_$i"} eq "")) {
637         $form->{rowcount}--;
638         $form->{"discount_$i"} = "";
639         display_form();
640
641       } else {
642         $form->{"id_$i"}   = 0;
643         new_item();
644       }
645     }
646   }
647   $main::lxdebug->leave_sub();
648 }
649
650 sub post_payment {
651   $main::lxdebug->enter_sub();
652
653   my $form     = $main::form;
654   my %myconfig = %main::myconfig;
655   my $locale   = $main::locale;
656
657   $main::auth->assert('invoice_edit');
658
659   $form->mtime_ischanged('ar') ;
660   my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
661
662   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
663   for my $i (1 .. $form->{paidaccounts}) {
664     if ($form->{"paid_$i"}) {
665       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
666
667       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
668
669
670       if ($form->{currency} ne $form->{defaultcurrency}) {
671         $form->{"exchangerate_$i"} = $form->{exchangerate}
672           if ($invdate == $datepaid);
673         $form->isblank("exchangerate_$i",
674                        $locale->text('Exchangerate for payment missing!'));
675       }
676       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
677         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
678
679       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
680       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
681       $form->error($locale->text('Cannot post payment for a closed period!'))
682         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
683     }
684   }
685
686   ($form->{AR})      = split /--/, $form->{AR};
687   ($form->{AR_paid}) = split /--/, $form->{AR_paid};
688   relink_accounts();
689   if ( IS->post_payment(\%myconfig, \%$form) ) {
690     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
691     $form->{what_done} = 'invoice';
692     $form->{addition}  = "PAYMENT POSTED";
693     $form->save_history;
694     $form->redirect($locale->text('Payment posted!'))
695   } else {
696    $form->error($locale->text('Cannot post payment!'));
697   };
698
699   $main::lxdebug->leave_sub();
700 }
701
702 sub post {
703   $main::lxdebug->enter_sub();
704
705   my $form     = $main::form;
706   my %myconfig = %main::myconfig;
707   my $locale   = $main::locale;
708
709   $main::auth->assert('invoice_edit');
710   $form->mtime_ischanged('ar');
711
712   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
713   $form->isblank("invdate",  $locale->text('Invoice Date missing!'));
714   $form->isblank("customer_id", $locale->text('Customer missing!'));
715   $form->error($locale->text('Cannot post invoice for a closed period!'))
716         if ($form->date_closed($form->{"invdate"}, \%myconfig));
717
718   $form->{invnumber} =~ s/^\s*//g;
719   $form->{invnumber} =~ s/\s*$//g;
720
721   # if oldcustomer ne customer redo form
722   if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
723     &update;
724     $::dispatcher->end_request;
725   }
726
727   if ($myconfig{mandatory_departments} && !$form->{department_id}) {
728     $form->{saved_message} = $::locale->text('You have to specify a department.');
729     update();
730     exit;
731   }
732
733   if ($form->{second_run}) {
734     $form->{print_and_post} = 0;
735   }
736
737   remove_emptied_rows();
738   &validate_items;
739
740   my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
741   my $invdate  = $form->datetonum($form->{invdate},  \%myconfig);
742
743   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
744     if ($form->date_max_future($invdate, \%myconfig));
745   $form->error($locale->text('Cannot post invoice for a closed period!'))
746     if ($invdate <= $closedto);
747
748   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
749     if ($form->{currency} ne $form->{defaultcurrency});
750
751   for my $i (1 .. $form->{paidaccounts}) {
752     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
753       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
754
755       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
756
757       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
758         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
759
760       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
761       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
762       $form->error($locale->text('Cannot post payment for a closed period!'))
763         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
764
765       if ($form->{currency} ne $form->{defaultcurrency}) {
766         $form->{"exchangerate_$i"} = $form->{exchangerate}
767           if ($invdate == $datepaid);
768         $form->isblank("exchangerate_$i",
769                        $locale->text('Exchangerate for payment missing!'));
770       }
771     }
772   }
773
774   ($form->{AR})        = split /--/, $form->{AR};
775   ($form->{AR_paid})   = split /--/, $form->{AR_paid};
776   $form->{storno}    ||= 0;
777
778   $form->{label} = $form->{type} eq 'credit_note' ? $locale->text('Credit Note') : $locale->text('Invoice');
779
780   $form->{id} = 0 if $form->{postasnew};
781
782   # get new invnumber in sequence if no invnumber is given or if posasnew was requested
783   if ($form->{postasnew}) {
784     if ($form->{type} eq "credit_note") {
785       undef($form->{cnnumber});
786     } else {
787       undef($form->{invnumber});
788     }
789   }
790
791   relink_accounts();
792
793   my $terms        = get_payment_terms_for_invoice();
794   $form->{duedate} = $terms->calc_date(reference_date => $form->{invdate}, due_date => $form->{due_due})->to_kivitendo if $terms;
795
796   # If transfer_out is requested, get rose db handle and do post and
797   # transfer out in one transaction. Otherwise just post the invoice.
798   if ($::instance_conf->get_is_transfer_out && $form->{type} ne 'credit_note' && !$form->{storno}) {
799     require SL::DB::Inventory;
800     my $rose_db = SL::DB::Inventory->new->db;
801     my @errors;
802
803     if (!$rose_db->with_transaction(sub {
804       if (!eval {
805         if (!IS->post_invoice(\%myconfig, \%$form, $rose_db->dbh)) {
806           push @errors, $locale->text('Cannot post invoice!');
807           die 'posting error';
808         }
809         my $err = IS->transfer_out(\%$form, $rose_db->dbh);
810         if (@{ $err }) {
811           push @errors, @{ $err };
812           die 'transfer error';
813         }
814
815         1;
816       }) {
817         push @errors, $EVAL_ERROR;
818         die 'transaction error';
819       }
820
821       1;
822     })) {
823       push @errors, $rose_db->error;
824       $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
825     }
826   } else {
827     if (!IS->post_invoice(\%myconfig, \%$form)) {
828       $form->error($locale->text('Cannot post invoice!'));
829     }
830   }
831
832   if(!exists $form->{addition}) {
833     $form->{snumbers}  =  'invnumber' .'_'. $form->{invnumber}; # ($form->{type} eq 'credit_note' ? 'cnnumber' : 'invnumber') .'_'. $form->{invnumber};
834     $form->{what_done} = 'invoice';
835     $form->{addition}  = $form->{print_and_post} ? "PRINTED AND POSTED" :
836                          $form->{storno}         ? "STORNO"             :
837                                                    "POSTED";
838     $form->save_history;
839   }
840
841   if (!$form->{no_redirect_after_post}) {
842     $form->{action} = 'edit';
843     $form->{script} = 'is.pl';
844     $form->{saved_message} = $form->{label} . " $form->{invnumber} " . $locale->text('posted!');
845     $form->{callback} = build_std_url(qw(action edit id callback saved_message));
846     $form->redirect;
847   }
848
849   $main::lxdebug->leave_sub();
850 }
851
852 sub print_and_post {
853   $main::lxdebug->enter_sub();
854
855   my $form     = $main::form;
856
857   $main::auth->assert('invoice_edit');
858
859   my $old_form                    = Form->new;
860   $form->{no_redirect_after_post} = 1;
861   $form->{print_and_post}         = 1;
862   &post();
863
864   &edit();
865   $main::lxdebug->leave_sub();
866
867 }
868
869 sub use_as_new {
870   $main::lxdebug->enter_sub();
871
872   my $form     = $main::form;
873   my %myconfig = %main::myconfig;
874
875   $main::auth->assert('invoice_edit');
876
877   delete @{ $form }{qw(printed emailed queued invnumber invdate exchangerate forex deliverydate id datepaid_1 gldate_1 acc_trans_id_1 source_1 memo_1 paid_1 exchangerate_1 AP_paid_1 storno locked)};
878   $form->{rowcount}--;
879   $form->{paidaccounts} = 1;
880   $form->{invdate}      = $form->current_date(\%myconfig);
881   my $terms             = get_payment_terms_for_invoice();
882   $form->{duedate}      = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
883   $form->{employee_id}  = SL::DB::Manager::Employee->current->id;
884   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
885   $form->{exchangerate} = $form->{forex} if $form->{forex};
886
887   $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
888
889   $form->{useasnew} = 1;
890   &display_form;
891
892   $main::lxdebug->leave_sub();
893 }
894
895 sub storno {
896   $main::lxdebug->enter_sub();
897
898   my $form     = $main::form;
899   my %myconfig = %main::myconfig;
900   my $locale   = $main::locale;
901
902   $main::auth->assert('invoice_edit');
903
904   if ($form->{storno}) {
905     $form->error($locale->text('Cannot storno storno invoice!'));
906   }
907
908   if (IS->has_storno(\%myconfig, $form, "ar")) {
909     $form->error($locale->text("Invoice has already been storno'd!"));
910   }
911   if ($form->datetonum($form->{invdate},  \%myconfig) <= $form->datetonum($form->{closedto}, \%myconfig)) {
912     $form->error($locale->text('Cannot storno invoice for a closed period!'));
913   }
914
915   # save the history of invoice being stornoed
916   $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
917   $form->{what_done} = 'invoice';
918   $form->{addition}  = "STORNO";
919   $form->save_history;
920
921   map({ my $key = $_; delete($form->{$key}) unless (grep({ $key eq $_ } qw(id login password type))); } keys(%{ $form }));
922
923   invoice_links();
924   prepare_invoice();
925   relink_accounts();
926
927   # Payments must not be recorded for the new storno invoice.
928   $form->{paidaccounts} = 0;
929   map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
930
931   # record link invoice to storno
932   $form->{convert_from_ar_ids} = $form->{id};
933   $form->{storno_id} = $form->{id};
934   $form->{storno} = 1;
935   $form->{id} = "";
936   $form->{invnumber} = "Storno zu " . $form->{invnumber};
937   $form->{invdate}   = DateTime->today->to_lxoffice;
938   $form->{rowcount}++;
939   # set new ids for storno invoice
940   # set new persistent ids for storno invoice items
941   $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
942
943   post();
944   $main::lxdebug->leave_sub();
945 }
946
947 sub preview {
948   $main::lxdebug->enter_sub();
949
950   my $form     = $main::form;
951
952   $main::auth->assert('invoice_edit');
953
954   $form->{preview} = 1;
955   my $old_form = Form->new;
956   for (keys %$form) { $old_form->{$_} = $form->{$_} }
957
958   &print_form($old_form);
959   $main::lxdebug->leave_sub();
960
961 }
962
963 sub credit_note {
964   $main::lxdebug->enter_sub();
965
966   my $form     = $main::form;
967   my %myconfig = %main::myconfig;
968   my $locale   = $main::locale;
969
970   $main::auth->assert('invoice_edit');
971
972   $form->{transdate} = $form->{invdate} = $form->current_date(\%myconfig);
973   $form->{duedate} =
974     $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
975
976   $form->{convert_from_ar_ids} = $form->{id};
977   $form->{id}     = '';
978   $form->{rowcount}--;
979
980
981   $form->{title}  = $locale->text('Add Credit Note');
982   $form->{script} = 'is.pl';
983
984   # Bei Gutschriften bezug zur Rechnungsnummer
985   $form->{invnumber_for_credit_note} = $form->{invnumber};
986   # bo creates the id, reset it
987   map { delete $form->{$_} }
988     qw(id invnumber subject message cc bcc printed emailed queued);
989   $form->{ $form->{vc} } =~ s/--.*//g;
990   $form->{type} = "credit_note";
991
992
993   map { $form->{"select$_"} = "" } ($form->{vc}, 'currency');
994
995 #  map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
996 #    qw(creditlimit creditremaining);
997
998   # set new persistent ids for credit note and link previous invoice id
999   $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1000
1001   my $currency = $form->{currency};
1002   &invoice_links;
1003
1004   $form->{currency}     = $currency;
1005   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1006   $form->{exchangerate} = $form->{forex} || '';
1007
1008   $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
1009
1010   # bei Gutschriften werden Zahlungseingänge aus Rechnung nicht übernommen
1011   for my $i (1 .. $form->{paidaccounts}) {
1012     delete $form->{"paid_$i"};
1013     delete $form->{"source_$i"};
1014     delete $form->{"memo_$i"};
1015     delete $form->{"datepaid_$i"};
1016     delete $form->{"gldate_$i"};
1017     delete $form->{"acc_trans_id_$i"};
1018     delete $form->{"AR_paid_$i"};
1019   };
1020   $form->{paidaccounts} = 1;
1021
1022   &prepare_invoice;
1023
1024
1025   &display_form;
1026
1027   $main::lxdebug->leave_sub();
1028 }
1029
1030 sub display_form {
1031   $::lxdebug->enter_sub;
1032
1033   $::auth->assert('invoice_edit');
1034
1035   relink_accounts();
1036
1037   my $new_rowcount = $::form->{"rowcount"} * 1 + 1;
1038   $::form->{"project_id_${new_rowcount}"} = $::form->{"globalproject_id"};
1039
1040   $::form->language_payment(\%::myconfig);
1041
1042   Common::webdav_folder($::form);
1043
1044   form_header();
1045   display_row(++$::form->{rowcount});
1046   form_footer();
1047
1048   $::lxdebug->leave_sub;
1049 }
1050
1051 sub delete {
1052   $::auth->assert('invoice_edit');
1053
1054   if (IS->delete_invoice(\%::myconfig, $::form)) {
1055     # saving the history
1056     if(!exists $::form->{addition}) {
1057       $::form->{snumbers}  = 'invnumber' .'_'. $::form->{invnumber};
1058       $::form->{what_done} = 'invoice';
1059       $::form->{addition}  = "DELETED";
1060       $::form->save_history;
1061     }
1062     # /saving the history
1063     $::form->redirect($::locale->text('Invoice deleted!'));
1064   }
1065   $::form->error($::locale->text('Cannot delete invoice!'));
1066 }
1067
1068 sub post_and_e_mail {
1069   e_mail();
1070 };
1071
1072 sub e_mail {
1073   $main::lxdebug->enter_sub();
1074
1075   my $form     = $main::form;
1076
1077   $main::auth->assert('invoice_edit');
1078
1079   if (!$form->{id}) {
1080     $form->{no_redirect_after_post} = 1;
1081
1082     my $saved_form = save_form();
1083
1084     post();
1085
1086     restore_form($saved_form, 0, qw(id invnumber));
1087   }
1088
1089   edit_e_mail();
1090
1091   $main::lxdebug->leave_sub();
1092 }
1093
1094 sub dispatcher {
1095   for my $action (qw(
1096     print update ship_to e_mail storno post_payment use_as_new credit_note
1097     delete post order preview post_and_e_mail print_and_post
1098     mark_as_paid
1099   )) {
1100     if ($::form->{"action_$action"}) {
1101       call_sub($action);
1102       return;
1103     }
1104   }
1105
1106   $::form->error($::locale->text('No action defined.'));
1107 }