1ec0ca44970b7f8dc3a5ddd44de2ae99459c9c1a
[kivitendo-erp.git] / bin / mozilla / io.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 # Veraendert 2005-01-05 - Marco Welter <mawe@linux-studio.de> - Neue Optik  #
8 #############################################################################
9 # SQL-Ledger, Accounting
10 # Copyright (c) 1998-2002
11 #
12 #  Author: Dieter Simader
13 #   Email: dsimader@sql-ledger.org
14 #     Web: http://www.sql-ledger.org
15 #
16 #
17 # This program is free software; you can redistribute it and/or modify
18 # it under the terms of the GNU General Public License as published by
19 # the Free Software Foundation; either version 2 of the License, or
20 # (at your option) any later version.
21 #
22 # This program is distributed in the hope that it will be useful,
23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25 # GNU General Public License for more details.
26 # You should have received a copy of the GNU General Public License
27 # along with this program; if not, write to the Free Software
28 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 #
30 #######################################################################
31 #
32 # common routines used in is, ir, oe
33 #
34 #######################################################################
35
36 use CGI;
37 use CGI::Ajax;
38 use List::Util qw(max);
39
40 use SL::Common;
41 use SL::CT;
42 use SL::IC;
43
44 require "bin/mozilla/common.pl";
45
46 # any custom scripts for this one
47 if (-f "bin/mozilla/custom_io.pl") {
48   eval { require "bin/mozilla/custom_io.pl"; };
49 }
50 if (-f "bin/mozilla/$form->{login}_io.pl") {
51   eval { require "bin/mozilla/$form->{login}_io.pl"; };
52 }
53
54 1;
55
56 # end of main
57
58 # this is for our long dates
59 # $locale->text('January')
60 # $locale->text('February')
61 # $locale->text('March')
62 # $locale->text('April')
63 # $locale->text('May ')
64 # $locale->text('June')
65 # $locale->text('July')
66 # $locale->text('August')
67 # $locale->text('September')
68 # $locale->text('October')
69 # $locale->text('November')
70 # $locale->text('December')
71
72 # this is for our short month
73 # $locale->text('Jan')
74 # $locale->text('Feb')
75 # $locale->text('Mar')
76 # $locale->text('Apr')
77 # $locale->text('May')
78 # $locale->text('Jun')
79 # $locale->text('Jul')
80 # $locale->text('Aug')
81 # $locale->text('Sep')
82 # $locale->text('Oct')
83 # $locale->text('Nov')
84 # $locale->text('Dec')
85 use SL::IS;
86 use SL::PE;
87 use SL::AM;
88 use Data::Dumper;
89 ########################################
90 # Eintrag fuer Version 2.2.0 geaendert #
91 # neue Optik im Rechnungsformular      #
92 ########################################
93
94 ##################################################
95 # build html-code for pricegroups in variable $form->{prices_$j}
96
97 sub set_pricegroup {
98   $lxdebug->enter_sub();
99   my $rowcount = shift;
100   for $j (1 .. $rowcount) {
101     next unless $form->{PRICES}{$j};
102     # build drop down list for pricegroups
103     my $option_tmpl = qq|<option value="%s--%s" %s>%s</option>|;
104     $form->{"prices_$j"}  = join '', map { sprintf $option_tmpl, @$_{qw(price pricegroup_id selected pricegroup)} } 
105                                          (+{ pricegroup => $locale->text("none (pricegroup)") }, @{ $form->{PRICES}{$j} });
106
107     foreach $item (@{ $form->{PRICES}{$j} }) {
108       # set new selectedpricegroup_id and prices for "Preis"
109       $form->{"pricegroup_old_$j"} = $item->{pricegroup_id}   if $item->{selected} &&  $item->{pricegroup_id};
110       $form->{"sellprice_$j"}      = $item->{price}           if $item->{selected} &&  $item->{pricegroup_id};
111       $form->{"price_new_$j"}      = $form->{"sellprice_$j"}  if $item->{selected} || !$item->{pricegroup_id};
112     }
113   }
114   $lxdebug->leave_sub();
115 }
116
117 sub select_item {
118   $lxdebug->enter_sub();
119   @column_index = qw(ndx partnumber description onhand unit sellprice);
120
121   $column_data{ndx}        = qq|<th>&nbsp;</th>|;
122   $column_data{partnumber} =
123     qq|<th class="listheading">| . $locale->text('Number') . qq|</th>|;
124   $column_data{description} =
125     qq|<th class="listheading">| . $locale->text('Part Description') . qq|</th>|;
126   $column_data{sellprice} =
127     qq|<th class="listheading">| . $locale->text('Price') . qq|</th>|;
128   $column_data{onhand} =
129     qq|<th class="listheading">| . $locale->text('Qty') . qq|</th>|;
130   $column_data{unit} =
131     qq|<th class="listheading">| . $locale->text('Unit') . qq|</th>|;
132   # list items with radio button on a form
133   $form->header;
134
135   $title   = $locale->text('Select from one of the items below');
136   $colspan = $#column_index + 1;
137
138   print qq|
139   <body>
140
141 <form method="post" action="$form->{script}">
142
143 <table width="100%">
144   <tr>
145     <th class="listtop" colspan="$colspan">$title</th>
146   </tr>
147   <tr height="5"></tr>
148   <tr class="listheading">|;
149
150   map { print "\n$column_data{$_}" } @column_index;
151
152   print qq|</tr>|;
153
154   my $i = 0;
155   foreach $ref (@{ $form->{item_list} }) {
156     $checked = ($i++) ? "" : "checked";
157
158     if ($lizenzen) {
159       if ($ref->{inventory_accno} > 0) {
160         $ref->{"lizenzen"} = qq|<option></option>|;
161         foreach $item (@{ $form->{LIZENZEN}{ $ref->{"id"} } }) {
162           $ref->{"lizenzen"} .=
163             qq|<option value=\"$item->{"id"}\">$item->{"licensenumber"}</option>|;
164         }
165         $ref->{"lizenzen"} .= qq|<option value="-1">Neue Lizenz</option>|;
166         $ref->{"lizenzen"} =~ s/\"/&quot;/g;
167       }
168     }
169
170     map { $ref->{$_} =~ s/\"/&quot;/g } qw(partnumber description unit);
171
172     my $display_sellprice  = $ref->{sellprice} * (1 - $form->{tradediscount});
173     $display_sellprice    /= $ref->{price_factor} if ($ref->{price_factor});
174     $display_sellprice     = $form->format_amount(\%myconfig, $display_sellprice, 2);
175
176     $column_data{ndx} =
177       qq|<td><input name="ndx" class="radio" type="radio" value="$i" $checked></td>|;
178     $column_data{partnumber} =
179       qq|<td><input name="new_partnumber_$i" type="hidden" value="$ref->{partnumber}">$ref->{partnumber}</td>|;
180     $column_data{description} =
181       qq|<td><input name="new_description_$i" type="hidden" value="$ref->{description}">$ref->{description}</td>|;
182     $column_data{sellprice} =
183       qq|<td align="right"><input name="new_sellprice_$i" type="hidden" value="$ref->{sellprice}">|
184       . $display_sellprice
185       . qq|</td>|;
186     $column_data{onhand} =
187       qq|<td align="right"><input name="new_onhand_$i" type="hidden" value="$ref->{onhand}">|
188       . $form->format_amount(\%myconfig, $ref->{onhand}, '', "&nbsp;")
189       . qq|</td>|;
190     $column_data{unit} =
191       qq|<td>$ref->{unit}</td>|;
192     $j++;
193     $j %= 2;
194     print qq|
195 <tr class=listrow$j>|;
196
197     map { print "\n$column_data{$_}" } @column_index;
198
199     print("</tr>\n");
200
201     my @new_fields =
202       qw(bin listprice inventory_accno income_accno expense_accno unit weight
203          assembly taxaccounts partsgroup formel longdescription not_discountable
204          part_payment_id partnotes id lastcost price_factor_id price_factor);
205     push(@new_fields, "lizenzen") if ($lizenzen);
206
207     print join "\n", map { $cgi->hidden("-name" => "new_${_}_$i", "-value" => $ref->{$_}) } @new_fields;
208     print "\n";
209   }
210
211   print qq|
212 <tr><td colspan="8"><hr size="3" noshade></td></tr>
213 </table>
214
215 <input name="lastndx" type="hidden" value="$i">
216
217 |;
218
219   # delete action variable
220   map { delete $form->{$_} } qw(action item_list header);
221
222   # save all other form variables
223   foreach $key (keys %${form}) {
224     $form->{$key} =~ s/\"/&quot;/g;
225     print qq|<input name="$key" type="hidden" value="$form->{$key}">\n|;
226   }
227
228   print qq|
229 <input type="hidden" name="nextsub" value="item_selected">
230
231 <br>
232 <input class="submit" type="submit" name="action" value="|
233     . $locale->text('Continue') . qq|">
234 </form>
235
236 </body>
237 </html>
238 |;
239
240   $lxdebug->leave_sub();
241 }
242
243 sub item_selected {
244   $lxdebug->enter_sub();
245
246   # replace the last row with the checked row
247   $i = $form->{rowcount};
248   $i = $form->{assembly_rows} if ($form->{item} eq 'assembly');
249
250   # index for new item
251   $j = $form->{ndx};
252
253   #sk
254   #($form->{"sellprice_$i"},$form->{"$pricegroup_old_$i"}) = split /--/, $form->{"sellprice_$i"};
255   #$form->{"sellprice_$i"} = $form->{"sellprice_$i"};
256
257   # if there was a price entered, override it
258   $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
259
260   my @new_fields =
261     qw(id partnumber description sellprice listprice inventory_accno
262        income_accno expense_accno bin unit weight assembly taxaccounts
263        partsgroup formel longdescription not_discountable partnotes lastcost
264        price_factor_id price_factor);
265
266   map { $form->{"${_}_$i"} = $form->{"new_${_}_$j"} } @new_fields;
267
268   $form->{"marge_price_factor_$i"} = $form->{"new_price_factor_$j"};
269
270   if ($form->{"part_payment_id_$i"} ne "") {
271     $form->{payment_id} = $form->{"part_payment_id_$i"};
272   }
273
274   if ($lizenzen) {
275     map { $form->{"${_}_$i"} = $form->{"new_${_}_$j"} } qw(lizenzen);
276   }
277
278   ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
279   $dec           = length $dec;
280   $decimalplaces = ($dec > 2) ? $dec : 2;
281
282   if ($sellprice) {
283     $form->{"sellprice_$i"} = $sellprice;
284   } else {
285
286     # if there is an exchange rate adjust sellprice
287     if (($form->{exchangerate} * 1) != 0) {
288       $form->{"sellprice_$i"} /= $form->{exchangerate};
289       $form->{"sellprice_$i"} =
290         $form->round_amount($form->{"sellprice_$i"}, $decimalplaces);
291     }
292   }
293
294   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
295     qw(sellprice listprice weight);
296
297   $form->{sellprice} += ($form->{"sellprice_$i"} * $form->{"qty_$i"});
298   $form->{weight}    += ($form->{"weight_$i"} * $form->{"qty_$i"});
299   
300   if ($form->{"not_discountable_$i"}) {
301     $form->{"discount_$i"} = 0;
302   }
303
304   $amount =
305     $form->{"sellprice_$i"} * (1 - $form->{"discount_$i"} / 100) *
306     $form->{"qty_$i"};
307   map { $form->{"${_}_base"} += $amount }
308     (split / /, $form->{"taxaccounts_$i"});
309   map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /,
310     $form->{"taxaccounts_$i"}
311     if !$form->{taxincluded};
312
313   $form->{creditremaining} -= $amount;
314
315   $form->{"runningnumber_$i"} = $i;
316
317   # delete all the new_ variables
318   for $i (1 .. $form->{lastndx}) {
319     map { delete $form->{"new_${_}_$i"} } @new_fields;
320   }
321
322   map { delete $form->{$_} } qw(ndx lastndx nextsub);
323
324   # format amounts
325   map {
326     $form->{"${_}_$i"} =
327       $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces)
328   } qw(sellprice listprice) if $form->{item} ne 'assembly';
329
330   # get pricegroups for parts
331   IS->get_pricegroups_for_parts(\%myconfig, \%$form);
332
333   # build up html code for prices_$i
334   set_pricegroup($form->{rowcount});
335
336   &display_form;
337
338   $lxdebug->leave_sub();
339 }
340
341 sub new_item {
342   $lxdebug->enter_sub();
343
344   # change callback
345   $form->{old_callback} = $form->escape($form->{callback}, 1);
346   $form->{callback}     = $form->escape("$form->{script}?action=display_form", 1);
347
348   # save all form variables except action in a previousform variable
349   my $previousform = join '&', map { $form->{$_} =~ s/&/%26/; "$_=$form->{$_}" } grep { !/action/ } keys %$form;
350
351   push @HIDDENS,      { 'name' => 'previousform', 'value' => $form->escape($previousform, 1) };
352   push @HIDDENS, map +{ 'name' => $_,             'value' => $form->{$_} },                       qw(rowcount vc login password);
353   push @HIDDENS, map +{ 'name' => $_,             'value' => $form->{"${_}_$form->{rowcount}"} }, qw(partnumber description unit sellprice);
354   push @HIDDENS,      { 'name' => 'taxaccount2',  'value' => $form->{taxaccounts} };
355
356   $form->header();
357   print $form->parse_html_template2("generic/new_item", { HIDDENS => [ sort { $a->{name} cmp $b->{name} } @HIDDENS ] } );
358
359   $lxdebug->leave_sub();
360 }
361
362 sub check_form {
363   $lxdebug->enter_sub();
364   my @a     = ();
365   my $count = 0;
366   my @flds  = (qw(id partnumber description qty ship sellprice unit discount inventory_accno income_accno expense_accno listprice taxaccounts bin assembly weight projectnumber project_id oldprojectnumber runningnumber serialnumber partsgroup payment_id not_discountable shop ve gv buchungsgruppen_id language_values sellprice_pg pricegroup_old price_old price_new unit_old ordnumber transdate longdescription basefactor marge_total marge_percent marge_price_factor lastcost price_factor_id));
367
368   # remove any makes or model rows
369   if ($form->{item} eq 'part') {
370     map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
371       qw(listprice sellprice lastcost weight rop);
372
373     @flds = (make, model);
374     for my $i (1 .. ($form->{makemodel_rows})) {
375       if (($form->{"make_$i"} ne "") || ($form->{"model_$i"} ne "")) {
376         push @a, {};
377         my $j = $#a;
378
379         map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
380         $count++;
381       }
382     }
383
384     $form->redo_rows(\@flds, \@a, $count, $form->{makemodel_rows});
385     $form->{makemodel_rows} = $count;
386
387   } elsif ($form->{item} eq 'assembly') {
388
389     $form->{sellprice} = 0;
390     $form->{weight}    = 0;
391     map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
392       qw(listprice rop stock);
393
394     @flds =
395       qw(id qty unit bom partnumber description sellprice weight runningnumber partsgroup);
396
397     for my $i (1 .. ($form->{assembly_rows} - 1)) {
398       if ($form->{"qty_$i"}) {
399         push @a, {};
400         my $j = $#a;
401
402         $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
403
404         map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
405
406         #($form->{"sellprice_$i"},$form->{"$pricegroup_old_$i"}) = split /--/, $form->{"sellprice_$i"};
407
408         $form->{sellprice} += ($form->{"qty_$i"} * $form->{"sellprice_$i"});
409         $form->{weight}    += ($form->{"qty_$i"} * $form->{"weight_$i"});
410         $count++;
411       }
412     }
413
414     $form->{sellprice} = $form->round_amount($form->{sellprice}, 2);
415
416     $form->redo_rows(\@flds, \@a, $count, $form->{assembly_rows});
417     $form->{assembly_rows} = $count;
418
419     $count = 0;
420     @flds  = qw(make model);
421     @a     = ();
422
423     for my $i (1 .. ($form->{makemodel_rows})) {
424       if (($form->{"make_$i"} ne "") || ($form->{"model_$i"} ne "")) {
425         push @a, {};
426         my $j = $#a;
427
428         map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
429         $count++;
430       }
431     }
432
433     $form->redo_rows(\@flds, \@a, $count, $form->{makemodel_rows});
434     $form->{makemodel_rows} = $count;
435
436   } elsif ($form->{item} eq 'service') {
437     map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) } qw(listprice sellprice lastcost);
438
439   } else {
440
441     # this section applies to invoices and orders
442     # remove any empty numbers
443     if ($form->{rowcount}) {
444       for my $i (1 .. $form->{rowcount} - 1) {
445         if ($form->{"partnumber_$i"}) {
446           push @a, {};
447           my $j = $#a;
448
449           map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
450           $count++;
451           if ($lizenzen) {
452             if ($form->{"licensenumber_$i"} == -1) {
453               &new_license($i);
454               exit;
455             }
456           }
457         }
458       }
459
460       $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
461       $form->{rowcount} = $count;
462
463       $form->{creditremaining} -= &invoicetotal;
464
465     }
466   }
467
468   #sk
469   # if pricegroups
470   if (   $form->{type} =~ (/sales_quotation/)
471       or (($form->{level} =~ /Sales/) and ($form->{type} =~ /invoice/))
472       or (($form->{level} eq undef) and ($form->{type} =~ /invoice/))
473       or ($form->{type} =~ /sales_order/)) {
474
475     # get pricegroups for parts
476     IS->get_pricegroups_for_parts(\%myconfig, \%$form);
477
478     # build up html code for prices_$i
479     set_pricegroup($form->{rowcount});
480
481   }
482
483   &display_form;
484
485   $lxdebug->leave_sub();
486 }
487
488 sub invoicetotal {
489   $lxdebug->enter_sub();
490
491   $form->{oldinvtotal} = 0;
492
493   # add all parts and deduct paid
494   map { $form->{"${_}_base"} = 0 } split / /, $form->{taxaccounts};
495
496   my ($amount, $sellprice, $discount, $qty);
497
498   for my $i (1 .. $form->{rowcount}) {
499     $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
500     $discount  = $form->parse_amount(\%myconfig, $form->{"discount_$i"});
501     $qty       = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
502
503     #($form->{"sellprice_$i"}, $form->{"$pricegroup_old_$i"}) = split /--/, $form->{"sellprice_$i"};
504
505     $amount = $sellprice * (1 - $discount / 100) * $qty;
506     map { $form->{"${_}_base"} += $amount }
507       (split (/ /, $form->{"taxaccounts_$i"}));
508     $form->{oldinvtotal} += $amount;
509   }
510
511   map { $form->{oldinvtotal} += ($form->{"${_}_base"} * $form->{"${_}_rate"}) }
512     split(/ /, $form->{taxaccounts})
513     if !$form->{taxincluded};
514
515   $form->{oldtotalpaid} = 0;
516   for $i (1 .. $form->{paidaccounts}) {
517     $form->{oldtotalpaid} += $form->{"paid_$i"};
518   }
519
520   $lxdebug->leave_sub();
521
522   # return total
523   return ($form->{oldinvtotal} - $form->{oldtotalpaid});
524 }
525
526 sub validate_items {
527   $lxdebug->enter_sub();
528
529   # check if items are valid
530   if ($form->{rowcount} == 1) {
531     &update;
532     exit;
533   }
534
535   for $i (1 .. $form->{rowcount} - 1) {
536     $form->isblank("partnumber_$i",
537                    $locale->text('Number missing in Row') . " $i");
538   }
539
540   $lxdebug->leave_sub();
541 }
542
543 sub order {
544   $lxdebug->enter_sub();
545   if ($form->{second_run}) {
546     $form->{print_and_post} = 0;
547   }
548   $form->{ordnumber} = $form->{invnumber};
549
550   $form->{old_employee_id} = $form->{employee_id};
551   $form->{old_salesman_id} = $form->{salesman_id};
552
553   map { delete $form->{$_} } qw(id printed emailed queued);
554   if ($form->{script} eq 'ir.pl' || $form->{type} eq 'request_quotation') {
555     $form->{title} = $locale->text('Add Purchase Order');
556     $form->{vc}    = 'vendor';
557     $form->{type}  = 'purchase_order';
558     $buysell       = 'sell';
559   }
560   if ($form->{script} eq 'is.pl' || $form->{type} eq 'sales_quotation') {
561     $form->{title} = $locale->text('Add Sales Order');
562     $form->{vc}    = 'customer';
563     $form->{type}  = 'sales_order';
564     $buysell       = 'buy';
565   }
566   $form->{script} = 'oe.pl';
567
568   $form->{shipto} = 1;
569
570   $form->{rowcount}--;
571
572   $form->{cp_id} *= 1;
573
574   require "bin/mozilla/$form->{script}";
575   my $script = $form->{"script"};
576   $script =~ s|.*/||;
577   $script =~ s|.pl$||;
578   $locale = new Locale($language, $script);
579
580   map { $form->{"select$_"} = "" } ($form->{vc}, currency);
581
582   $currency = $form->{currency};
583
584   &order_links;
585
586   $form->{currency}     = $currency;
587   $form->{exchangerate} = "";
588   $form->{forex}        = "";
589   $form->{exchangerate} = $exchangerate
590     if (
591         $form->{forex} = (
592                   $exchangerate =
593                     $form->check_exchangerate(
594                     \%myconfig, $form->{currency}, $form->{transdate}, $buysell
595                     )));
596
597   for $i (1 .. $form->{rowcount}) {
598     map({ $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig,
599                                                      $form->{"${_}_${i}"})
600             if ($form->{"${_}_${i}"}) }
601         qw(ship qty sellprice listprice basefactor));
602   }
603
604   &prepare_order;
605   &display_form;
606
607   $lxdebug->leave_sub();
608 }
609
610 sub quotation {
611   $lxdebug->enter_sub();
612   if ($form->{second_run}) {
613     $form->{print_and_post} = 0;
614   }
615   map { delete $form->{$_} } qw(id printed emailed queued);
616
617   if ($form->{script} eq 'ir.pl' || $form->{type} eq 'purchase_order') {
618     $form->{title} = $locale->text('Add Request for Quotation');
619     $form->{vc}    = 'vendor';
620     $form->{type}  = 'request_quotation';
621     $buysell       = 'sell';
622   }
623   if ($form->{script} eq 'is.pl' || $form->{type} eq 'sales_order') {
624     $form->{title} = $locale->text('Add Quotation');
625     $form->{vc}    = 'customer';
626     $form->{type}  = 'sales_quotation';
627     $buysell       = 'buy';
628   }
629
630   $form->{cp_id} *= 1;
631
632   $form->{script} = 'oe.pl';
633
634   $form->{shipto} = 1;
635
636   $form->{rowcount}--;
637
638   require "bin/mozilla/$form->{script}";
639
640   map { $form->{"select$_"} = "" } ($form->{vc}, currency);
641
642   $currency = $form->{currency};
643
644   &order_links;
645
646   $form->{currency}     = $currency;
647   $form->{exchangerate} = "";
648   $form->{forex}        = "";
649   $form->{exchangerate} = $exchangerate
650     if (
651         $form->{forex} = (
652                   $exchangerate =
653                     $form->check_exchangerate(
654                     \%myconfig, $form->{currency}, $form->{transdate}, $buysell
655                     )));
656
657   for $i (1 .. $form->{rowcount}) {
658     map({ $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig,
659                                                      $form->{"${_}_${i}"})
660             if ($form->{"${_}_${i}"}) }
661         qw(ship qty sellprice listprice basefactor));
662   }
663
664   &prepare_order;
665   &display_form;
666
667   $lxdebug->leave_sub();
668 }
669
670 sub request_for_quotation {
671   quotation();
672 }
673
674 sub edit_e_mail {
675   $lxdebug->enter_sub();
676
677   if ($form->{second_run}) {
678     $form->{print_and_post} = 0;
679     $form->{resubmit}       = 0;
680   }
681
682   $form->{email} = $form->{shiptoemail} if $form->{shiptoemail} && $form->{formname} =~ /(pick|packing|bin)_list/;
683
684   if ($form->{"cp_id"} && !$form->{"email"}) {
685     CT->get_contact(\%myconfig, $form);
686     $form->{"email"} = $form->{"cp_email"};
687   }
688
689   $title = $locale->text('E-mail') . " " . $form->get_formname_translation();
690
691   $form->{oldmedia} = $form->{media};
692   $form->{media}    = "email";
693
694   my $attachment_filename = $form->generate_attachment_filename();
695
696   $form->{"fokus"} = $form->{"email"} ? "Form.subject" : "Form.email";
697   $form->header;
698
699   my (@dont_hide_key_list, %dont_hide_key, @hidden_keys);
700   @dont_hide_key_list = qw(action email cc bcc subject message sendmode format header override);
701   @dont_hide_key{@dont_hide_key_list} = (1) x @dont_hide_key_list;
702   @hidden_keys = sort grep { !$dont_hide_key{$_} } grep { !ref $form->{$_} } keys %$form;
703
704   print $form->parse_html_template2('generic/edit_email',
705                                     { title           => $title,
706                                       a_filename      => $attachment_filename,
707                                       _print_options_ => print_options('inline' => 1),
708                                       HIDDEN          => [ map +{ name => $_, value => $form->{$_} }, @hidden_keys ],
709                                       SHOW_BCC        => $myconfig{role} eq 'admin' });
710
711   $lxdebug->leave_sub();
712 }
713
714 sub send_email {
715   $lxdebug->enter_sub();
716
717   my $callback = $form->{script} . "?action=edit";
718   map({ $callback .= "\&${_}=" . E($form->{$_}); }
719       qw(login password type id));
720
721   print_form("return");
722
723   Common->save_email_status(\%myconfig, $form);
724
725   $form->{callback} = $callback;
726   $form->redirect();
727
728   $lxdebug->leave_sub();
729 }
730
731 # generate the printing options displayed at the bottom of oe and is forms.
732 # this function will attempt to guess what type of form is displayed, and will generate according options
733 #
734 # about the coding: 
735 # this version builds the arrays of options pretty directly. if you have trouble understanding how,
736 # the opthash function builds hashrefs which are then pieced together for the template arrays.
737 # unneeded options are "undef"ed out, and then grepped out. 
738 #
739 # the inline options is untested, but intended to be used later in metatemplating
740 sub print_options {
741   $lxdebug->enter_sub();
742
743   my %options = @_;
744
745   # names 3 parameters and returns a hashref, for use in templates
746   sub opthash { +{ value => shift, selected => shift, oname => shift } }
747   (@FORMNAME, @FORMNAME, @LANGUAGE_ID, @FORMAT, @SENDMODE, @MEDIA, @PRINTER_ID, @SELECTS) = ();
748
749   # note: "||"-selection is only correct for values where "0" is _not_ a correct entry
750   $form->{sendmode}   = "attachment";
751   $form->{format}     = $form->{format} || $myconfig{template_format} || "pdf";
752   $form->{copies}     = $form->{copies} || $myconfig{copies}          || 3;
753   $form->{media}      = $form->{media}  || $myconfig{default_media}   || "screen";
754   $form->{printer_id} = defined $form->{printer_id}           ? $form->{printer_id} :
755                         defined $myconfig{default_printer_id} ? $myconfig{default_printer_id} : "";
756
757   $form->{PD}{ $form->{formname} } = "selected";
758   $form->{DF}{ $form->{format} }   = "selected";
759   $form->{OP}{ $form->{media} }    = "selected";
760   $form->{SM}{ $form->{formname} } = "selected";
761
762   push @FORMNAME, grep $_,
763     ($form->{type} eq 'purchase_order') ? (
764       opthash("purchase_order",      $form->{PD}{purchase_order},      $locale->text('Purchase Order')),
765       opthash("bin_list",            $form->{PD}{bin_list},            $locale->text('Bin List')) 
766     ) : undef,
767     ($form->{type} eq 'credit_note') ?
768       opthash("credit_note",         $form->{PD}{credit_note},         $locale->text('Credit Note')) : undef,
769     ($form->{type} eq 'sales_order') ? (
770       opthash("sales_order",         $form->{PD}{sales_order},         $locale->text('Confirmation')),
771       opthash("proforma",            $form->{PD}{proforma},            $locale->text('Proforma Invoice')),
772       opthash("pick_list",           $form->{PD}{pick_list},           $locale->text('Pick List')),
773       opthash("packing_list",        $form->{PD}{packing_list},        $locale->text('Packing List')) 
774     ) : undef,
775     ($form->{type} =~ /_quotation$/) ?
776       opthash("$`_quotation",        $form->{PD}{"$`_quotation"},      $locale->text('Quotation')) : undef,
777     ($form->{type} eq 'invoice') ? (
778       opthash("invoice",             $form->{PD}{invoice},             $locale->text('Invoice')),
779       opthash("proforma",            $form->{PD}{proforma},            $locale->text('Proforma Invoice')),
780       opthash("packing_list",        $form->{PD}{packing_list},        $locale->text('Packing List'))
781     ) : undef,
782     ($form->{type} eq 'invoice' && $form->{storno}) ? (
783       opthash("storno_invoice",      $form->{PD}{storno_invoice},      $locale->text('Storno Invoice')),
784       opthash("storno_packing_list", $form->{PD}{storno_packing_list}, $locale->text('Storno Packing List')) 
785     ) : undef,
786     ($form->{type} eq 'credit_note') ?
787       opthash("credit_note",         $form->{PD}{credit_note},         $locale->text('Credit Note')) : undef;
788
789   push @SENDMODE, 
790     opthash("attachment",            $form->{SM}{attachment},          $locale->text('Attachment')),
791     opthash("inline",                $form->{SM}{inline},              $locale->text('In-line'))
792       if ($form->{media} eq 'email');
793
794   push @MEDIA, grep $_,
795       opthash("screen",              $form->{OP}{screen},              $locale->text('Screen')),
796     (scalar @{ $form->{printers} } && $latex_templates) ?
797       opthash("printer",             $form->{OP}{printer},             $locale->text('Printer')) : undef,
798     ($latex_templates && !$options->{no_queue}) ?
799       opthash("queue",               $form->{OP}{queue},               $locale->text('Queue')) : undef
800         if ($form->{media} ne 'email');
801
802   push @FORMAT, grep $_,
803     ($opendocument_templates && $openofficeorg_writer_bin && $xvfb_bin && (-x $openofficeorg_writer_bin) && (-x $xvfb_bin)
804      && !$options->{no_opendocument_pdf}) ?
805       opthash("opendocument_pdf",    $form->{DF}{"opendocument_pdf"},  $locale->text("PDF (OpenDocument/OASIS)")) : undef,
806     ($latex_templates) ?
807       opthash("pdf",                 $form->{DF}{pdf},                 $locale->text('PDF')) : undef,
808     ($latex_templates && !$options->{no_postscript}) ?
809       opthash("postscript",          $form->{DF}{postscript},          $locale->text('Postscript')) : undef,
810     (!$options->{no_html}) ?
811       opthash("html", $form->{DF}{html}, "HTML") : undef,
812     ($opendocument_templates && !$options->{no_opendocument}) ?
813       opthash("opendocument",        $form->{DF}{opendocument},        $locale->text("OpenDocument/OASIS")) : undef;
814
815   push @LANGUAGE_ID, 
816     map { opthash($_->{id}, ($_->{id} eq $form->{language_id} ? 'selected' : ''), $_->{description}) } +{}, @{ $form->{languages} }
817       if (ref $form->{languages} eq 'ARRAY');
818
819   push @PRINTER_ID, 
820     map { opthash($_->{id}, ($_->{id} eq $form->{printer_id} ? 'selected' : ''), $_->{printer_description}) } +{}, @{ $form->{printers} }
821       if ((ref $form->{printers} eq 'ARRAY') && scalar @{ $form->{printers } });
822
823   @SELECTS = map { sname => lc $_, DATA => \@$_, show => !$options{"hide_" . lc($_)} && scalar @$_ }, qw(FORMNAME LANGUAGE_ID FORMAT SENDMODE MEDIA PRINTER_ID);
824
825   my %dont_display_groupitems = (
826     'dunning' => 1,
827     );
828
829   %template_vars = (
830     display_copies       => scalar @{ $form->{printers} } && $latex_templates && $form->{media} ne 'email',
831     display_remove_draft => (!$form->{id} && $form->{draft_id}),
832     display_groupitems   => !$dont_display_groupitems{$form->{type}},
833     groupitems_checked   => $form->{groupitems} ? "checked" : '',
834     remove_draft_checked => $form->{remove_draft} ? "checked" : ''
835   );
836
837   my $print_options = $form->parse_html_template2("generic/print_options", { SELECTS  => \@SELECTS, %template_vars } );
838
839   if ($options{inline}) {
840     $lxdebug->leave_sub();
841     return $print_options;
842   }
843
844   print $print_options;
845
846   $lxdebug->leave_sub();
847 }
848
849 sub print {
850   $lxdebug->enter_sub();
851
852   if ($form->{print_nextsub}) {
853     call_sub($form->{print_nextsub});
854     $lxdebug->leave_sub();
855     return;
856   }
857
858   # if this goes to the printer pass through
859   if ($form->{media} eq 'printer' || $form->{media} eq 'queue') {
860     $form->error($locale->text('Select postscript or PDF!'))
861       if ($form->{format} !~ /(postscript|pdf)/);
862
863     $old_form = new Form;
864     map { $old_form->{$_} = $form->{$_} } keys %$form;
865   }
866
867   if (!$form->{id} || (($form->{formname} eq "proforma") && !$form->{proforma} && (($form->{type} =~ /_order$/) || ($form->{type} =~ /_quotation$/)))) {
868     if ($form->{formname} eq "proforma") {
869       $form->{proforma} = 1;
870     }
871     $form->{print_and_save} = 1;
872     my $formname = $form->{formname};
873     &save();
874     $form->{formname} = $formname;
875     &edit();
876     exit;
877   }
878
879   &print_form($old_form);
880
881   $lxdebug->leave_sub();
882 }
883
884 sub print_form {
885   $lxdebug->enter_sub();
886   my ($old_form) = @_;
887
888   $inv       = "inv";
889   $due       = "due";
890   $numberfld = "invnumber";
891
892   $display_form =
893     ($form->{display_form}) ? $form->{display_form} : "display_form";
894
895   # $form->{"notes"} will be overridden by the customer's/vendor's "notes" field. So save it here.
896   $form->{ $form->{"formname"} . "notes" } = $form->{"notes"};
897
898   if ($form->{formname} eq "invoice") {
899     $form->{label} = $locale->text('Invoice');
900   }
901   if ($form->{formname} eq "packing_list") {
902
903     # this is from an invoice
904     $form->{label} = $locale->text('Packing List');
905   }
906   if ($form->{formname} eq 'sales_order') {
907     $inv                  = "ord";
908     $due                  = "req";
909     $form->{"${inv}date"} = $form->{transdate};
910     $form->{label}        = $locale->text('Confirmation');
911     $numberfld            = "sonumber";
912     $order                = 1;
913   }
914
915   if (($form->{type} eq 'invoice') && ($form->{formname} eq 'proforma') ) {
916     $inv                  = "inv";
917     $due                  = "due";
918     $form->{"${inv}date"} = $form->{invdate};
919     $form->{label}        = $locale->text('Proforma Invoice');
920     $numberfld            = "sonumber";
921     $order                = 0;
922   }
923
924   if (($form->{type} eq 'sales_order') && ($form->{formname} eq 'proforma') ) {
925     $inv                  = "inv";
926     $due                  = "due";
927     $form->{"${inv}date"} = $form->{transdate};
928     $form->{"invdate"}    = $form->{transdate};
929     $form->{invnumber}    = $form->{ordnumber};
930     $form->{label}        = $locale->text('Proforma Invoice');
931     $numberfld            = "sonumber";
932     $order                = 1;
933   }
934
935   if ($form->{formname} eq 'packing_list' && $form->{type} ne 'invoice') {
936
937     # we use the same packing list as from an invoice
938     $inv = "ord";
939     $due = "req";
940     $form->{invdate} = $form->{"${inv}date"} = $form->{transdate};
941     $form->{label} = $locale->text('Packing List');
942     $order = 1;
943     # set invnumber for template packing_list 
944     $form->{invnumber}   = $form->{ordnumber};
945   }
946   if ($form->{formname} eq 'pick_list') {
947     $inv                  = "ord";
948     $due                  = "req";
949     $form->{"${inv}date"} =
950       ($form->{transdate}) ? $form->{transdate} : $form->{invdate};
951     $form->{label} = $locale->text('Pick List');
952     $order = 1 unless $form->{type} eq 'invoice';
953   }
954   if ($form->{formname} eq 'purchase_order') {
955     $inv                  = "ord";
956     $due                  = "req";
957     $form->{"${inv}date"} = $form->{transdate};
958     $form->{label}        = $locale->text('Purchase Order');
959     $numberfld            = "ponumber";
960     $order                = 1;
961   }
962   if ($form->{formname} eq 'bin_list') {
963     $inv                  = "ord";
964     $due                  = "req";
965     $form->{"${inv}date"} = $form->{transdate};
966     $form->{label}        = $locale->text('Bin List');
967     $order                = 1;
968   }
969   if ($form->{formname} eq 'sales_quotation') {
970     $inv                  = "quo";
971     $due                  = "req";
972     $form->{"${inv}date"} = $form->{transdate};
973     $form->{label}        = $locale->text('Quotation');
974     $numberfld            = "sqnumber";
975     $order                = 1;
976   }
977
978   if (($form->{type} eq 'sales_quotation') && ($form->{formname} eq 'proforma') ) {
979     $inv                  = "quo";
980     $due                  = "req";
981     $form->{"${inv}date"} = $form->{transdate};
982     $form->{"invdate"}    = $form->{transdate};
983     $form->{label}        = $locale->text('Proforma Invoice');
984     $numberfld            = "sqnumber";
985     $order                = 1;
986   }
987
988   if ($form->{formname} eq 'request_quotation') {
989     $inv                  = "quo";
990     $due                  = "req";
991     $form->{"${inv}date"} = $form->{transdate};
992     $form->{label}        = $locale->text('RFQ');
993     $numberfld            = "rfqnumber";
994     $order                = 1;
995   }
996
997   $form->isblank("email", $locale->text('E-mail address missing!'))
998     if ($form->{media} eq 'email');
999   $form->isblank("${inv}date",
1000            $locale->text($form->{label}) 
1001            . ": "
1002            . $locale->text(' Date missing!'));
1003
1004   # $locale->text('Invoice Number missing!')
1005   # $locale->text('Invoice Date missing!')
1006   # $locale->text('Packing List Number missing!')
1007   # $locale->text('Packing List Date missing!')
1008   # $locale->text('Order Number missing!')
1009   # $locale->text('Order Date missing!')
1010   # $locale->text('Quotation Number missing!')
1011   # $locale->text('Quotation Date missing!')
1012
1013   # assign number
1014   $form->{what_done} = $form->{formname};
1015   if (!$form->{"${inv}number"} && !$form->{preview} && !$form->{id}) {
1016     $form->{"${inv}number"} = $form->update_defaults(\%myconfig, $numberfld);
1017     if ($form->{media} ne 'email') {
1018
1019       # get pricegroups for parts
1020       IS->get_pricegroups_for_parts(\%myconfig, \%$form);
1021
1022       # build up html code for prices_$i
1023       set_pricegroup($form->{rowcount});
1024
1025       $form->{rowcount}--;
1026
1027       call_sub($display_form);
1028       # saving the history
1029           if(!exists $form->{addition}) {
1030         $form->{snumbers} = qq|ordnumber_| . $form->{ordnumber}; 
1031             $form->{addition} = "PRINTED";
1032             $form->save_history($form->dbconnect(\%myconfig));
1033       }
1034       # /saving the history
1035       exit;
1036     }
1037   }
1038
1039   &validate_items;
1040
1041   # Save the email address given in the form because it should override the setting saved for the customer/vendor.
1042   my ($saved_email, $saved_cc, $saved_bcc) =
1043     ($form->{"email"}, $form->{"cc"}, $form->{"bcc"});
1044
1045   $language_saved = $form->{language_id};
1046   $payment_id_saved = $form->{payment_id};
1047   $salesman_id_saved = $form->{salesman_id};
1048   $cp_id_saved = $form->{cp_id};
1049
1050   call_sub("$form->{vc}_details");
1051
1052   $form->{language_id} = $language_saved;
1053   $form->{payment_id} = $payment_id_saved;
1054
1055   $form->{"email"} = $saved_email if ($saved_email);
1056   $form->{"cc"}    = $saved_cc    if ($saved_cc);
1057   $form->{"bcc"}   = $saved_bcc   if ($saved_bcc);
1058
1059   if (!$cp_id_saved) {
1060     # No contact was selected. Delete all contact variables because
1061     # IS->customer_details() and IR->vendor_details() get the default
1062     # contact anyway.
1063     map({ delete($form->{$_}); } grep(/^cp_/, keys(%{ $form })));
1064   }
1065
1066   my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
1067   if ($form->{"language_id"}) {
1068     ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) =
1069       AM->get_language_details(\%myconfig, $form, $form->{language_id});
1070   } else {
1071     $output_dateformat = $myconfig{"dateformat"};
1072     $output_numberformat = $myconfig{"numberformat"};
1073     $output_longdates = 1;
1074   }
1075
1076   ($form->{employee}) = split /--/, $form->{employee};
1077
1078   # create the form variables
1079   if ($order) {
1080     OE->order_details(\%myconfig, \%$form);
1081   } else {
1082     IS->invoice_details(\%myconfig, \%$form, $locale);
1083   }
1084
1085   $form->get_salesman(\%myconfig, $salesman_id_saved);
1086
1087   if ($form->{shipto_id}) {
1088     $form->get_shipto(\%myconfig);
1089   }
1090
1091   @a = qw(name street zipcode city country);
1092
1093   $shipto = 1;
1094
1095   # if there is no shipto fill it in from billto
1096   foreach $item (@a) {
1097     if ($form->{"shipto$item"}) {
1098       $shipto = 0;
1099       last;
1100     }
1101   }
1102
1103   if ($shipto) {
1104     if (   $form->{formname} eq 'purchase_order'
1105         || $form->{formname} eq 'request_quotation') {
1106       $form->{shiptoname}   = $myconfig{company};
1107       $form->{shiptostreet} = $myconfig{address};
1108     } else {
1109       map { $form->{"shipto$_"} = $form->{$_} } @a;
1110     }
1111   }
1112
1113   $form->{notes} =~ s/^\s+//g;
1114
1115   $form->{templates} = "$myconfig{templates}";
1116
1117   delete $form->{printer_command};
1118
1119   $form->{language} = $form->get_template_language(\%myconfig);
1120
1121   my $printer_code;
1122   if ($form->{media} ne 'email') {
1123     $printer_code = $form->get_printer_code(\%myconfig);
1124     if ($printer_code ne "") {
1125       $printer_code = "_" . $printer_code;
1126     }
1127   }
1128
1129   if ($form->{language} ne "") {
1130     map({ $form->{"unit"}->[$_] =
1131             AM->translate_units($form, $form->{"language"},
1132                                 $form->{"unit"}->[$_], $form->{"qty"}->[$_]); }
1133         (0..scalar(@{$form->{"unit"}}) - 1));
1134     $form->{language} = "_" . $form->{language};
1135   }
1136
1137   # Format dates.
1138   format_dates($output_dateformat, $output_longdates,
1139                qw(invdate orddate quodate pldate duedate reqdate transdate
1140                   shippingdate deliverydate validitydate paymentdate
1141                   datepaid transdate_oe deliverydate_oe
1142                   employee_startdate employee_enddate
1143                   ),
1144                grep({ /^datepaid_\d+$/ ||
1145                         /^transdate_oe_\d+$/ ||
1146                         /^deliverydate_oe_\d+$/ ||
1147                         /^reqdate_\d+$/ ||
1148                         /^deliverydate_\d+$/ ||
1149                         /^transdate_\d+$/
1150                     } keys(%{$form})));
1151
1152   reformat_numbers($output_numberformat, 2,
1153                    qw(invtotal ordtotal quototal subtotal linetotal
1154                       listprice sellprice netprice discount
1155                       tax taxbase total paid),
1156                    grep({ /^linetotal_\d+$/ ||
1157                             /^listprice_\d+$/ ||
1158                             /^sellprice_\d+$/ ||
1159                             /^netprice_\d+$/ ||
1160                             /^taxbase_\d+$/ ||
1161                             /^discount_\d+$/ ||
1162                             /^paid_\d+$/ ||
1163                             /^subtotal_\d+$/ ||
1164                             /^total_\d+$/ ||
1165                             /^tax_\d+$/
1166                         } keys(%{$form})));
1167
1168   reformat_numbers($output_numberformat, undef,
1169                    qw(qty price_factor),
1170                    grep({ /^qty_\d+$/
1171                         } keys(%{$form})));
1172
1173   $form->{IN} = "$form->{formname}$form->{language}${printer_code}.html";
1174   if ($form->{format} eq 'postscript') {
1175     $form->{postscript} = 1;
1176     $form->{IN} =~ s/html$/tex/;
1177   } elsif ($form->{"format"} =~ /pdf/) {
1178     $form->{pdf} = 1;
1179     if ($form->{"format"} =~ /opendocument/) {
1180       $form->{IN} =~ s/html$/odt/;
1181     } else {
1182       $form->{IN} =~ s/html$/tex/;
1183     }
1184   } elsif ($form->{"format"} =~ /opendocument/) {
1185     $form->{"opendocument"} = 1;
1186     $form->{"IN"} =~ s/html$/odt/;
1187   }
1188
1189   delete $form->{OUT};
1190
1191   if ($form->{media} eq 'printer') {
1192     $form->{OUT} = "| $form->{printer_command} &>/dev/null";
1193     $form->{printed} .= " $form->{formname}";
1194     $form->{printed} =~ s/^ //;
1195   }
1196   $printed = $form->{printed};
1197
1198   if ($form->{media} eq 'email') {
1199     $form->{subject} = qq|$form->{label} $form->{"${inv}number"}|
1200       unless $form->{subject};
1201
1202     $form->{emailed} .= " $form->{formname}";
1203     $form->{emailed} =~ s/^ //;
1204   }
1205   $emailed = $form->{emailed};
1206
1207   if ($form->{media} eq 'queue') {
1208     %queued = map { s|.*/|| } split / /, $form->{queued};
1209
1210     if ($filename = $queued{ $form->{formname} }) {
1211       $form->{queued} =~ s/\Q$form->{formname} $filename\E//;
1212       unlink "$spool/$filename";
1213       $filename =~ s/\..*$//g;
1214     } else {
1215       $filename = time;
1216       $filename .= $$;
1217     }
1218
1219     $filename .= ($form->{postscript}) ? '.ps' : '.pdf';
1220     $form->{OUT} = ">$spool/$filename";
1221
1222     # add type
1223     $form->{queued} .= " $form->{formname} $filename";
1224
1225     $form->{queued} =~ s/^ //;
1226   }
1227   $queued = $form->{queued};
1228
1229 # saving the history
1230   if(!exists $form->{addition}) {
1231     $form->{snumbers} = qq|ordnumber_| . $form->{ordnumber};
1232     if($form->{media} =~ /printer/) {
1233         $form->{addition} = "PRINTED";
1234     }
1235     elsif($form->{media} =~ /email/) {
1236         $form->{addition} = "MAILED";
1237     }
1238     elsif($form->{media} =~ /queue/) {
1239         $form->{addition} = "QUEUED";
1240     }
1241     elsif($form->{media} =~ /screen/) {
1242         $form->{addition} = "SCREENED";
1243     }
1244     $form->save_history($form->dbconnect(\%myconfig));
1245   }
1246   # /saving the history
1247
1248   $form->parse_template(\%myconfig, $userspath);
1249
1250   $form->{callback} = "";
1251
1252   if ($form->{media} eq 'email') {
1253     $form->{message} = $locale->text('sent') unless $form->{message};
1254   }
1255   $message = $form->{message};
1256
1257   # if we got back here restore the previous form
1258   if ($form->{media} =~ /(printer|email|queue)/) {
1259
1260     $form->update_status(\%myconfig)
1261       if ($form->{media} eq 'queue' && $form->{id});
1262
1263     return $lxdebug->leave_sub() if ($old_form eq "return");
1264
1265     if ($old_form) {
1266
1267       $old_form->{"${inv}number"} = $form->{"${inv}number"};
1268
1269       # restore and display form
1270       map { $form->{$_} = $old_form->{$_} } keys %$old_form;
1271
1272       $form->{queued}  = $queued;
1273       $form->{printed} = $printed;
1274       $form->{emailed} = $emailed;
1275       $form->{message} = $message;
1276
1277       $form->{rowcount}--;
1278       map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
1279         qw(exchangerate creditlimit creditremaining);
1280
1281       for $i (1 .. $form->{paidaccounts}) {
1282         map {
1283           $form->{"${_}_$i"} =
1284             $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
1285         } qw(paid exchangerate);
1286       }
1287
1288       call_sub($display_form);
1289       exit;
1290     }
1291
1292     $msg =
1293       ($form->{media} eq 'printer')
1294       ? $locale->text('sent to printer')
1295       : $locale->text('emailed to') . " $form->{email}";
1296     $form->redirect(qq|$form->{label} $form->{"${inv}number"} $msg|);
1297   }
1298   if ($form->{printing}) {
1299    call_sub($display_form);
1300    exit; 
1301   }
1302
1303   $lxdebug->leave_sub();
1304 }
1305
1306 sub customer_details {
1307   $lxdebug->enter_sub();
1308   IS->customer_details(\%myconfig, \%$form, @_);
1309   $lxdebug->leave_sub();
1310 }
1311
1312 sub vendor_details {
1313   $lxdebug->enter_sub();
1314
1315   IR->vendor_details(\%myconfig, \%$form, @_);
1316
1317   $lxdebug->leave_sub();
1318 }
1319
1320 sub post_as_new {
1321   $lxdebug->enter_sub();
1322
1323   $form->{postasnew} = 1;
1324   map { delete $form->{$_} } qw(printed emailed queued);
1325
1326   &post;
1327
1328   $lxdebug->leave_sub();
1329 }
1330
1331 sub ship_to {
1332   $lxdebug->enter_sub();
1333   if ($form->{second_run}) {
1334     $form->{print_and_post} = 0;
1335   }
1336
1337   $title = $form->{title};
1338   $form->{title} = $locale->text('Ship to');
1339
1340   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
1341     qw(exchangerate creditlimit creditremaining);
1342
1343   my @shipto_vars =
1344     qw(shiptoname shiptostreet shiptozipcode shiptocity shiptocountry
1345        shiptocontact shiptophone shiptofax shiptoemail
1346        shiptodepartment_1 shiptodepartment_2);
1347
1348   my @addr_vars =
1349     (qw(name department_1 department_2 street zipcode city country
1350         contact email phone fax));
1351
1352   # get details for name
1353   call_sub("$form->{vc}_details", @addr_vars);
1354
1355   $number =
1356     ($form->{vc} eq 'customer')
1357     ? $locale->text('Customer Number')
1358     : $locale->text('Vendor Number');
1359
1360   # get pricegroups for parts
1361   IS->get_pricegroups_for_parts(\%myconfig, \%$form);
1362
1363   # build up html code for prices_$i
1364   set_pricegroup($form->{rowcount});
1365
1366   $nextsub = ($form->{display_form}) ? $form->{display_form} : "display_form";
1367
1368   $form->{rowcount}--;
1369
1370   $form->header;
1371
1372   print qq|
1373 <body>
1374
1375 <form method="post" action="$form->{script}">
1376
1377 <table width="100%">
1378   <tr>
1379     <td>
1380       <table>
1381         <tr class="listheading">
1382           <th class="listheading" colspan="2" width="50%">|
1383     . $locale->text('Billing Address') . qq|</th>
1384           <th class="listheading" width="50%">|
1385     . $locale->text('Shipping Address') . qq|</th>
1386         </tr>
1387         <tr height="5"></tr>
1388         <tr>
1389           <th align="right" nowrap>$number</th>
1390           <td>$form->{"$form->{vc}number"}</td>
1391         </tr>
1392         <tr>
1393           <th align="right" nowrap>| . $locale->text('Company Name') . qq|</th>
1394           <td>$form->{name}</td>
1395           <td><input name="shiptoname" size="35" value="$form->{shiptoname}"></td>
1396         </tr>
1397         <tr>
1398           <th align="right" nowrap>| . $locale->text('Department') . qq|</th>
1399           <td>$form->{department_1}</td>
1400           <td><input name="shiptodepartment_1" size="35" value="$form->{shiptodepartment_1}"></td>
1401         </tr>
1402         <tr>
1403           <th align="right" nowrap>&nbsp;</th>
1404           <td>$form->{department_2}</td>
1405           <td><input name="shiptodepartment_2" size="35" value="$form->{shiptodepartment_2}"></td>
1406         </tr>
1407         <tr>
1408           <th align="right" nowrap>| . $locale->text('Street') . qq|</th>
1409           <td>$form->{street}</td>
1410           <td><input name="shiptostreet" size="35" value="$form->{shiptostreet}"></td>
1411         </tr>
1412         <tr>
1413           <th align="right" nowrap>| . $locale->text('Zipcode') . qq|</th>
1414           <td>$form->{zipcode}</td>
1415           <td><input name="shiptozipcode" size="35" value="$form->{shiptozipcode}"></td>
1416         </tr>
1417         <tr>
1418           <th align="right" nowrap>| . $locale->text('City') . qq|</th>
1419           <td>$form->{city}</td>
1420           <td><input name="shiptocity" size="35" value="$form->{shiptocity}"></td>
1421         </tr>
1422         <tr>
1423           <th align="right" nowrap>| . $locale->text('Country') . qq|</th>
1424           <td>$form->{country}</td>
1425           <td><input name="shiptocountry" size="35" value="$form->{shiptocountry}"></td>
1426         </tr>
1427         <tr>
1428           <th align="right" nowrap>| . $locale->text('Contact') . qq|</th>
1429           <td>$form->{contact}</td>
1430           <td><input name="shiptocontact" size="35" value="$form->{shiptocontact}"></td>
1431         </tr>
1432         <tr>
1433           <th align="right" nowrap>| . $locale->text('Phone') . qq|</th>
1434           <td>$form->{phone}</td>
1435           <td><input name="shiptophone" size="20" value="$form->{shiptophone}"></td>
1436         </tr>
1437         <tr>
1438           <th align="right" nowrap>| . $locale->text('Fax') . qq|</th>
1439           <td>$form->{fax}</td>
1440           <td><input name="shiptofax" size="20" value="$form->{shiptofax}"></td>
1441         </tr>
1442         <tr>
1443           <th align="right" nowrap>| . $locale->text('E-mail') . qq|</th>
1444           <td>$form->{email}</td>
1445           <td><input name="shiptoemail" size="35" value="$form->{shiptoemail}"></td>
1446         </tr>
1447       </table>
1448     </td>
1449   </tr>
1450 </table>
1451 | . $cgi->hidden("-name" => "nextsub", "-value" => $nextsub);
1452 ;
1453
1454
1455
1456   # delete shipto
1457   map({ delete $form->{$_} } (@shipto_vars, qw(header)));
1458   $form->{title} = $title;
1459
1460   foreach $key (keys %$form) {
1461     $form->{$key} =~ s/\"/&quot;/g;
1462     print qq|<input type="hidden" name="$key" value="$form->{$key}">\n|;
1463   }
1464
1465   print qq|
1466
1467 <hr size="3" noshade>
1468
1469 <br>
1470 <input class="submit" type="submit" name="action" value="|
1471     . $locale->text('Continue') . qq|">
1472 </form>
1473
1474 </body>
1475 </html>
1476 |;
1477
1478   $lxdebug->leave_sub();
1479 }
1480
1481 sub new_license {
1482   $lxdebug->enter_sub();
1483
1484   my $row = shift;
1485
1486   # change callback
1487   $form->{old_callback} = $form->escape($form->{callback}, 1);
1488   $form->{callback} = $form->escape("$form->{script}?action=display_form", 1);
1489   $form->{old_callback} = $form->escape($form->{old_callback}, 1);
1490
1491   # delete action
1492   delete $form->{action};
1493   $customer = $form->{customer};
1494   map { $form->{"old_$_"} = $form->{"${_}_$row"} } qw(partnumber description);
1495
1496   # save all other form variables in a previousform variable
1497   $form->{row} = $row;
1498   foreach $key (keys %$form) {
1499
1500     # escape ampersands
1501     $form->{$key} =~ s/&/%26/g;
1502     $previousform .= qq|$key=$form->{$key}&|;
1503   }
1504   chop $previousform;
1505   $previousform = $form->escape($previousform, 1);
1506
1507   $form->{script} = "licenses.pl";
1508
1509   map { $form->{$_} = $form->{"old_$_"} } qw(partnumber description);
1510   map { $form->{$_} = $form->escape($form->{$_}, 1) }
1511     qw(partnumber description);
1512   $form->{callback} =
1513     qq|$form->{script}?login=$form->{login}&password=$form->{password}&action=add&vc=$form->{db}&$form->{db}_id=$form->{id}&$form->{db}=$name&type=$form->{type}&customer=$customer&partnumber=$form->{partnumber}&description=$form->{description}&previousform="$previousform"&initial=1|;
1514   $form->redirect;
1515
1516   $lxdebug->leave_sub();
1517 }
1518
1519 sub relink_accounts {
1520   $lxdebug->enter_sub();
1521
1522   $form->{"taxaccounts"} =~ s/\s*$//;
1523   $form->{"taxaccounts"} =~ s/^\s*//;
1524   foreach my $accno (split(/\s*/, $form->{"taxaccounts"})) {
1525     map({ delete($form->{"${accno}_${_}"}); } qw(rate description taxnumber));
1526   }
1527   $form->{"taxaccounts"} = "";
1528
1529   for (my $i = 1; $i <= $form->{"rowcount"}; $i++) {
1530     if ($form->{"id_$i"}) {
1531       IC->retrieve_accounts(\%myconfig, $form, $form->{"id_$i"}, $i, 1);
1532     }
1533   }
1534
1535   $lxdebug->leave_sub();
1536 }
1537
1538 sub set_duedate {
1539   $lxdebug->enter_sub();
1540
1541   $form->get_duedate(\%myconfig);
1542
1543   my $q = new CGI;
1544   $result = "$form->{duedate}";
1545   print $q->header();
1546   print $result;
1547   $lxdebug->leave_sub();
1548
1549 }
1550