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