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