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