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