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