8aed4918cd4754c3b098376ab37f8d4c6e37f0b0
[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 require "bin/mozilla/io.pl";
42 require "bin/mozilla/invoice_io.pl";
43 require "bin/mozilla/arap.pl";
44 require "bin/mozilla/drafts.pl";
45
46 use strict;
47
48 1;
49
50 # end of main
51
52 sub add {
53   $main::lxdebug->enter_sub();
54
55   my $form     = $main::form;
56   my $locale   = $main::locale;
57
58   $main::auth->assert('invoice_edit');
59
60   return $main::lxdebug->leave_sub() if (load_draft_maybe());
61
62   if ($form->{type} eq "credit_note") {
63     $form->{title} = $locale->text('Add Credit Note');
64
65     if ($form->{storno}) {
66       $form->{title} = $locale->text('Add Storno Credit Note');
67     }
68   } else {
69     $form->{title} = $locale->text('Add Sales Invoice');
70
71   }
72
73
74   $form->{callback} = "$form->{script}?action=add&type=$form->{type}" unless $form->{callback};
75
76   $form->{jsscript} = "date";
77
78   &invoice_links;
79   &prepare_invoice;
80   &display_form;
81
82   $main::lxdebug->leave_sub();
83 }
84
85 sub edit {
86   $main::lxdebug->enter_sub();
87
88   my $form     = $main::form;
89   my $locale   = $main::locale;
90
91   $main::auth->assert('invoice_edit');
92
93   $form->{taxincluded_changed_by_user} = 1;
94
95   # show history button
96   $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
97   #/show hhistory button
98
99   my ($language_id, $printer_id);
100   if ($form->{print_and_post}) {
101     $form->{action}   = "print";
102     $form->{resubmit} = 1;
103     $language_id = $form->{language_id};
104     $printer_id = $form->{printer_id};
105   }
106
107   &invoice_links;
108   if ($form->{type} eq "credit_note") {
109     $form->{title} = $locale->text('Edit Credit Note');
110     $form->{title} = $locale->text('Edit Storno Credit Note') if $form->{storno};
111   } else {
112     $form->{title} = $locale->text('Edit Sales Invoice');
113     $form->{title} = $locale->text('Edit Storno Invoice')     if $form->{storno};
114   }
115
116   &prepare_invoice;
117   if ($form->{print_and_post}) {
118     $form->{language_id} = $language_id;
119     $form->{printer_id} = $printer_id;
120   }
121
122   &display_form;
123
124   $main::lxdebug->leave_sub();
125 }
126
127 sub invoice_links {
128   $main::lxdebug->enter_sub();
129
130   my $form     = $main::form;
131   my %myconfig = %main::myconfig;
132
133   $main::auth->assert('invoice_edit');
134
135   $form->{vc} = 'customer';
136
137   # create links
138   $form->{webdav}   = $::lx_office_conf{features}->{webdav};
139
140   $form->create_links("AR", \%myconfig, "customer");
141
142   if ($form->{all_customer}) {
143     unless ($form->{customer_id}) {
144       $form->{customer_id} = $form->{all_customer}->[0]->{id};
145       $form->{salesman_id} = $form->{all_customer}->[0]->{salesman_id};
146     }
147   }
148
149   my $editing = $form->{id};
150
151   $form->backup_vars(qw(payment_id language_id taxzone_id salesman_id taxincluded currency cp_id intnotes id shipto_id));
152
153   IS->get_customer(\%myconfig, \%$form);
154
155   #quote all_customer Bug 133
156   foreach my $ref (@{ $form->{all_customer} }) {
157     $ref->{name} = $form->quote($ref->{name});
158   }
159
160   $form->restore_vars(qw(id));
161
162   IS->retrieve_invoice(\%myconfig, \%$form);
163   $form->restore_vars(qw(payment_id language_id taxzone_id currency intnotes cp_id shipto_id));
164   $form->restore_vars(qw(taxincluded)) if $form->{id};
165   $form->restore_vars(qw(salesman_id)) if $editing;
166
167
168   # build vendor/customer drop down comatibility... don't ask
169   if (@{ $form->{"all_customer"} }) {
170     $form->{"selectcustomer"} = 1;
171     $form->{customer}         = qq|$form->{customer}--$form->{"customer_id"}|;
172   }
173
174   $form->{"oldcustomer"}  = $form->{customer};
175
176   if ($form->{"oldcustomer"} !~ m/--\d+$/ && $form->{"customer_id"}) {
177     $form->{"oldcustomer"} .= qq|--$form->{"customer_id"}|
178   }
179
180
181 #  $form->{oldcustomer} = "$form->{customer}--$form->{customer_id}";
182 #  $form->{selectcustomer} = 1;
183
184   $form->{employee} = "$form->{employee}--$form->{employee_id}";
185
186   # forex
187   $form->{forex} = $form->{exchangerate};
188   my $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
189
190   foreach my $key (keys %{ $form->{AR_links} }) {
191     foreach my $ref (@{ $form->{AR_links}{$key} }) {
192       $form->{"select$key"} .= "<option>$ref->{accno}--$ref->{description}</option>\n";
193     }
194
195     if ($key eq "AR_paid") {
196       next unless $form->{acc_trans}{$key};
197       for my $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
198         $form->{"AR_paid_$i"}      = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
199
200         $form->{"acc_trans_id_$i"}    = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
201         # reverse paid
202         $form->{"paid_$i"}         = $form->{acc_trans}{$key}->[$i - 1]->{amount} * -1;
203         $form->{"datepaid_$i"}     = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
204         $form->{"gldate_$i"}       = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
205         $form->{"exchangerate_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
206         $form->{"forex_$i"}        = $form->{"exchangerate_$i"};
207         $form->{"source_$i"}       = $form->{acc_trans}{$key}->[$i - 1]->{source};
208         $form->{"memo_$i"}         = $form->{acc_trans}{$key}->[$i - 1]->{memo};
209
210         $form->{paidaccounts} = $i;
211       }
212     } else {
213       $form->{$key} = "$form->{acc_trans}{$key}->[0]->{accno}--$form->{acc_trans}{$key}->[0]->{description}";
214     }
215   }
216
217   $form->{paidaccounts} = 1 unless (exists $form->{paidaccounts});
218
219   $form->{AR} = $form->{AR_1} unless $form->{id};
220
221   $form->{locked} = ($form->datetonum($form->{invdate},  \%myconfig)
222                   <= $form->datetonum($form->{closedto}, \%myconfig));
223
224   $main::lxdebug->leave_sub();
225 }
226
227 sub prepare_invoice {
228   $main::lxdebug->enter_sub();
229
230   my $form     = $main::form;
231   my %myconfig = %main::myconfig;
232
233   $main::auth->assert('invoice_edit');
234
235   if ($form->{type} eq "credit_note") {
236     $form->{type}     = "credit_note";
237     $form->{formname} = "credit_note";
238   } else {
239     $form->{type}     = "invoice";
240     $form->{formname} = "invoice";
241   }
242
243   if ($form->{id}) {
244
245     my $i = 0;
246
247     foreach my $ref (@{ $form->{invoice_details} }) {
248       $i++;
249
250       map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
251
252       $form->{"discount_$i"}   = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100);
253       my ($dec)                = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
254       $dec                     = length $dec;
255       my $decimalplaces        = ($dec > 2) ? $dec : 2;
256
257       $form->{"sellprice_$i"}  = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
258       (my $dec_qty)            = ($form->{"qty_$i"} =~ /\.(\d+)/);
259       $dec_qty                 = length $dec_qty;
260
261       $form->{"lastcost_$i"}  = $form->format_amount(\%myconfig, $form->{"lastcost_$i"}, $decimalplaces);
262
263       $form->{"qty_$i"}        = $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
264
265       $form->{"sellprice_pg_$i"} = join ('--', $form->{"sellprice_$i"}, $form->{"pricegroup_id_$i"});
266
267       $form->{rowcount}        = $i;
268
269     }
270
271     # get pricegroups for parts
272     IS->get_pricegroups_for_parts(\%myconfig, \%$form);
273
274     # Problem: set_pricegroup resets the sellprice of old invoices to the price
275     # currently defined in the pricegroup, which is a problem if the price has
276     # changed, as the old invoice gets the new price
277     # set_pricegroup must never be called, when an old invoice is initially loaded
278
279     # set_pricegroup($_) for 1 .. $form->{rowcount};
280   }
281   $main::lxdebug->leave_sub();
282 }
283
284 sub form_header {
285   $main::lxdebug->enter_sub();
286
287   my $form     = $main::form;
288   my %myconfig = %main::myconfig;
289   my $locale   = $main::locale;
290   my $cgi      = $::request->{cgi};
291
292   $main::auth->assert('invoice_edit');
293
294   my %TMPL_VAR = ();
295   my @custom_hiddens;
296
297   $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
298   $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
299
300   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
301
302   my @old_project_ids = ($form->{"globalproject_id"});
303   map { push @old_project_ids, $form->{"project_id_$_"} if $form->{"project_id_$_"}; } 1..$form->{"rowcount"};
304
305   $form->get_lists("projects"      => { "key"    => "ALL_PROJECTS",
306                                         "all"    => 0,
307                                         "old_id" => \@old_project_ids },
308                    "taxzones"      => "ALL_TAXZONES",
309                    "currencies"    => "ALL_CURRENCIES",
310                    "customers"     => "ALL_CUSTOMERS",
311                    "departments"   => "all_departments",
312                    "price_factors" => "ALL_PRICE_FACTORS");
313
314   $TMPL_VAR{ALL_EMPLOYEES}         = SL::DB::Manager::Employee->get_all(query => [ or => [ id => $::form->{employee_id},  deleted => 0 ] ]);
315   $TMPL_VAR{ALL_SALESMEN}          = SL::DB::Manager::Employee->get_all(query => [ or => [ id => $::form->{salesman_id},  deleted => 0 ] ]);
316   $TMPL_VAR{ALL_SHIPTO}            = SL::DB::Manager::Shipto->get_all(query => [
317     or => [ trans_id  => $::form->{"$::form->{vc}_id"} * 1, and => [ shipto_id => $::form->{shipto_id} * 1, trans_id => undef ] ]
318   ]);
319   $TMPL_VAR{ALL_CONTACTS}          = SL::DB::Manager::Contact->get_all(query => [
320     or => [
321       cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
322       and      => [
323         cp_cv_id => undef,
324         cp_id    => $::form->{cp_id} * 1
325       ]
326     ]
327   ]);
328   $TMPL_VAR{department_labels}     = sub { "$_[0]->{description}--$_[0]->{id}" };
329
330   # customer
331   $TMPL_VAR{vc_keys} = sub { "$_[0]->{name}--$_[0]->{id}" };
332   $TMPL_VAR{vclimit} = $myconfig{vclimit};
333   $TMPL_VAR{vc_select} = "customer_or_vendor_selection_window('customer', '', 0, 0)";
334   push @custom_hiddens, "customer_id";
335   push @custom_hiddens, "oldcustomer";
336   push @custom_hiddens, "selectcustomer";
337
338   # currencies and exchangerate
339   my @values = map { $_       } @{ $form->{ALL_CURRENCIES} };
340   my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
341   $form->{currency}            = $form->{defaultcurrency} unless $form->{currency};
342   $form->{show_exchangerate}   = $form->{currency} ne $form->{defaultcurrency};
343   $TMPL_VAR{currencies}        = NTI($::request->{cgi}->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
344                                                       '-values' => \@values, '-labels' => \%labels,
345                                                       '-onchange' => "document.getElementById('update_button').click();"
346                                      )) if scalar @values;
347   push @custom_hiddens, "forex";
348   push @custom_hiddens, "exchangerate" if $form->{forex};
349
350   $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
351   $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
352
353   $form->{fokus} = "invoice.customer";
354
355   my $follow_up_vc         =  $form->{customer};
356   $follow_up_vc            =~ s/--\d*\s*$//;
357   $TMPL_VAR{customer_name} = $follow_up_vc;
358
359 # set option selected
360   foreach my $item (qw(AR)) {
361     $form->{"select$item"} =~ s/ selected//;
362     $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
363   }
364
365   $TMPL_VAR{is_type_credit_note} = $form->{type}   eq "credit_note";
366   $TMPL_VAR{is_format_html}      = $form->{format} eq 'html';
367   $TMPL_VAR{dateformat}          = $myconfig{dateformat};
368   $TMPL_VAR{numberformat}        = $myconfig{numberformat};
369
370   # hiddens
371   $TMPL_VAR{HIDDENS} = [qw(
372     id action type media format queued printed emailed title vc discount
373     title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
374     max_dunning_level dunning_amount
375     shiptoname shiptostreet shiptozipcode shiptocity shiptocountry  shiptocontact shiptophone shiptofax
376     shiptoemail shiptodepartment_1 shiptodepartment_2  shiptocp_gender message email subject cc bcc taxaccounts cursor_fokus
377     convert_from_do_ids convert_from_oe_ids
378   ), @custom_hiddens,
379   map { $_.'_rate', $_.'_description', $_.'_taxnumber' } split / /, $form->{taxaccounts}];
380
381   $form->{jsscript} = 1;
382   $form->header();
383
384   print $form->parse_html_template("is/form_header", \%TMPL_VAR);
385
386   $main::lxdebug->leave_sub();
387 }
388
389 sub form_footer {
390   $main::lxdebug->enter_sub();
391
392   my $form     = $main::form;
393   my %myconfig = %main::myconfig;
394   my $locale   = $main::locale;
395
396   $main::auth->assert('invoice_edit');
397
398   $form->{invtotal}    = $form->{invsubtotal};
399
400   # note rows
401   $form->{rows} = max 2,
402     $form->numtextrows($form->{notes},    26, 8),
403     $form->numtextrows($form->{intnotes}, 35, 8);
404
405
406   # tax, total and subtotal calculations
407   my ($tax, $subtotal);
408   $form->{taxaccounts_array} = [ split / /, $form->{taxaccounts} ];
409
410   my $paymet_id = $::form->{payment_id};
411   IS->get_customer(\%myconfig, \%$form) if $form->{type} =~ /sales_(order|quotation)/;
412   $::form->{payment_id} = $paymet_id;
413
414   if ( $form->{vc} eq 'customer' && !$form->{taxincluded_changed_by_user} ) {
415     $form->{taxincluded} = defined($form->{taxincluded_checked}) ? $form->{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 ($::lx_office_conf{features}->{payments_changeable} == 0) {
448       # never
449       $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
450     } elsif ($::lx_office_conf{features}->{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   print $form->parse_html_template('is/form_footer', {
469     is_type_credit_note => ($form->{type} eq "credit_note"),
470     totalpaid           => $totalpaid,
471     paid_missing        => $form->{invtotal} - $totalpaid,
472     print_options       => print_options(inline => 1),
473     show_storno         => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ar") && !$totalpaid,
474     show_delete         => ($form->current_date(\%myconfig) eq $form->{gldate}),
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 invoice for a closed period!'))
718     if ($invdate <= $closedto);
719
720   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
721     if ($form->{currency} ne $form->{defaultcurrency});
722
723   for my $i (1 .. $form->{paidaccounts}) {
724     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
725       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
726
727       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
728
729       $form->error($locale->text('Cannot post payment for a closed period!'))
730         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
731
732       if ($form->{currency} ne $form->{defaultcurrency}) {
733         $form->{"exchangerate_$i"} = $form->{exchangerate}
734           if ($invdate == $datepaid);
735         $form->isblank("exchangerate_$i",
736                        $locale->text('Exchangerate for payment missing!'));
737       }
738     }
739   }
740
741   ($form->{AR})        = split /--/, $form->{AR};
742   ($form->{AR_paid})   = split /--/, $form->{AR_paid};
743   $form->{storno}    ||= 0;
744
745   $form->{label} = $form->{type} eq 'credit_note' ? $locale->text('Credit Note') : $locale->text('Invoice');
746
747   $form->{id} = 0 if $form->{postasnew};
748
749   # get new invnumber in sequence if no invnumber is given or if posasnew was requested
750   if ($form->{postasnew}) {
751     if ($form->{type} eq "credit_note") {
752       undef($form->{cnnumber});
753     } else {
754       undef($form->{invnumber});
755     }
756   }
757
758   relink_accounts();
759   $form->error($locale->text('Cannot post invoice!'))
760     unless IS->post_invoice(\%myconfig, \%$form);
761   remove_draft() if $form->{remove_draft};
762
763   if(!exists $form->{addition}) {
764     $form->{snumbers} =  'invnumber' .'_'. $form->{invnumber}; # ($form->{type} eq 'credit_note' ? 'cnnumber' : 'invnumber') .'_'. $form->{invnumber};
765     $form->{addition} = $form->{print_and_post} ? "PRINTED AND POSTED" :
766                         $form->{storno}         ? "STORNO"             :
767                                                   "POSTED";
768     $form->save_history;
769   }
770
771   if (!$form->{no_redirect_after_post}) {
772     $form->{action} = 'edit';
773     $form->{script} = 'is.pl';
774     $form->{saved_message} = $form->{label} . " $form->{invnumber} " . $locale->text('posted!');
775     $form->{callback} = build_std_url(qw(action edit id saved_message));
776     $form->redirect;
777   }
778
779   $main::lxdebug->leave_sub();
780 }
781
782 sub print_and_post {
783   $main::lxdebug->enter_sub();
784
785   my $form     = $main::form;
786
787   $main::auth->assert('invoice_edit');
788
789   my $old_form                    = new Form;
790   $form->{no_redirect_after_post} = 1;
791   $form->{print_and_post}         = 1;
792   &post();
793
794   &edit();
795   $main::lxdebug->leave_sub();
796
797 }
798
799 sub use_as_template {
800   $main::lxdebug->enter_sub();
801
802   my $form     = $main::form;
803   my %myconfig = %main::myconfig;
804
805   $main::auth->assert('invoice_edit');
806
807   map { 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);
808   $form->{paidaccounts} = 1;
809   $form->{rowcount}--;
810   $form->{invdate} = $form->current_date(\%myconfig);
811
812   # remember pricegroups for "use as template"
813   IS->get_pricegroups_for_parts(\%myconfig, \%$form);
814   set_pricegroup($_) for 1 .. $form->{rowcount};
815
816   &display_form;
817
818   $main::lxdebug->leave_sub();
819 }
820
821 sub storno {
822   $main::lxdebug->enter_sub();
823
824   my $form     = $main::form;
825   my %myconfig = %main::myconfig;
826   my $locale   = $main::locale;
827
828   $main::auth->assert('invoice_edit');
829
830   if ($form->{storno}) {
831     $form->error($locale->text('Cannot storno storno invoice!'));
832   }
833
834   if (IS->has_storno(\%myconfig, $form, "ar")) {
835     $form->error($locale->text("Invoice has already been storno'd!"));
836   }
837
838   map({ my $key = $_; delete($form->{$key}) unless (grep({ $key eq $_ } qw(id login password type))); } keys(%{ $form }));
839
840   invoice_links();
841   prepare_invoice();
842   relink_accounts();
843
844   # Payments must not be recorded for the new storno invoice.
845   $form->{paidaccounts} = 0;
846   map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
847
848   $form->{storno_id} = $form->{id};
849   $form->{storno} = 1;
850   $form->{id} = "";
851   $form->{invnumber} = "Storno zu " . $form->{invnumber};
852   $form->{rowcount}++;
853
854   post();
855   $main::lxdebug->leave_sub();
856 }
857
858 sub preview {
859   $main::lxdebug->enter_sub();
860
861   my $form     = $main::form;
862
863   $main::auth->assert('invoice_edit');
864
865   $form->{preview} = 1;
866   my $old_form = new Form;
867   for (keys %$form) { $old_form->{$_} = $form->{$_} }
868
869   &print_form($old_form);
870   $main::lxdebug->leave_sub();
871
872 }
873
874 sub delete {
875   $main::lxdebug->enter_sub();
876
877   my $form     = $main::form;
878   my $locale   = $main::locale;
879
880   $main::auth->assert('invoice_edit');
881
882   if ($form->{second_run}) {
883     $form->{print_and_post} = 0;
884   }
885   $form->header;
886
887   print qq|
888 <body>
889
890 <form method="post" action="$form->{script}">
891 |;
892
893   # delete action variable
894   map { delete $form->{$_} } qw(action header);
895
896   foreach my $key (keys %$form) {
897     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
898     $form->{$key} =~ s/\"/&quot;/g;
899     print qq|<input type="hidden" name="$key" value="$form->{$key}">\n|;
900   }
901
902   print qq|
903 <h2 class="confirm">| . $locale->text('Confirm!') . qq|</h2>
904
905 <h4>|
906     . $locale->text('Are you sure you want to delete Invoice Number')
907     . qq| $form->{invnumber}
908 </h4>
909
910 <p>
911 <input name="action" class="submit" type="submit" value="|
912     . $locale->text('Yes') . qq|">
913 </form>
914 |;
915
916   $main::lxdebug->leave_sub();
917 }
918
919 sub credit_note {
920   $main::lxdebug->enter_sub();
921
922   my $form     = $main::form;
923   my %myconfig = %main::myconfig;
924   my $locale   = $main::locale;
925
926   $main::auth->assert('invoice_edit');
927
928   $form->{transdate} = $form->{invdate} = $form->current_date(\%myconfig);
929   $form->{duedate} =
930     $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
931
932   $form->{id}     = '';
933   $form->{rowcount}--;
934   $form->{shipto} = 1;
935
936
937   $form->{title}  = $locale->text('Add Credit Note');
938   $form->{script} = 'is.pl';
939
940   # Bei Gutschriften bezug zur Rechnungsnummer
941   $form->{invnumber_for_credit_note} = $form->{invnumber};
942   # bo creates the id, reset it
943   map { delete $form->{$_} }
944     qw(id invnumber subject message cc bcc printed emailed queued);
945   $form->{ $form->{vc} } =~ s/--.*//g;
946   $form->{type} = "credit_note";
947
948
949   map { $form->{"select$_"} = "" } ($form->{vc}, 'currency');
950
951 #  map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
952 #    qw(creditlimit creditremaining);
953
954   for my $i (1 .. $form->{rowcount}) {
955     for (qw(listprice)) {
956       $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"}) if $form->{"${_}_${i}"};
957     }
958   }
959
960   my $currency = $form->{currency};
961   &invoice_links;
962
963   $form->{currency}     = $currency;
964   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, 'buy');
965   $form->{exchangerate} = $form->{forex} || '';
966
967   $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
968
969   # bei Gutschriften werden Zahlungseingänge aus Rechnung nicht übernommen
970   for my $i (1 .. $form->{paidaccounts}) {
971     delete $form->{"paid_$i"};
972     delete $form->{"source_$i"};
973     delete $form->{"memo_$i"};
974     delete $form->{"datepaid_$i"};
975     delete $form->{"gldate_$i"};
976     delete $form->{"acc_trans_id_$i"};
977     delete $form->{"AR_paid_$i"};
978   };
979   $form->{paidaccounts} = 1;
980
981   &prepare_invoice;
982
983
984   &display_form;
985
986   $main::lxdebug->leave_sub();
987 }
988
989 sub yes {
990   $main::lxdebug->enter_sub();
991
992   my $form     = $main::form;
993   my %myconfig = %main::myconfig;
994   my $locale   = $main::locale;
995
996   $main::auth->assert('invoice_edit');
997
998   if (IS->delete_invoice(\%myconfig, \%$form)) {
999     # saving the history
1000     if(!exists $form->{addition}) {
1001       $form->{snumbers} = 'invnumber' .'_'. $form->{invnumber}; # ($form->{type} eq 'credit_note' ? 'cnnumber' : 'invnumber') .'_'. $form->{invnumber};
1002       $form->{addition} = "DELETED";
1003       $form->save_history;
1004     }
1005     # /saving the history
1006     $form->redirect($locale->text('Invoice deleted!'));
1007   }
1008   $form->error($locale->text('Cannot delete invoice!'));
1009
1010   $main::lxdebug->leave_sub();
1011 }
1012
1013 sub e_mail {
1014   $main::lxdebug->enter_sub();
1015
1016   my $form     = $main::form;
1017
1018   $main::auth->assert('invoice_edit');
1019
1020   if (!$form->{id}) {
1021     $form->{no_redirect_after_post} = 1;
1022
1023     my $saved_form = save_form();
1024
1025     post();
1026
1027     restore_form($saved_form, 0, qw(id invnumber));
1028   }
1029
1030   edit_e_mail();
1031
1032   $main::lxdebug->leave_sub();
1033 }