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