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