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