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