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