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