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