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