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