Die Hinweise in admin_create_dataset.html korrekt in T8 gesetzt, Übersetzungen geändert
[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
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 currency 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 currency 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         $form->{"acc_trans_id_$i"}    = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
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->{"gldate_$i"}       = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
203         $form->{"exchangerate_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
204         $form->{"forex_$i"}        = $form->{"exchangerate_$i"};
205         $form->{"source_$i"}       = $form->{acc_trans}{$key}->[$i - 1]->{source};
206         $form->{"memo_$i"}         = $form->{acc_trans}{$key}->[$i - 1]->{memo};
207
208         $form->{paidaccounts} = $i;
209       }
210     } else {
211       $form->{$key} = "$form->{acc_trans}{$key}->[0]->{accno}--$form->{acc_trans}{$key}->[0]->{description}";
212     }
213   }
214
215   $form->{paidaccounts} = 1 unless (exists $form->{paidaccounts});
216
217   $form->{AR} = $form->{AR_1} unless $form->{id};
218
219   $form->{locked} = ($form->datetonum($form->{invdate},  \%myconfig)
220                   <= $form->datetonum($form->{closedto}, \%myconfig));
221
222   $main::lxdebug->leave_sub();
223 }
224
225 sub prepare_invoice {
226   $main::lxdebug->enter_sub();
227
228   my $form     = $main::form;
229   my %myconfig = %main::myconfig;
230
231   $main::auth->assert('invoice_edit');
232
233   if ($form->{type} eq "credit_note") {
234     $form->{type}     = "credit_note";
235     $form->{formname} = "credit_note";
236   } else {
237     $form->{type}     = "invoice";
238     $form->{formname} = "invoice";
239   }
240
241   if ($form->{id}) {
242
243     my $i = 0;
244
245     foreach my $ref (@{ $form->{invoice_details} }) {
246       $i++;
247
248       map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
249
250       $form->{"discount_$i"}   = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100);
251       my ($dec)                = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
252       $dec                     = length $dec;
253       my $decimalplaces        = ($dec > 2) ? $dec : 2;
254
255       $form->{"sellprice_$i"}  = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
256       (my $dec_qty)            = ($form->{"qty_$i"} =~ /\.(\d+)/);
257       $dec_qty                 = length $dec_qty;
258
259       $form->{"lastcost_$i"}  = $form->format_amount(\%myconfig, $form->{"lastcost_$i"}, $decimalplaces);
260
261       $form->{"qty_$i"}        = $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
262
263       $form->{"sellprice_pg_$i"} = join ('--', $form->{"sellprice_$i"}, $form->{"pricegroup_id_$i"});
264
265       $form->{rowcount}        = $i;
266
267     }
268
269     # get pricegroups for parts
270     IS->get_pricegroups_for_parts(\%myconfig, \%$form);
271
272     # Problem: set_pricegroup resets the sellprice of old invoices to the price
273     # currently defined in the pricegroup, which is a problem if the price has
274     # changed, as the old invoice gets the new price
275     # set_pricegroup must never be called, when an old invoice is initially loaded
276
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      = $::request->{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 @old_project_ids = ($form->{"globalproject_id"});
301   map { push @old_project_ids, $form->{"project_id_$_"} if $form->{"project_id_$_"}; } 1..$form->{"rowcount"};
302
303   $form->get_lists("contacts"      => "ALL_CONTACTS",
304                    "shipto"        => "ALL_SHIPTO",
305                    "projects"      => { "key"    => "ALL_PROJECTS",
306                                         "all"    => 0,
307                                         "old_id" => \@old_project_ids },
308                    "employees"     => "ALL_EMPLOYEES",
309                    "salesmen"      => "ALL_SALESMEN",
310                    "taxzones"      => "ALL_TAXZONES",
311                    "currencies"    => "ALL_CURRENCIES",
312                    "customers"     => "ALL_CUSTOMERS",
313                    "departments"   => "all_departments",
314                    "price_factors" => "ALL_PRICE_FACTORS");
315
316   $TMPL_VAR{sales_employee_labels} = sub { $_[0]->{name} || $_[0]->{login} };
317   $TMPL_VAR{shipto_labels}         = sub { join "; ", grep { $_ } map { $_[0]->{"shipto${_}" } } qw(name department_1 street city) };
318   $TMPL_VAR{contact_labels}        = sub { join(', ', $_[0]->{"cp_name"}, $_[0]->{"cp_givenname"}) . ($_[0]->{cp_abteilung} ? " ($_[0]->{cp_abteilung})" : "") };
319   $TMPL_VAR{department_labels}     = sub { "$_[0]->{description}--$_[0]->{id}" };
320
321   # customer
322   $TMPL_VAR{vc_keys} = sub { "$_[0]->{name}--$_[0]->{id}" };
323   $TMPL_VAR{vclimit} = $myconfig{vclimit};
324   $TMPL_VAR{vc_select} = "customer_or_vendor_selection_window('customer', '', 0, 0)";
325   push @custom_hiddens, "customer_id";
326   push @custom_hiddens, "oldcustomer";
327   push @custom_hiddens, "selectcustomer";
328
329   # currencies and exchangerate
330   my @values = map { $_       } @{ $form->{ALL_CURRENCIES} };
331   my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
332   $form->{currency}            = $form->{defaultcurrency} unless $form->{currency};
333   $form->{show_exchangerate}   = $form->{currency} ne $form->{defaultcurrency};
334   $TMPL_VAR{currencies}        = NTI($::request->{cgi}->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
335                                                       '-values' => \@values, '-labels' => \%labels,
336                                                       '-onchange' => "document.getElementById('update_button').click();"
337                                      )) 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  shiptocp_gender 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
391   # note rows
392   $form->{rows} = max 2,
393     $form->numtextrows($form->{notes},    26, 8),
394     $form->numtextrows($form->{intnotes}, 35, 8);
395
396
397   # tax, total and subtotal calculations
398   my ($tax, $subtotal);
399   $form->{taxaccounts_array} = [ split / /, $form->{taxaccounts} ];
400
401   foreach my $item (@{ $form->{taxaccounts_array} }) {
402     if ($form->{"${item}_base"}) {
403       if ($form->{taxincluded}) {
404         $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
405                                                                                  / (1 + $form->{"${item}_rate"})), 2);
406         $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
407       } else {
408         $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
409         $form->{invtotal} += $form->{"${item}_total"};
410       }
411     }
412   }
413
414   # follow ups
415   if ($form->{id}) {
416     $form->{follow_ups}            = FU->follow_ups('trans_id' => $form->{id}) || [];
417     $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
418   }
419
420   # payments
421   my $totalpaid = 0;
422   $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
423   $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
424
425   # Standard Konto für Umlaufvermögen
426   my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
427
428   for my $i (1 .. $form->{paidaccounts}) {
429     $form->{"changeable_$i"} = 1;
430     if ($::lx_office_conf{features}->{payments_changeable} == 0) {
431       # never
432       $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
433     } elsif ($::lx_office_conf{features}->{payments_changeable} == 2) {
434       # on the same day
435       $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
436                                   ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
437     }
438
439     $form->{"selectAR_paid_$i"} = $form->{selectAR_paid};
440     if (!$form->{"AR_paid_$i"}) {
441       $form->{"selectAR_paid_$i"} =~ s/option>$accno_arap--(.*?)</option selected>$accno_arap--$1</;
442     } else {
443       $form->{"selectAR_paid_$i"} =~ s/option>\Q$form->{"AR_paid_$i"}\E/option selected>$form->{"AR_paid_$i"}/;
444     }
445
446     $totalpaid += $form->{"paid_$i"};
447   }
448
449   $form->{oldinvtotal} = $form->{invtotal};
450
451   print $form->parse_html_template('is/form_footer', {
452     is_type_credit_note => ($form->{type} eq "credit_note"),
453     totalpaid           => $totalpaid,
454     paid_missing        => $form->{invtotal} - $totalpaid,
455     print_options       => print_options(inline => 1),
456     show_storno         => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ar") && !$totalpaid,
457     show_delete         => ($form->current_date(\%myconfig) eq $form->{gldate}),
458   });
459 ##print $form->parse_html_template('is/_payments'); # parser
460 ##print $form->parse_html_template('webdav/_list'); # parser
461
462   $main::lxdebug->leave_sub();
463 }
464
465 sub mark_as_paid {
466   $main::lxdebug->enter_sub();
467
468   my $form     = $main::form;
469   my %myconfig = %main::myconfig;
470
471   $main::auth->assert('invoice_edit');
472
473   &mark_as_paid_common(\%myconfig,"ar");
474
475   $main::lxdebug->leave_sub();
476 }
477
478 sub update {
479   $main::lxdebug->enter_sub();
480
481   my $form     = $main::form;
482   my %myconfig = %main::myconfig;
483
484   $main::auth->assert('invoice_edit');
485
486   my ($recursive_call) = @_;
487
488   $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate}) unless $recursive_call;
489
490   $form->{print_and_post} = 0         if $form->{second_run};
491   my $taxincluded         = $form->{taxincluded} ? "checked" : '';
492   $form->{update} = 1;
493
494   &check_name("customer");
495
496   $form->{taxincluded} ||= $taxincluded;
497
498   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
499   $form->{exchangerate} = $form->{forex} if $form->{forex};
500
501   for my $i (1 .. $form->{paidaccounts}) {
502     next unless $form->{"paid_$i"};
503     map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
504     $form->{"forex_$i"}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
505     $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
506   }
507
508   my $i            = $form->{rowcount};
509   my $exchangerate = $form->{exchangerate} || 1;
510
511   # if last row empty, check the form otherwise retrieve new item
512   if (   ($form->{"partnumber_$i"} eq "")
513       && ($form->{"description_$i"} eq "")
514       && ($form->{"partsgroup_$i"}  eq "")) {
515
516     $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
517     &check_form;
518
519   } else {
520
521     IS->retrieve_item(\%myconfig, \%$form);
522
523     my $rows = scalar @{ $form->{item_list} };
524
525     # Falls kein Kundenrabatt vorhanden ist, den aktuellen Rabatt nicht mit 0% überschreiben,
526     # da hier der Anwender schon manual einen Wert eingetragen haben könnte (analog zu qty) Bugfix: 1412
527     if ($form->{customer_discount}){
528       $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{customer_discount} * 100);
529     }
530
531     if ($rows) {
532       $form->{"qty_$i"} = ($form->{"qty_$i"} * 1) ? $form->{"qty_$i"} : 1;
533
534       if ($rows > 1) {
535
536         select_item(mode => 'IS');
537         ::end_of_request();
538
539       } else {
540
541         my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
542
543         map { $form->{item_list}[$i]{$_} =~ s/\"/&quot;/g } qw(partnumber description unit);
544         map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
545
546         $form->{payment_id}    = $form->{"part_payment_id_$i"} if $form->{"part_payment_id_$i"} ne "";
547         $form->{"discount_$i"} = 0                             if $form->{"not_discountable_$i"};
548
549         $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
550
551         ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
552         my $decimalplaces = max 2, length $1;
553
554         if ($sellprice) {
555           $form->{"sellprice_$i"} = $sellprice;
556         } else {
557           # if there is an exchange rate adjust sellprice
558           $form->{"sellprice_$i"} *= (1 - $form->{tradediscount});
559           $form->{"sellprice_$i"} /= $exchangerate;
560         }
561
562         $form->{"listprice_$i"} /= $exchangerate;
563
564         my $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"} / 100);
565         map { $form->{"${_}_base"} = 0 }                                 split / /, $form->{taxaccounts};
566         map { $form->{"${_}_base"} += $amount }                          split / /, $form->{"taxaccounts_$i"};
567         map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{"taxaccounts_$i"} if !$form->{taxincluded};
568
569         $form->{creditremaining} -= $amount;
570
571         map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces) } qw(sellprice listprice lastcost);
572
573         $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"});
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 gldate_1 acc_trans_id_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_ gldate_ acc_trans_id_ 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->{"gldate_$i"};
949     delete $form->{"acc_trans_id_$i"};
950     delete $form->{"AR_paid_$i"};
951   };
952   $form->{paidaccounts} = 1;
953
954   &prepare_invoice;
955
956
957   &display_form;
958
959   $main::lxdebug->leave_sub();
960 }
961
962 sub yes {
963   $main::lxdebug->enter_sub();
964
965   my $form     = $main::form;
966   my %myconfig = %main::myconfig;
967   my $locale   = $main::locale;
968
969   $main::auth->assert('invoice_edit');
970
971   if (IS->delete_invoice(\%myconfig, \%$form)) {
972     # saving the history
973     if(!exists $form->{addition}) {
974     $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
975       $form->{addition} = "DELETED";
976       $form->save_history;
977     }
978     # /saving the history
979     $form->redirect($locale->text('Invoice deleted!'));
980   }
981   $form->error($locale->text('Cannot delete invoice!'));
982
983   $main::lxdebug->leave_sub();
984 }
985
986 sub e_mail {
987   $main::lxdebug->enter_sub();
988
989   my $form     = $main::form;
990
991   $main::auth->assert('invoice_edit');
992
993   if (!$form->{id}) {
994     $form->{no_redirect_after_post} = 1;
995
996     my $saved_form = save_form();
997
998     post();
999
1000     restore_form($saved_form, 0, qw(id invnumber));
1001   }
1002
1003   edit_e_mail();
1004
1005   $main::lxdebug->leave_sub();
1006 }