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