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