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