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