Zusätzliche Auftragsfelder beim Laden von Rechnungen holen.
[kivitendo-erp.git] / bin / mozilla / is.pl
1 #=====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (c) 1998-2002
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 #
16 # This program is free software; you can redistribute it and/or modify
17 # it under the terms of the GNU General Public License as published by
18 # the Free Software Foundation; either version 2 of the License, or
19 # (at your option) any later version.
20 #
21 # This program is distributed in the hope that it will be useful,
22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 # GNU General Public License for more details.
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28 #======================================================================
29 #
30 # Inventory invoicing module
31 #
32 #======================================================================
33
34 use SL::FU;
35 use SL::IS;
36 use SL::PE;
37 use Data::Dumper;
38 use List::Util qw(max sum);
39
40 require "bin/mozilla/io.pl";
41 require "bin/mozilla/invoice_io.pl";
42 require "bin/mozilla/arap.pl";
43 require "bin/mozilla/drafts.pl";
44
45 use strict;
46
47 my $edit;
48 my $print_post;
49
50 1;
51
52 # end of main
53
54 sub add {
55   $main::lxdebug->enter_sub();
56
57   my $form     = $main::form;
58   my $locale   = $main::locale;
59
60   $main::auth->assert('invoice_edit');
61
62   return $main::lxdebug->leave_sub() if (load_draft_maybe());
63
64   if ($form->{type} eq "credit_note") {
65     $form->{title} = $locale->text('Add Credit Note');
66
67     if ($form->{storno}) {
68       $form->{title} = $locale->text('Add Storno Credit Note');
69     }
70   } else {
71     $form->{title} = $locale->text('Add Sales Invoice');
72
73   }
74
75
76   $form->{callback} = "$form->{script}?action=add&type=$form->{type}" unless $form->{callback};
77
78   $form->{jsscript} = "date";
79
80   &invoice_links;
81   &prepare_invoice;
82   &display_form;
83
84   $main::lxdebug->leave_sub();
85 }
86
87 sub edit {
88   $main::lxdebug->enter_sub();
89
90   my $form     = $main::form;
91   my $locale   = $main::locale;
92
93   $main::auth->assert('invoice_edit');
94
95   # show history button
96   $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
97   #/show hhistory button
98
99   if ($form->{type} eq "credit_note") {
100     $form->{title} = $locale->text('Edit Credit Note');
101     $form->{title} = $locale->text('Edit Storno Credit Note') if $form->{storno};
102   } else {
103     $form->{title} = $locale->text('Edit Sales Invoice');
104     $form->{title} = $locale->text('Edit Storno Invoice')     if $form->{storno};
105   }
106
107   my ($language_id, $printer_id);
108   if ($form->{print_and_post}) {
109     $form->{action}   = "print";
110     $form->{resubmit} = 1;
111     $language_id = $form->{language_id};
112     $printer_id = $form->{printer_id};
113   }
114   &invoice_links;
115   &prepare_invoice;
116   if ($form->{print_and_post}) {
117     $form->{language_id} = $language_id;
118     $form->{printer_id} = $printer_id;
119   }
120
121   &display_form;
122
123   $main::lxdebug->leave_sub();
124 }
125
126 sub invoice_links {
127   $main::lxdebug->enter_sub();
128
129   my $form     = $main::form;
130   my %myconfig = %main::myconfig;
131
132   $main::auth->assert('invoice_edit');
133
134   $form->{vc} = 'customer';
135
136   # create links
137   $form->{webdav}   = $main::webdav;
138   $form->{lizenzen} = $main::lizenzen;
139
140   $form->create_links("AR", \%myconfig, "customer");
141
142   if ($form->{all_customer}) {
143     unless ($form->{customer_id}) {
144       $form->{customer_id} = $form->{all_customer}->[0]->{id};
145       $form->{salesman_id} = $form->{all_customer}->[0]->{salesman_id};
146     }
147   }
148
149   $form->backup_vars(qw(payment_id language_id taxzone_id salesman_id taxincluded cp_id intnotes id shipto_id));
150
151   IS->get_customer(\%myconfig, \%$form);
152
153   #quote all_customer Bug 133
154   foreach my $ref (@{ $form->{all_customer} }) {
155     $ref->{name} = $form->quote($ref->{name});
156   }
157
158   # Load data for a specific order and update form fields
159   my $order_data = IS->get_order_data();
160
161   # Copy the fields we need to %form
162   for my $key (qw(payment_id salesman_id orddate taxzone_id quonumber)) {
163     $form->{$key} = $order_data->{$key};
164   }
165
166   $form->restore_vars(qw(id));
167
168   IS->retrieve_invoice(\%myconfig, \%$form);
169   $form->restore_vars(qw(payment_id language_id taxzone_id intnotes cp_id shipto_id));
170   $form->restore_vars(qw(taxincluded)) if $form->{id};
171   $form->restore_vars(qw(salesman_id)) if $main::editing;
172
173
174   # build vendor/customer drop down comatibility... don't ask
175   if (@{ $form->{"all_customer"} }) {
176     $form->{"selectcustomer"} = 1;
177     $form->{customer}         = qq|$form->{customer}--$form->{"customer_id"}|;
178   }
179
180   $form->{"oldcustomer"}  = $form->{customer};
181
182   if ($form->{"oldcustomer"} !~ m/--\d+$/ && $form->{"customer_id"}) {
183     $form->{"oldcustomer"} .= qq|--$form->{"customer_id"}|
184   }
185
186
187 #  $form->{oldcustomer} = "$form->{customer}--$form->{customer_id}";
188 #  $form->{selectcustomer} = 1;
189
190   $form->{employee} = "$form->{employee}--$form->{employee_id}";
191
192   # forex
193   $form->{forex} = $form->{exchangerate};
194   my $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
195
196   foreach my $key (keys %{ $form->{AR_links} }) {
197     foreach my $ref (@{ $form->{AR_links}{$key} }) {
198       $form->{"select$key"} .= "<option>$ref->{accno}--$ref->{description}</option>\n";
199     }
200
201     if ($key eq "AR_paid") {
202       next unless $form->{acc_trans}{$key};
203       for my $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
204         $form->{"AR_paid_$i"}      = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
205
206         # reverse paid
207         $form->{"paid_$i"}         = $form->{acc_trans}{$key}->[$i - 1]->{amount} * -1;
208         $form->{"datepaid_$i"}     = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
209         $form->{"exchangerate_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
210         $form->{"forex_$i"}        = $form->{"exchangerate_$i"};
211         $form->{"source_$i"}       = $form->{acc_trans}{$key}->[$i - 1]->{source};
212         $form->{"memo_$i"}         = $form->{acc_trans}{$key}->[$i - 1]->{memo};
213
214         $form->{paidaccounts} = $i;
215       }
216     } else {
217       $form->{$key} = "$form->{acc_trans}{$key}->[0]->{accno}--$form->{acc_trans}{$key}->[0]->{description}";
218     }
219   }
220
221   $form->{paidaccounts} = 1 unless (exists $form->{paidaccounts});
222
223   $form->{AR} = $form->{AR_1} unless $form->{id};
224
225   $form->{locked} = ($form->datetonum($form->{invdate},  \%myconfig)
226                   <= $form->datetonum($form->{closedto}, \%myconfig));
227
228   $main::lxdebug->leave_sub();
229 }
230
231 sub prepare_invoice {
232   $main::lxdebug->enter_sub();
233
234   my $form     = $main::form;
235   my %myconfig = %main::myconfig;
236
237   $main::auth->assert('invoice_edit');
238
239   if ($form->{type} eq "credit_note") {
240     $form->{type}     = "credit_note";
241     $form->{formname} = "credit_note";
242   } else {
243     $form->{type}     = "invoice";
244     $form->{formname} = "invoice";
245   }
246
247   if ($form->{id}) {
248
249     my $i = 0;
250
251     foreach my $ref (@{ $form->{invoice_details} }) {
252       $i++;
253
254       map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
255
256       $form->{"discount_$i"}   = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100);
257       my ($dec)                = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
258       $dec                     = length $dec;
259       my $decimalplaces        = ($dec > 2) ? $dec : 2;
260
261       $form->{"sellprice_$i"}  = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
262       (my $dec_qty)            = ($form->{"qty_$i"} =~ /\.(\d+)/);
263       $dec_qty                 = length $dec_qty;
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   our %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   $form->{radier}          = ($form->current_date(\%myconfig) eq $form->{gldate}) ? 1 : 0;
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                    "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         exit;
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);
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   our $invdate;
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     exit;
653   }
654   if ($form->{second_run}) {
655     $form->{print_and_post} = 0;
656   }
657
658   &validate_items;
659
660   my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
661   my $invdate  = $form->datetonum($form->{invdate},  \%myconfig);
662
663   $form->error($locale->text('Cannot post invoice for a closed period!'))
664     if ($invdate <= $closedto);
665
666   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
667     if ($form->{currency} ne $form->{defaultcurrency});
668
669   for my $i (1 .. $form->{paidaccounts}) {
670     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
671       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
672
673       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
674
675       $form->error($locale->text('Cannot post payment for a closed period!'))
676         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
677
678       if ($form->{currency} ne $form->{defaultcurrency}) {
679         $form->{"exchangerate_$i"} = $form->{exchangerate}
680           if ($invdate == $datepaid);
681         $form->isblank("exchangerate_$i",
682                        $locale->text('Exchangerate for payment missing!'));
683       }
684     }
685   }
686
687   ($form->{AR})        = split /--/, $form->{AR};
688   ($form->{AR_paid})   = split /--/, $form->{AR_paid};
689   $form->{storno}    ||= 0;
690
691   $form->{label} = $locale->text('Invoice');
692
693   $form->{id} = 0 if $form->{postasnew};
694
695   # get new invnumber in sequence if no invnumber is given or if posasnew was requested
696   if ($form->{postasnew}) {
697     if ($form->{type} eq "credit_note") {
698       undef($form->{cnnumber});
699     } else {
700       undef($form->{invnumber});
701     }
702   }
703
704   relink_accounts();
705   $form->error($locale->text('Cannot post invoice!'))
706     unless IS->post_invoice(\%myconfig, \%$form);
707   remove_draft() if $form->{remove_draft};
708
709   if(!exists $form->{addition}) {
710     $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
711     $form->{addition} = $print_post     ? "PRINTED AND POSTED" :
712                         $form->{storno} ? "STORNO"             :
713                                           "POSTED";
714     $form->save_history($form->dbconnect(\%myconfig));
715   }
716
717   $form->redirect( $form->{label} . " $form->{invnumber} " . $locale->text('posted!'))
718     unless $print_post;
719
720   $main::lxdebug->leave_sub();
721 }
722
723 sub print_and_post {
724   $main::lxdebug->enter_sub();
725
726   my $form     = $main::form;
727
728   $main::auth->assert('invoice_edit');
729
730   my $old_form               = new Form;
731   $print_post             = 1;
732   $form->{print_and_post} = 1;
733   &post();
734
735   &edit();
736   $main::lxdebug->leave_sub();
737
738 }
739
740 sub use_as_template {
741   $main::lxdebug->enter_sub();
742
743   my $form     = $main::form;
744   my %myconfig = %main::myconfig;
745
746   $main::auth->assert('invoice_edit');
747
748   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);
749   $form->{paidaccounts} = 1;
750   $form->{rowcount}--;
751   $form->{invdate} = $form->current_date(\%myconfig);
752   &display_form;
753
754   $main::lxdebug->leave_sub();
755 }
756
757 sub storno {
758   $main::lxdebug->enter_sub();
759
760   my $form     = $main::form;
761   my %myconfig = %main::myconfig;
762   my $locale   = $main::locale;
763
764   $main::auth->assert('invoice_edit');
765
766   if ($form->{storno}) {
767     $form->error($locale->text('Cannot storno storno invoice!'));
768   }
769
770   if (IS->has_storno(\%myconfig, $form, "ar")) {
771     $form->error($locale->text("Invoice has already been storno'd!"));
772   }
773
774   map({ my $key = $_; delete($form->{$key}) unless (grep({ $key eq $_ } qw(id login password stylesheet type))); } keys(%{ $form }));
775
776   invoice_links();
777   prepare_invoice();
778   relink_accounts();
779
780   # Payments must not be recorded for the new storno invoice.
781   $form->{paidaccounts} = 0;
782   map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
783
784   $form->{storno_id} = $form->{id};
785   $form->{storno} = 1;
786   $form->{id} = "";
787   $form->{invnumber} = "Storno zu " . $form->{invnumber};
788   $form->{rowcount}++;
789
790   post();
791   $main::lxdebug->leave_sub();
792 }
793
794 sub preview {
795   $main::lxdebug->enter_sub();
796
797   my $form     = $main::form;
798
799   $main::auth->assert('invoice_edit');
800
801   $form->{preview} = 1;
802   my $old_form = new Form;
803   for (keys %$form) { $old_form->{$_} = $form->{$_} }
804
805   &print_form($old_form);
806   $main::lxdebug->leave_sub();
807
808 }
809
810 sub delete {
811   $main::lxdebug->enter_sub();
812
813   my $form     = $main::form;
814   my $locale   = $main::locale;
815
816   $main::auth->assert('invoice_edit');
817
818   if ($form->{second_run}) {
819     $form->{print_and_post} = 0;
820   }
821   $form->header;
822
823   print qq|
824 <body>
825
826 <form method="post" action="$form->{script}">
827 |;
828
829   # delete action variable
830   map { delete $form->{$_} } qw(action header);
831
832   foreach my $key (keys %$form) {
833     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
834     $form->{$key} =~ s/\"/&quot;/g;
835     print qq|<input type="hidden" name="$key" value="$form->{$key}">\n|;
836   }
837
838   print qq|
839 <h2 class="confirm">| . $locale->text('Confirm!') . qq|</h2>
840
841 <h4>|
842     . $locale->text('Are you sure you want to delete Invoice Number')
843     . qq| $form->{invnumber}
844 </h4>
845
846 <p>
847 <input name="action" class="submit" type="submit" value="|
848     . $locale->text('Yes') . qq|">
849 </form>
850 |;
851
852   $main::lxdebug->leave_sub();
853 }
854
855 sub credit_note {
856   $main::lxdebug->enter_sub();
857
858   my $form     = $main::form;
859   my %myconfig = %main::myconfig;
860   my $locale   = $main::locale;
861
862   $main::auth->assert('invoice_edit');
863
864   $form->{transdate} = $form->{invdate} = $form->current_date(\%myconfig);
865   $form->{duedate} =
866     $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
867
868   $form->{id}     = '';
869   $form->{rowcount}--;
870   $form->{shipto} = 1;
871
872
873   $form->{title}  = $locale->text('Add Credit Note');
874   $form->{script} = 'is.pl';
875   our $script         = "is";
876   our $buysell        = 'buy';
877
878
879   # bo creates the id, reset it
880   map { delete $form->{$_} }
881     qw(id invnumber subject message cc bcc printed emailed queued);
882   $form->{ $form->{vc} } =~ s/--.*//g;
883   $form->{type} = "credit_note";
884
885
886   map { $form->{"select$_"} = "" } ($form->{vc}, 'currency');
887
888 #  map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
889 #    qw(creditlimit creditremaining);
890
891   my $currency = $form->{currency};
892   &invoice_links;
893
894   $form->{currency}     = $currency;
895   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, $buysell);
896   $form->{exchangerate} = $form->{forex} || '';
897
898   $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
899
900   &prepare_invoice;
901
902
903   &display_form;
904
905   $main::lxdebug->leave_sub();
906 }
907
908 sub yes {
909   $main::lxdebug->enter_sub();
910
911   my $form     = $main::form;
912   my %myconfig = %main::myconfig;
913   my $locale   = $main::locale;
914
915   $main::auth->assert('invoice_edit');
916
917   if (IS->delete_invoice(\%myconfig, \%$form, $main::spool)) {
918     # saving the history
919         if(!exists $form->{addition}) {
920     $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
921           $form->{addition} = "DELETED";
922           $form->save_history($form->dbconnect(\%myconfig));
923     }
924     # /saving the history
925     $form->redirect($locale->text('Invoice deleted!'));
926   }
927   $form->error($locale->text('Cannot delete invoice!'));
928
929   $main::lxdebug->leave_sub();
930 }
931
932 sub e_mail {
933   $main::lxdebug->enter_sub();
934
935   my $form     = $main::form;
936
937   $main::auth->assert('invoice_edit');
938
939   if (!$form->{id}) {
940     $print_post = 1;
941
942     my $saved_form = save_form();
943
944     post();
945
946     restore_form($saved_form, 0, qw(id invnumber));
947   }
948
949   edit_e_mail();
950
951   $main::lxdebug->leave_sub();
952 }