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