0567e672e34169d0a0847b0562171fe109752aeb
[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 Data::Dumper;
38 use List::Util qw(max sum);
39
40 require "bin/mozilla/io.pl";
41 require "bin/mozilla/invoice_io.pl";
42 require "bin/mozilla/arap.pl";
43 require "bin/mozilla/drafts.pl";
44
45 use strict;
46
47 my $edit;
48 my $payment;
49 my $print_post;
50
51 1;
52
53 # end of main
54
55 sub add {
56   $main::lxdebug->enter_sub();
57
58   my $form     = $main::form;
59   my $locale   = $main::locale;
60
61   $main::auth->assert('invoice_edit');
62
63   return $main::lxdebug->leave_sub() if (load_draft_maybe());
64
65   if ($form->{type} eq "credit_note") {
66     $form->{title} = $locale->text('Add Credit Note');
67
68     if ($form->{storno}) {
69       $form->{title} = $locale->text('Add Storno Credit Note');
70     }
71   } else {
72     $form->{title} = $locale->text('Add Sales Invoice');
73
74   }
75
76
77   $form->{callback} = "$form->{script}?action=add&type=$form->{type}" unless $form->{callback};
78
79   $form->{jsscript} = "date";
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   # show history button
97   $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
98   #/show hhistory button
99
100   if ($form->{type} eq "credit_note") {
101     $form->{title} = $locale->text('Edit Credit Note');
102     $form->{title} = $locale->text('Edit Storno Credit Note') if $form->{storno};
103   } else {
104     $form->{title} = $locale->text('Edit Sales Invoice');
105     $form->{title} = $locale->text('Edit Storno Invoice')     if $form->{storno};
106   }
107
108   my ($language_id, $printer_id);
109   if ($form->{print_and_post}) {
110     $form->{action}   = "print";
111     $form->{resubmit} = 1;
112     $language_id = $form->{language_id};
113     $printer_id = $form->{printer_id};
114   }
115   &invoice_links;
116   &prepare_invoice;
117   if ($form->{print_and_post}) {
118     $form->{language_id} = $language_id;
119     $form->{printer_id} = $printer_id;
120   }
121
122   &display_form;
123
124   $main::lxdebug->leave_sub();
125 }
126
127 sub invoice_links {
128   $main::lxdebug->enter_sub();
129
130   my $form     = $main::form;
131   my %myconfig = %main::myconfig;
132
133   $main::auth->assert('invoice_edit');
134
135   $form->{vc} = 'customer';
136
137   # create links
138   $form->{webdav}   = $main::webdav;
139   $form->{lizenzen} = $main::lizenzen;
140
141   $form->create_links("AR", \%myconfig, "customer");
142
143   if ($form->{all_customer}) {
144     unless ($form->{customer_id}) {
145       $form->{customer_id} = $form->{all_customer}->[0]->{id};
146       $form->{salesman_id} = $form->{all_customer}->[0]->{salesman_id};
147     }
148   }
149
150   $form->backup_vars(qw(payment_id language_id taxzone_id salesman_id taxincluded cp_id intnotes id shipto_id));
151
152   IS->get_customer(\%myconfig, \%$form);
153
154   #quote all_customer Bug 133
155   foreach my $ref (@{ $form->{all_customer} }) {
156     $ref->{name} = $form->quote($ref->{name});
157   }
158
159   $form->restore_vars(qw(id));
160
161   IS->retrieve_invoice(\%myconfig, \%$form);
162   $form->restore_vars(qw(payment_id language_id taxzone_id intnotes cp_id shipto_id));
163   $form->restore_vars(qw(taxincluded)) if $form->{id};
164   $form->restore_vars(qw(salesman_id)) if $main::editing;
165
166   # build vendor/customer drop down comatibility... don't ask
167   if (@{ $form->{"all_customer"} }) {
168     $form->{"selectcustomer"} = 1;
169     $form->{customer}         = qq|$form->{customer}--$form->{"customer_id"}|;
170   }
171
172   $form->{oldcustomer} = "$form->{customer}--$form->{customer_id}";
173   $form->{selectcustomer} = 1;
174
175   # departments
176 #  if ($form->{all_departments}) {
177 #    $form->{selectdepartment} = "<option>\n";
178 #    $form->{department}       = "$form->{department}--$form->{department_id}";
179 #
180 #    map {
181 #      $form->{selectdepartment} .= "<option>$_->{description}--$_->{id}</option>\n"
182 #    } @{ $form->{all_departments} };
183 #  }
184
185   $form->{employee} = "$form->{employee}--$form->{employee_id}";
186
187   # forex
188   $form->{forex} = $form->{exchangerate};
189   my $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
190
191   foreach my $key (keys %{ $form->{AR_links} }) {
192     foreach my $ref (@{ $form->{AR_links}{$key} }) {
193       $form->{"select$key"} .= "<option>$ref->{accno}--$ref->{description}</option>\n";
194     }
195
196     if ($key eq "AR_paid") {
197       next unless $form->{acc_trans}{$key};
198       for my $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
199         $form->{"AR_paid_$i"}      = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
200
201         # reverse paid
202         $form->{"paid_$i"}         = $form->{acc_trans}{$key}->[$i - 1]->{amount} * -1;
203         $form->{"datepaid_$i"}     = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
204         $form->{"exchangerate_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
205         $form->{"forex_$i"}        = $form->{"exchangerate_$i"};
206         $form->{"source_$i"}       = $form->{acc_trans}{$key}->[$i - 1]->{source};
207         $form->{"memo_$i"}         = $form->{acc_trans}{$key}->[$i - 1]->{memo};
208
209         $form->{paidaccounts} = $i;
210       }
211     } else {
212       $form->{$key} = "$form->{acc_trans}{$key}->[0]->{accno}--$form->{acc_trans}{$key}->[0]->{description}";
213     }
214   }
215
216   $form->{paidaccounts} = 1 unless (exists $form->{paidaccounts});
217
218   $form->{AR} = $form->{AR_1} unless $form->{id};
219
220   $form->{locked} = ($form->datetonum($form->{invdate},  \%myconfig)
221                   <= $form->datetonum($form->{closedto}, \%myconfig));
222
223   $main::lxdebug->leave_sub();
224 }
225
226 sub prepare_invoice {
227   $main::lxdebug->enter_sub();
228
229   my $form     = $main::form;
230   my %myconfig = %main::myconfig;
231
232   $main::auth->assert('invoice_edit');
233
234   if ($form->{type} eq "credit_note") {
235     $form->{type}     = "credit_note";
236     $form->{formname} = "credit_note";
237   } else {
238     $form->{type}     = "invoice";
239     $form->{formname} = "invoice";
240   }
241
242   if ($form->{id}) {
243
244     my $i = 0;
245
246     foreach my $ref (@{ $form->{invoice_details} }) {
247       $i++;
248
249       map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
250
251       $form->{"discount_$i"}   = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100);
252       my ($dec)                = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
253       $dec                     = length $dec;
254       my $decimalplaces        = ($dec > 2) ? $dec : 2;
255
256       $form->{"sellprice_$i"}  = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
257       (my $dec_qty)            = ($form->{"qty_$i"} =~ /\.(\d+)/);
258       $dec_qty                 = length $dec_qty;
259
260       $form->{"qty_$i"}        = $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
261
262       $form->{rowcount}        = $i;
263
264     }
265
266     # get pricegroups for parts
267     IS->get_pricegroups_for_parts(\%myconfig, \%$form);
268     set_pricegroup($_) for 1 .. $form->{rowcount};
269   }
270   $main::lxdebug->leave_sub();
271 }
272
273 sub form_header {
274   $main::lxdebug->enter_sub();
275
276   my $form     = $main::form;
277   my %myconfig = %main::myconfig;
278   my $locale   = $main::locale;
279   my $cgi      = $main::cgi;
280
281   $main::auth->assert('invoice_edit');
282
283   our %TMPL_VAR = ();
284   my @custom_hiddens;
285
286   $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
287   $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
288
289   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
290   $form->{radier}          = ($form->current_date(\%myconfig) eq $form->{gldate}) ? 1 : 0;
291
292   $payment = qq|<option value=""></option>|;
293   foreach my $item (@{ $form->{payment_terms} }) {
294     if ($form->{payment_id} eq $item->{id}) {
295       $payment .= qq|<option value="$item->{id}" selected>$item->{description}</option>|;
296     } else {
297       $payment .= qq|<option value="$item->{id}">$item->{description}</option>|;
298     }
299   }
300
301   my $set_duedate_url = "$form->{script}?action=set_duedate";
302
303   push @ { $form->{AJAX} }, new CGI::Ajax( 'set_duedate' => $set_duedate_url );
304
305   my @old_project_ids = ($form->{"globalproject_id"});
306   map { push @old_project_ids, $form->{"project_id_$_"} if $form->{"project_id_$_"}; } 1..$form->{"rowcount"};
307
308   $form->get_lists("contacts"      => "ALL_CONTACTS",
309                    "shipto"        => "ALL_SHIPTO",
310                    "projects"      => { "key"    => "ALL_PROJECTS",
311                                         "all"    => 0,
312                                         "old_id" => \@old_project_ids },
313                    "employees"     => "ALL_EMPLOYEES",
314                    "salesmen"      => "ALL_SALESMEN",
315                    "taxzones"      => "ALL_TAXZONES",
316                    "currencies"    => "ALL_CURRENCIES",
317                    "customers"     => "ALL_CUSTOMERS",
318                    "price_factors" => "ALL_PRICE_FACTORS");
319
320   $TMPL_VAR{sales_employee_labels} = sub { $_[0]->{name} || $_[0]->{login} };
321   $TMPL_VAR{shipto_labels}         = sub { join "; ", grep { $_ } map { $_[0]->{"shipto${_}" } } qw(name department_1 street city) };
322   $TMPL_VAR{contact_labels}        = sub { join(', ', $_[0]->{"cp_name"}, $_[0]->{"cp_givenname"}) . ($_[0]->{cp_abteilung} ? " ($_[0]->{cp_abteilung})" : "") };
323   $TMPL_VAR{department_labels}     = sub { "$_[0]->{description}--$_[0]->{id}" };
324
325   # customer
326   $TMPL_VAR{vc_keys} = sub { "$_[0]->{name}--$_[0]->{id}" };
327   $TMPL_VAR{vclimit} = $myconfig{vclimit};
328   $TMPL_VAR{vc_select} = "customer_or_vendor_selection_window('customer', '', 0, 0)";
329   push @custom_hiddens, "customer_id";
330   push @custom_hiddens, "oldcustomer";
331   push @custom_hiddens, "selectcustomer";
332
333   # currencies and exchangerate
334   my @values = map { $_       } @{ $form->{ALL_CURRENCIES} };
335   my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
336   $form->{currency}            = $form->{defaultcurrency} unless $form->{currency};
337   $TMPL_VAR{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
338   $TMPL_VAR{currencies}        = NTI($cgi->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
339                                                       '-values' => \@values, '-labels' => \%labels)) if scalar @values;
340   push @custom_hiddens, "forex";
341   push @custom_hiddens, "exchangerate" if $form->{forex};
342
343   $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
344   $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
345
346   $form->{fokus} = "invoice.customer";
347
348   my $follow_up_vc         =  $form->{customer};
349   $follow_up_vc            =~ s/--\d*\s*$//;
350   $TMPL_VAR{customer_name} = $follow_up_vc;
351
352 # set option selected
353   foreach my $item (qw(AR)) {
354     $form->{"select$item"} =~ s/ selected//;
355     $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
356   }
357
358   $TMPL_VAR{is_type_credit_note} = $form->{type}   eq "credit_note";
359   $TMPL_VAR{is_format_html}      = $form->{format} eq 'html';
360   $TMPL_VAR{dateformat}          = $myconfig{dateformat};
361   $TMPL_VAR{numberformat}        = $myconfig{numberformat};
362
363   # hiddens
364   $TMPL_VAR{HIDDENS} = [qw(
365     id action type media format queued printed emailed title vc discount
366     title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
367     max_dunning_level dunning_amount
368     shiptoname shiptostreet shiptozipcode shiptocity shiptocountry  shiptocontact shiptophone shiptofax
369     shiptoemail shiptodepartment_1 shiptodepartment_2 message email subject cc bcc taxaccounts cursor_fokus
370     convert_from_do_ids convert_from_oe_ids
371   ), @custom_hiddens,
372   map { $_.'_rate', $_.'_description', $_.'_taxnumber' } split / /, $form->{taxaccounts}];
373
374   $form->{jsscript} = 1;
375   $form->header();
376
377   print $form->parse_html_template("is/form_header", \%TMPL_VAR);
378
379   $main::lxdebug->leave_sub();
380 }
381
382 sub form_footer {
383   $main::lxdebug->enter_sub();
384
385   my $form     = $main::form;
386   my %myconfig = %main::myconfig;
387   my $locale   = $main::locale;
388
389   $main::auth->assert('invoice_edit');
390
391   $form->{invtotal}    = $form->{invsubtotal};
392   $form->{oldinvtotal} = $form->{invtotal};
393
394   # note rows
395   $form->{rows} = max 2,
396     $form->numtextrows($form->{notes},    26, 8),
397     $form->numtextrows($form->{intnotes}, 35, 8);
398
399
400   # tax, total and subtotal calculations
401   my ($tax, $subtotal);
402   $form->{taxaccounts_array} = [ split / /, $form->{taxaccounts} ];
403
404   foreach my $item (@{ $form->{taxaccounts_array} }) {
405     if ($form->{"${item}_base"}) {
406       if ($form->{taxincluded}) {
407         $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
408                                                                                  / (1 + $form->{"${item}_rate"})), 2);
409         $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
410       } else {
411         $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
412         $form->{invtotal} += $form->{"${item}_total"};
413       }
414     }
415   }
416
417   # follow ups
418   if ($form->{id}) {
419     $form->{follow_ups}            = FU->follow_ups('trans_id' => $form->{id}) || [];
420     $form->{follow_ups_unfinished} = sum map { $_->{due} * 1 } @{ $form->{follow_ups} };
421   }
422
423   # payments
424   my $totalpaid = 0;
425   $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
426   $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
427
428   for my $i (1 .. $form->{paidaccounts}) {
429     $form->{"selectAR_paid_$i"} = $form->{selectAR_paid};
430     $form->{"selectAR_paid_$i"} =~ s/option>\Q$form->{"AR_paid_$i"}\E/option selected>$form->{"AR_paid_$i"}/;
431     $totalpaid += $form->{"paid_$i"};
432   }
433
434   print $form->parse_html_template('is/form_footer', {
435     is_type_credit_note => ($form->{type} eq "credit_note"),
436     totalpaid           => $totalpaid,
437     paid_missing        => $form->{invtotal} - $totalpaid,
438     print_options       => print_options(inline => 1),
439     show_storno         => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ar") && !$totalpaid,
440     show_delete         => ($form->current_date(\%myconfig) eq $form->{gldate}),
441   });
442 ##print $form->parse_html_template('is/_payments'); # parser
443 ##print $form->parse_html_template('webdav/_list'); # parser
444
445   $main::lxdebug->leave_sub();
446 }
447
448 sub mark_as_paid {
449   $main::lxdebug->enter_sub();
450
451   my $form     = $main::form;
452   my %myconfig = %main::myconfig;
453
454   $main::auth->assert('invoice_edit');
455
456   &mark_as_paid_common(\%myconfig,"ar");
457
458   $main::lxdebug->leave_sub();
459 }
460
461 sub update {
462   $main::lxdebug->enter_sub();
463
464   my $form     = $main::form;
465   my %myconfig = %main::myconfig;
466
467   $main::auth->assert('invoice_edit');
468
469   my ($recursive_call) = shift;
470
471   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) } qw(exchangerate creditlimit creditremaining) unless $recursive_call;
472
473   $form->{print_and_post} = 0         if $form->{second_run};
474   my $taxincluded            = "checked" if $form->{taxincluded};
475   $form->{update} = 1;
476
477   &check_name("customer");
478
479   $form->{taxincluded} ||= $taxincluded;
480
481   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
482   $form->{exchangerate} = $form->{forex} if $form->{forex};
483
484   for my $i (1 .. $form->{paidaccounts}) {
485     next unless $form->{"paid_$i"};
486     map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
487     $form->{"forex_$i"}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
488     $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
489   }
490
491   my $i            = $form->{rowcount};
492   my $exchangerate = $form->{exchangerate} || 1;
493
494   # if last row empty, check the form otherwise retrieve new item
495   if (   ($form->{"partnumber_$i"} eq "")
496       && ($form->{"description_$i"} eq "")
497       && ($form->{"partsgroup_$i"}  eq "")) {
498
499     $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
500     &check_form;
501
502   } else {
503
504     IS->retrieve_item(\%myconfig, \%$form);
505
506     my $rows = scalar @{ $form->{item_list} };
507
508     $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{customer_discount} * 100);
509
510     if ($rows) {
511       $form->{"qty_$i"} = ($form->{"qty_$i"} * 1) ? $form->{"qty_$i"} : 1;
512
513       if ($rows > 1) {
514
515         &select_item;
516         exit;
517
518       } else {
519
520         my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
521
522         map { $form->{item_list}[$i]{$_} =~ s/\"/&quot;/g } qw(partnumber description unit);
523         map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
524
525         $form->{payment_id}    = $form->{"part_payment_id_$i"} if $form->{"part_payment_id_$i"} ne "";
526         $form->{"discount_$i"} = 0                             if $form->{"not_discountable_$i"};
527
528         $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
529
530         ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
531         my $decimalplaces = max 2, length $1;
532
533         if ($sellprice) {
534           $form->{"sellprice_$i"} = $sellprice;
535         } else {
536           # if there is an exchange rate adjust sellprice
537           $form->{"sellprice_$i"} *= (1 - $form->{tradediscount});
538           $form->{"sellprice_$i"} /= $exchangerate;
539         }
540
541         $form->{"listprice_$i"} /= $exchangerate;
542
543         my $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"} / 100);
544         map { $form->{"${_}_base"} = 0 }                                 split / /, $form->{taxaccounts};
545         map { $form->{"${_}_base"} += $amount }                          split / /, $form->{"taxaccounts_$i"};
546         map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{"taxaccounts_$i"} if !$form->{taxincluded};
547
548         $form->{creditremaining} -= $amount;
549
550         map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces) } qw(sellprice listprice);
551
552         $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"});
553
554         if ($main::lizenzen) {
555           if ($form->{"inventory_accno_$i"} ne "") {
556             $form->{"lizenzen_$i"} = qq|<option></option>|;
557             foreach my $item (@{ $form->{LIZENZEN}{ $form->{"id_$i"} } }) {
558               $form->{"lizenzen_$i"} .= qq|<option value="$item->{"id"}">$item->{"licensenumber"}</option>|;
559             }
560             $form->{"lizenzen_$i"} .= qq|<option value=-1>Neue Lizenz</option>|;
561           }
562         }
563
564         # get pricegroups for parts
565         IS->get_pricegroups_for_parts(\%myconfig, \%$form);
566
567         # build up html code for prices_$i
568         &set_pricegroup($i);
569       }
570
571       &display_form;
572
573     } else {
574
575       # ok, so this is a new part
576       # ask if it is a part or service item
577
578       if (   $form->{"partsgroup_$i"}
579           && ($form->{"partsnumber_$i"} eq "")
580           && ($form->{"description_$i"} eq "")) {
581         $form->{rowcount}--;
582         $form->{"discount_$i"} = "";
583         display_form();
584
585       } else {
586         $form->{"id_$i"}   = 0;
587         new_item();
588       }
589     }
590   }
591   $main::lxdebug->leave_sub();
592 }
593
594 sub post_payment {
595   $main::lxdebug->enter_sub();
596
597   my $form     = $main::form;
598   my %myconfig = %main::myconfig;
599   my $locale   = $main::locale;
600
601   $main::auth->assert('invoice_edit');
602
603   our $invdate;
604
605   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
606   for my $i (1 .. $form->{paidaccounts}) {
607     if ($form->{"paid_$i"}) {
608       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
609
610       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
611
612       $form->error($locale->text('Cannot post payment for a closed period!'))
613         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
614
615       if ($form->{currency} ne $form->{defaultcurrency}) {
616         $form->{"exchangerate_$i"} = $form->{exchangerate}
617           if ($invdate == $datepaid);
618         $form->isblank("exchangerate_$i",
619                        $locale->text('Exchangerate for payment missing!'));
620       }
621     }
622   }
623
624   ($form->{AR})      = split /--/, $form->{AR};
625   ($form->{AR_paid}) = split /--/, $form->{AR_paid};
626   relink_accounts();
627   $form->redirect($locale->text('Payment posted!'))
628       if (IS->post_payment(\%myconfig, \%$form));
629     $form->error($locale->text('Cannot post payment!'));
630
631
632   $main::lxdebug->leave_sub();
633 }
634
635 sub post {
636   $main::lxdebug->enter_sub();
637
638   my $form     = $main::form;
639   my %myconfig = %main::myconfig;
640   my $locale   = $main::locale;
641
642   $main::auth->assert('invoice_edit');
643
644   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
645   $form->isblank("invdate",  $locale->text('Invoice Date missing!'));
646   $form->isblank("customer", $locale->text('Customer missing!'));
647   $form->error($locale->text('Cannot post invoice for a closed period!'))
648         if ($form->date_closed($form->{"invdate"}, \%myconfig));
649
650   $form->{invnumber} =~ s/^\s*//g;
651   $form->{invnumber} =~ s/\s*$//g;
652
653   # if oldcustomer ne customer redo form
654   if (&check_name('customer')) {
655     &update;
656     exit;
657   }
658   if ($form->{second_run}) {
659     $form->{print_and_post} = 0;
660   }
661
662   &validate_items;
663
664   my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
665   my $invdate  = $form->datetonum($form->{invdate},  \%myconfig);
666
667   $form->error($locale->text('Cannot post invoice for a closed period!'))
668     if ($invdate <= $closedto);
669
670   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
671     if ($form->{currency} ne $form->{defaultcurrency});
672
673   for my $i (1 .. $form->{paidaccounts}) {
674     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
675       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
676
677       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
678
679       $form->error($locale->text('Cannot post payment for a closed period!'))
680         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
681
682       if ($form->{currency} ne $form->{defaultcurrency}) {
683         $form->{"exchangerate_$i"} = $form->{exchangerate}
684           if ($invdate == $datepaid);
685         $form->isblank("exchangerate_$i",
686                        $locale->text('Exchangerate for payment missing!'));
687       }
688     }
689   }
690
691   ($form->{AR})        = split /--/, $form->{AR};
692   ($form->{AR_paid})   = split /--/, $form->{AR_paid};
693   $form->{storno}    ||= 0;
694
695   $form->{label} = $locale->text('Invoice');
696
697   $form->{id} = 0 if $form->{postasnew};
698
699   # get new invnumber in sequence if no invnumber is given or if posasnew was requested
700   if ($form->{postasnew}) {
701     if ($form->{type} eq "credit_note") {
702       undef($form->{cnnumber});
703     } else {
704       undef($form->{invnumber});
705     }
706   }
707
708   relink_accounts();
709   $form->error($locale->text('Cannot post invoice!'))
710     unless IS->post_invoice(\%myconfig, \%$form);
711   remove_draft() if $form->{remove_draft};
712
713   if(!exists $form->{addition}) {
714     $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
715     $form->{addition} = $print_post     ? "PRINTED AND POSTED" :
716                         $form->{storno} ? "STORNO"             :
717                                           "POSTED";
718     $form->save_history($form->dbconnect(\%myconfig));
719   }
720
721   $form->redirect( $form->{label} . " $form->{invnumber} " . $locale->text('posted!'))
722     unless $print_post;
723
724   $main::lxdebug->leave_sub();
725 }
726
727 sub print_and_post {
728   $main::lxdebug->enter_sub();
729
730   my $form     = $main::form;
731
732   $main::auth->assert('invoice_edit');
733
734   my $old_form               = new Form;
735   $print_post             = 1;
736   $form->{print_and_post} = 1;
737   &post();
738
739   &edit();
740   $main::lxdebug->leave_sub();
741
742 }
743
744 sub use_as_template {
745   $main::lxdebug->enter_sub();
746
747   my $form     = $main::form;
748   my %myconfig = %main::myconfig;
749
750   $main::auth->assert('invoice_edit');
751
752   map { delete $form->{$_} } qw(printed emailed queued invnumber invdate deliverydate id datepaid_1 source_1 memo_1 paid_1 exchangerate_1 AP_paid_1 storno);
753   $form->{paidaccounts} = 1;
754   $form->{rowcount}--;
755   $form->{invdate} = $form->current_date(\%myconfig);
756   &display_form;
757
758   $main::lxdebug->leave_sub();
759 }
760
761 sub storno {
762   $main::lxdebug->enter_sub();
763
764   my $form     = $main::form;
765   my %myconfig = %main::myconfig;
766   my $locale   = $main::locale;
767
768   $main::auth->assert('invoice_edit');
769
770   if ($form->{storno}) {
771     $form->error($locale->text('Cannot storno storno invoice!'));
772   }
773
774   if (IS->has_storno(\%myconfig, $form, "ar")) {
775     $form->error($locale->text("Invoice has already been storno'd!"));
776   }
777
778   map({ my $key = $_; delete($form->{$key}) unless (grep({ $key eq $_ } qw(id login password stylesheet type))); } keys(%{ $form }));
779
780   invoice_links();
781   prepare_invoice();
782   relink_accounts();
783
784   # Payments must not be recorded for the new storno invoice.
785   $form->{paidaccounts} = 0;
786   map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
787
788   $form->{storno_id} = $form->{id};
789   $form->{storno} = 1;
790   $form->{id} = "";
791   $form->{invnumber} = "Storno zu " . $form->{invnumber};
792   $form->{rowcount}++;
793
794   post();
795   $main::lxdebug->leave_sub();
796 }
797
798 sub preview {
799   $main::lxdebug->enter_sub();
800
801   my $form     = $main::form;
802
803   $main::auth->assert('invoice_edit');
804
805   $form->{preview} = 1;
806   my $old_form = new Form;
807   for (keys %$form) { $old_form->{$_} = $form->{$_} }
808
809   &print_form($old_form);
810   $main::lxdebug->leave_sub();
811
812 }
813
814 sub delete {
815   $main::lxdebug->enter_sub();
816
817   my $form     = $main::form;
818   my $locale   = $main::locale;
819
820   $main::auth->assert('invoice_edit');
821
822   if ($form->{second_run}) {
823     $form->{print_and_post} = 0;
824   }
825   $form->header;
826
827   print qq|
828 <body>
829
830 <form method="post" action="$form->{script}">
831 |;
832
833   # delete action variable
834   map { delete $form->{$_} } qw(action header);
835
836   foreach my $key (keys %$form) {
837     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
838     $form->{$key} =~ s/\"/&quot;/g;
839     print qq|<input type="hidden" name="$key" value="$form->{$key}">\n|;
840   }
841
842   print qq|
843 <h2 class="confirm">| . $locale->text('Confirm!') . qq|</h2>
844
845 <h4>|
846     . $locale->text('Are you sure you want to delete Invoice Number')
847     . qq| $form->{invnumber}
848 </h4>
849
850 <p>
851 <input name="action" class="submit" type="submit" value="|
852     . $locale->text('Yes') . qq|">
853 </form>
854 |;
855
856   $main::lxdebug->leave_sub();
857 }
858
859 sub credit_note {
860   $main::lxdebug->enter_sub();
861
862   my $form     = $main::form;
863   my %myconfig = %main::myconfig;
864   my $locale   = $main::locale;
865
866   $main::auth->assert('invoice_edit');
867
868   $form->{transdate} = $form->{invdate} = $form->current_date(\%myconfig);
869   $form->{duedate} =
870     $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
871
872   $form->{id}     = '';
873   $form->{rowcount}--;
874   $form->{shipto} = 1;
875
876
877   $form->{title}  = $locale->text('Add Credit Note');
878   $form->{script} = 'is.pl';
879   our $script         = "is";
880   our $buysell        = 'buy';
881
882
883   # bo creates the id, reset it
884   map { delete $form->{$_} }
885     qw(id invnumber subject message cc bcc printed emailed queued);
886   $form->{ $form->{vc} } =~ s/--.*//g;
887   $form->{type} = "credit_note";
888
889
890   map { $form->{"select$_"} = "" } ($form->{vc}, 'currency');
891
892   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
893     qw(creditlimit creditremaining);
894
895   my $currency = $form->{currency};
896   &invoice_links;
897
898   $form->{currency}     = $currency;
899   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, $buysell);
900   $form->{exchangerate} = $form->{forex} || '';
901
902   $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
903
904   &prepare_invoice;
905
906
907   &display_form;
908
909   $main::lxdebug->leave_sub();
910 }
911
912 sub yes {
913   $main::lxdebug->enter_sub();
914
915   my $form     = $main::form;
916   my %myconfig = %main::myconfig;
917   my $locale   = $main::locale;
918
919   $main::auth->assert('invoice_edit');
920
921   if (IS->delete_invoice(\%myconfig, \%$form, $main::spool)) {
922     # saving the history
923         if(!exists $form->{addition}) {
924     $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
925           $form->{addition} = "DELETED";
926           $form->save_history($form->dbconnect(\%myconfig));
927     }
928     # /saving the history
929     $form->redirect($locale->text('Invoice deleted!'));
930   }
931   $form->error($locale->text('Cannot delete invoice!'));
932
933   $main::lxdebug->leave_sub();
934 }
935
936 sub e_mail {
937   $main::lxdebug->enter_sub();
938
939   my $form     = $main::form;
940
941   $main::auth->assert('invoice_edit');
942
943   if (!$form->{id}) {
944     $print_post = 1;
945
946     my $saved_form = save_form();
947
948     post();
949
950     restore_form($saved_form, 0, qw(id invnumber));
951   }
952
953   edit_e_mail();
954
955   $main::lxdebug->leave_sub();
956 }