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