Auslagerung gemeinsamen Codes.
[kivitendo-erp.git] / bin / mozilla / oe.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-2003
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 # Order entry module
31 # Quotation module
32 #======================================================================
33
34 use POSIX qw(strftime);
35
36 use SL::DO;
37 use SL::FU;
38 use SL::OE;
39 use SL::IR;
40 use SL::IS;
41 use SL::PE;
42 use SL::ReportGenerator;
43 use List::Util qw(max reduce sum);
44
45 require "bin/mozilla/io.pl";
46 require "bin/mozilla/arap.pl";
47 require "bin/mozilla/reportgenerator.pl";
48
49 1;
50
51 # end of main
52
53 # For locales.pl:
54 # $locale->text('Edit the purchase_order');
55 # $locale->text('Edit the sales_order');
56 # $locale->text('Edit the request_quotation');
57 # $locale->text('Edit the sales_quotation');
58
59 # $locale->text('Workflow purchase_order');
60 # $locale->text('Workflow sales_order');
61 # $locale->text('Workflow request_quotation');
62 # $locale->text('Workflow sales_quotation');
63
64 my $oe_access_map = {
65   'sales_order'       => 'sales_order_edit',
66   'purchase_order'    => 'purchase_order_edit',
67   'request_quotation' => 'request_quotation_edit',
68   'sales_quotation'   => 'sales_quotation_edit',
69 };
70
71 sub check_oe_access {
72   my $right   = $oe_access_map->{$form->{type}};
73   $right    ||= 'DOES_NOT_EXIST';
74
75   $auth->assert($right);
76 }
77
78 sub set_headings {
79   $lxdebug->enter_sub();
80
81   check_oe_access();
82
83   my ($action) = @_;
84
85   if ($form->{type} eq 'purchase_order') {
86     $form->{title}   = $action eq "edit" ?
87       $locale->text('Edit Purchase Order') :
88       $locale->text('Add Purchase Order');
89     $form->{heading} = $locale->text('Purchase Order');
90     $form->{vc}      = 'vendor';
91   }
92   if ($form->{type} eq 'sales_order') {
93     $form->{title}   = $action eq "edit" ?
94       $locale->text('Edit Sales Order') :
95       $locale->text('Add Sales Order');
96     $form->{heading} = $locale->text('Sales Order');
97     $form->{vc}      = 'customer';
98   }
99   if ($form->{type} eq 'request_quotation') {
100     $form->{title}   = $action eq "edit" ?
101       $locale->text('Edit Request for Quotation') :
102       $locale->text('Add Request for Quotation');
103     $form->{heading} = $locale->text('Request for Quotation');
104     $form->{vc}      = 'vendor';
105   }
106   if ($form->{type} eq 'sales_quotation') {
107     $form->{title}   = $action eq "edit" ?
108       $locale->text('Edit Quotation') :
109       $locale->text('Add Quotation');
110     $form->{heading} = $locale->text('Quotation');
111     $form->{vc}      = 'customer';
112   }
113
114   $lxdebug->leave_sub();
115 }
116
117 sub add {
118   $lxdebug->enter_sub();
119
120   check_oe_access();
121
122   set_headings("add");
123
124   $form->{callback} =
125     "$form->{script}?action=add&type=$form->{type}&vc=$form->{vc}"
126     unless $form->{callback};
127
128   &order_links;
129   &prepare_order;
130   &display_form;
131
132   $lxdebug->leave_sub();
133 }
134
135 sub edit {
136   $lxdebug->enter_sub();
137
138   check_oe_access();
139
140   # show history button
141   $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
142   #/show hhistory button
143
144   $form->{simple_save} = 0;
145
146   set_headings("edit");
147
148   # editing without stuff to edit? try adding it first
149   if ($form->{rowcount} && !$form->{print_and_save}) {
150     map { $id++ if $form->{"multi_id_$_"} } (1 .. $form->{rowcount});
151     if (!$id) {
152
153       # reset rowcount
154       undef $form->{rowcount};
155       &add;
156       $lxdebug->leave_sub();
157       return;
158     }
159   } elsif (!$form->{id}) {
160     &add;
161     $lxdebug->leave_sub();
162     return;
163   }
164
165   if ($form->{print_and_save}) {
166     $form->{action}   = "print";
167     $form->{resubmit} = 1;
168     $language_id = $form->{language_id};
169     $printer_id = $form->{printer_id};
170   }
171
172   set_headings("edit");
173
174   &order_links;
175
176   $form->{rowcount} = 0;
177   foreach $ref (@{ $form->{form_details} }) {
178     $form->{rowcount}++;
179     map { $form->{"${_}_$form->{rowcount}"} = $ref->{$_} } keys %{$ref};
180   }
181
182   &prepare_order;
183
184   if ($form->{print_and_save}) {
185     $form->{language_id} = $language_id;
186     $form->{printer_id} = $printer_id;
187   }
188
189   &display_form;
190
191   $lxdebug->leave_sub();
192 }
193
194 sub order_links {
195   $lxdebug->enter_sub();
196
197   check_oe_access();
198
199   # get customer/vendor
200   $form->all_vc(\%myconfig, $form->{vc}, ($form->{vc} eq 'customer') ? "AR" : "AP");
201
202   # retrieve order/quotation
203   $form->{webdav}   = $webdav;
204   $form->{jsscript} = 1;
205
206   my $editing = $form->{id};
207
208   OE->retrieve(\%myconfig, \%$form);
209
210   # if multiple rowcounts (== collective order) then check if the
211   # there were more than one customer (in that case OE::retrieve removes
212   # the content from the field)
213   $form->error($locale->text('Collective Orders only work for orders from one customer!'))
214     if          $form->{rowcount}  && $form->{type}     eq 'sales_order'
215      && defined $form->{customer}  && $form->{customer} eq '';
216
217   $form->{"$form->{vc}_id"} ||= $form->{"all_$form->{vc}"}->[0]->{id} if $form->{"all_$form->{vc}"};
218
219   $form->backup_vars(qw(payment_id language_id taxzone_id salesman_id taxincluded cp_id intnotes));
220   $form->{shipto} = 1 if $form->{id};
221
222   # get customer / vendor
223   IR->get_vendor(\%myconfig, \%$form)   if $form->{type} =~ /(purchase_order|request_quotation)/;
224   IS->get_customer(\%myconfig, \%$form) if $form->{type} =~ /sales_(order|quotation)/;
225
226   $form->restore_vars(qw(payment_id language_id taxzone_id intnotes cp_id));
227   $form->restore_vars(qw(taxincluded)) if $form->{id};
228   $form->restore_vars(qw(salesman_id)) if $editing;
229   $form->{forex}       = $form->{exchangerate};
230   $form->{employee}    = "$form->{employee}--$form->{employee_id}";
231
232   # build vendor/customer drop down comatibility... don't ask
233   if (@{ $form->{"all_$form->{vc}"} }) {
234     $form->{"select$form->{vc}"} = 1;
235     $form->{$form->{vc}}         = qq|$form->{$form->{vc}}--$form->{"$form->{vc}_id"}|;
236   }
237
238   $form->{"old$form->{vc}"}  = $form->{$form->{vc}};
239   $form->{"old$form->{vc}"} .= qq|--$form->{"$form->{vc}_id"}| unless ($form->{"old$form->{vc}"} =~ m/--\d+$/);
240
241   $lxdebug->leave_sub();
242 }
243
244 sub prepare_order {
245   $lxdebug->enter_sub();
246
247   check_oe_access();
248
249   $form->{formname} ||= $form->{type};
250
251   for my $i (1 .. $form->{rowcount}) {
252     $form->{"reqdate_$i"} ||= $form->{"deliverydate_$i"};
253     $form->{"discount_$i"}  = $form->format_amount(\%myconfig, $form->{"discount_$i"} * ($form->{id} ? 100 : 1));
254     $form->{"sellprice_$i"} = $form->format_amount(\%myconfig, $form->{"sellprice_$i"});
255     $form->{"qty_$i"}       = $form->format_amount(\%myconfig, $form->{"qty_$i"});
256   }
257
258   $lxdebug->leave_sub();
259 }
260
261 sub form_header {
262   $lxdebug->enter_sub();
263   my @custom_hiddens;
264
265   check_oe_access();
266
267   # Container for template variables. Unfortunately this has to be visible in form_footer too, so not my.
268   our %TMPL_VAR = ();
269
270   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
271
272   $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
273   $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
274
275   map { $form->{$_} = H($form->{$_}) }
276     qw(shippingpoint shipvia notes intnotes shiptoname
277        shiptostreet shiptozipcode shiptocity shiptocountry shiptocontact
278        shiptophone shiptofax shiptodepartment_1 shiptodepartment_2);
279  
280   # use JavaScript Calendar or not
281   $form->{jsscript} = 1;
282   $TMPL_VAR{button1} = qq|
283      <td nowrap><input name=transdate id=transdate size=11 title="$myconfig{dateformat}" value="$form->{transdate}" onBlur=\"check_right_date_format(this)\">
284       <input type=button name=transdate id="trigger1" value=| . $locale->text('button') . qq|></td>
285     |;
286   $TMPL_VAR{button2} = qq|
287      <td nowrap width="13"><input name=reqdate id=reqdate size=11 title="$myconfig{dateformat}" value="$form->{reqdate}" onBlur=\"check_right_date_format(this)\">
288       <input type=button name=reqdate name=reqdate id="trigger2" value=| . $locale->text('button') . qq|></td>
289    |;
290   #write Trigger
291   $TMPL_VAR{jsscript} = Form->write_trigger(\%myconfig, "2", "transdate", "BL", "trigger1", "reqdate", "BL", "trigger2");
292
293   # openclosed checkboxes
294   my @tmp;
295   push @tmp, sprintf qq|<input name="delivered" id="delivered" type="checkbox" class="checkbox" value="1" %s><label for="delivered">%s</label>|,
296                         $form->{"delivered"} ? "checked" : "",  $locale->text('Delivered') if $form->{"type"} =~ /_order$/;
297   push @tmp, sprintf qq|<input name="closed" id="closed" type="checkbox" class="checkbox" value="1" %s><label for="closed">%s</label>|,
298                         $form->{"closed"}    ? "checked" : "",  $locale->text('Closed')    if $form->{id};
299   $TMPL_VAR{openclosed} = sprintf qq|<tr><td colspan=%d align=center>%s</td></tr>\n|, 2 * scalar @tmp, join "\n", @tmp if @tmp;
300
301   # set option selected
302   foreach $item ($form->{vc}, 'currency', 'department', ($form->{vc} eq "customer" ? 'customer' : 'vendor')) {
303     $form->{"select$item"} =~ s/ selected//;
304     $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
305   }
306
307   #quote select[customer|vendor] Bug 133
308   $form->{"select$form->{vc}"} = $form->quote($form->{"select$form->{vc}"});
309
310   #substitute \n and \r to \s (bug 543)
311   $form->{"select$form->{vc}"} =~ s/[\n\r]/&nbsp;/g;
312   
313   my @old_project_ids = ($form->{"globalproject_id"}, grep { $_ } map { $form->{"project_id_$_"} } 1..$form->{"rowcount"});
314
315   my $vc = $form->{vc} eq "customer" ? "customers" : "vendors";
316   $form->get_lists("contacts"      => "ALL_CONTACTS",
317                    "shipto"        => "ALL_SHIPTO",
318                    "projects"      => { "key"      => "ALL_PROJECTS",
319                                         "all"      => 0,
320                                         "old_id"   => \@old_project_ids },
321                    "employees"     => "ALL_EMPLOYEES",
322                    "salesmen"      => "ALL_SALESMEN",
323                    "taxzones"      => "ALL_TAXZONES",
324                    "payments"      => "ALL_PAYMENTS",
325                    "currencies"    => "ALL_CURRENCIES",
326                    "departments"   => "ALL_DEPARTMENTS",
327                    $vc             => { key   => "ALL_" . uc($vc),
328                                         limit => $myconfig{vclimit} + 1 },
329                    "price_factors" => "ALL_PRICE_FACTORS");
330
331   # label subs
332   $TMPL_VAR{sales_employee_labels} = sub { $_[0]->{name} || $_[0]->{login} };
333   $TMPL_VAR{shipto_labels}         = sub { join "; ", grep { $_ } map { $_[0]->{"shipto${_}" } } qw(name department_1 street city) };
334   $TMPL_VAR{contact_labels}        = sub { join(', ', $_[0]->{"cp_name"}, $_[0]->{"cp_givenname"}) . ($_[0]->{cp_abteilung} ? " ($_[0]->{cp_abteilung})" : "") };
335   $TMPL_VAR{department_labels}     = sub { "$_[0]->{description}--$_[0]->{id}" }; 
336
337   # vendor/customer
338   $TMPL_VAR{vc_keys} = sub { "$_[0]->{name}--$_[0]->{id}" };
339   $TMPL_VAR{vclimit} = $myconfig{vclimit};
340   $TMPL_VAR{vc_select} = "customer_or_vendor_selection_window('$form->{vc}', '', @{[ $form->{vc} eq 'vendor' ? 1 : 0 ]}, 0)";
341   push @custom_hiddens, "$form->{vc}_id";
342   push @custom_hiddens, "old$form->{vc}";
343   push @custom_hiddens, "select$form->{vc}";
344
345   # currencies and exchangerate
346   @values = map { $_ } @{ $form->{ALL_CURRENCIES} };
347   %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
348   $form->{currency}            = $form->{defaultcurrency} unless $form->{currency};
349   $TMPL_VAR{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
350   $TMPL_VAR{currencies}        = NTI($cgi->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
351                                                       '-values' => \@values, '-labels' => \%labels)) if scalar @values;
352   push @custom_hiddens, "forex";
353   push @custom_hiddens, "exchangerate" if $form->{forex};
354
355   # credit remaining
356   $creditwarning = (($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update}) ? 1 : 0;
357   $TMPL_VAR{is_credit_remaining_negativ} = ($form->{creditremaining} =~ /-/) ? "0" : "1";
358   
359   # business
360   $TMPL_VAR{business_label} = ($form->{vc} eq "customer" ? $locale->text('Customer type') : $locale->text('Vendor type'));
361
362   push @custom_hiddens, "ordnumber"      if $form->{type} =~ /_quotation$/;
363   push @custom_hiddens, "customer_klass" if $form->{vc} eq 'customer';
364
365   $credittext = $locale->text('Credit Limit exceeded!!!');
366
367   my $follow_up_vc                =  $form->{ $form->{vc} eq 'customer' ? 'customer' : 'vendor' };
368   $follow_up_vc                   =~ s/--.*?//;
369   $TMPL_VAR{follow_up_trans_info} =  ($form->{type} =~ /_quotation$/ ? $form->{quonumber} : $form->{ordnumber}) . " ($follow_up_vc)";
370
371   if ($form->{id}) {
372     my $follow_ups = FU->follow_ups('trans_id' => $form->{id});
373
374     if (scalar @{ $follow_ups }) {
375       $TMPL_VAR{num_follow_ups}     = scalar                    @{ $follow_ups };
376       $TMPL_VAR{num_due_follow_ups} = sum map { $_->{due} * 1 } @{ $follow_ups };
377     }
378   }
379
380   $onload = ($form->{resubmit} && ($form->{format} eq "html")) ? "window.open('about:blank','Beleg'); document.oe.target = 'Beleg';document.oe.submit()"
381           : ($form->{resubmit})                                ? "document.oe.submit()"
382           : ($creditwarning)                                   ? "alert('$credittext')"
383           :                                                      "focus()";
384
385   $onload .= qq|;setupDateFormat('|. $myconfig{dateformat} .qq|', '|. $locale->text("Falsches Datumsformat!") .qq|')|;
386   $onload .= qq|;setupPoints('|.   $myconfig{numberformat} .qq|', '|. $locale->text("wrongformat") .qq|')|;
387   $TMPL_VAR{onload} = $onload;
388
389   $form->{javascript} .= qq|<script type="text/javascript" src="js/show_form_details.js"></script>|;
390   $form->{javascript} .= qq|<script type="text/javascript" src="js/show_history.js"></script>|;
391   $form->{javascript} .= qq|<script type="text/javascript" src="js/show_vc_details.js"></script>|;
392
393   $form->header;
394
395   $TMPL_VAR{HIDDENS} = [ map { name => $_, value => $form->{$_} },
396      qw(id action type vc formname media format proforma queued printed emailed
397         title creditlimit creditremaining tradediscount business
398         max_dunning_level dunning_amount shiptoname shiptostreet shiptozipcode
399         shiptocity shiptocountry shiptocontact shiptophone shiptofax
400         shiptodepartment_1 shiptodepartment_2 shiptoemail
401         message email subject cc bcc taxpart taxservice taxaccounts cursor_fokus),
402         @custom_hiddens,
403         map { $_.'_rate', $_.'_description' } split / /, $form->{taxaccounts} ];  # deleted: discount
404
405   %TMPL_VAR = (
406      %TMPL_VAR,
407      is_sales        => scalar ($form->{type} =~ /^sales_/),              # these vars are exported, so that the template
408      is_order        => scalar ($form->{type} =~ /_order$/),              # may determine what to show
409      is_sales_quo    => scalar ($form->{type} =~ /sales_quotation$/),
410      is_req_quo      => scalar ($form->{type} =~ /request_quotation$/),
411      is_sales_ord    => scalar ($form->{type} =~ /sales_order$/),
412      is_pur_ord      => scalar ($form->{type} =~ /purchase_order$/),
413   );
414
415   print $form->parse_html_template("oe/form_header", { %TMPL_VAR });
416
417   $lxdebug->leave_sub();
418 }
419
420 sub form_footer {
421   $lxdebug->enter_sub();
422
423   check_oe_access();
424
425   $form->{invtotal} = $form->{invsubtotal};
426
427   $rows    = max 2, $form->numtextrows($form->{notes}, 25, 8);
428   $introws = max 2, $form->numtextrows($form->{intnotes}, 35, 8);
429   $rows    = max $rows, $introws;
430
431   $TMPL_VAR{notes} = qq|<textarea name=notes rows=$rows cols=25 wrap=soft>$form->{notes}</textarea>|;
432   $TMPL_VAR{intnotes} = qq|<textarea name=intnotes rows=$rows cols=35 wrap=soft>$form->{intnotes}</textarea>|;
433
434   if (!$form->{taxincluded}) {
435
436     foreach $item (split / /, $form->{taxaccounts}) {
437       if ($form->{"${item}_base"}) {
438         $form->{invtotal} += $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
439         $form->{"${item}_total"} = $form->format_amount(\%myconfig, $form->{"${item}_total"}, 2);
440
441         $TMPL_VAR{tax} .= qq|
442               <tr>
443                 <th align=right>$form->{"${item}_description"}&nbsp;| . $form->{"${item}_rate"} * 100 .qq|%</th>
444                 <td align=right>$form->{"${item}_total"}</td>
445               </tr> |;
446       }
447     }
448
449     $form->{invsubtotal} = $form->format_amount(\%myconfig, $form->{invsubtotal}, 2, 0);
450
451   } else {
452     foreach $item (split / /, $form->{taxaccounts}) {
453       if ($form->{"${item}_base"}) {
454         $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"} / (1 + $form->{"${item}_rate"})), 2);
455         $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
456         $form->{"${item}_total"} = $form->format_amount(\%myconfig, $form->{"${item}_total"}, 2);
457         $form->{"${item}_netto"} = $form->format_amount(\%myconfig, $form->{"${item}_netto"}, 2);
458
459         $TMPL_VAR{tax} .= qq|
460               <tr>
461                 <th align=right>Enthaltene $form->{"${item}_description"}&nbsp;| . $form->{"${item}_rate"} * 100 .qq|%</th>
462                 <td align=right>$form->{"${item}_total"}</td>
463               </tr>
464               <tr>
465                 <th align=right>Nettobetrag</th>
466                 <td align=right>$form->{"${item}_netto"}</td>
467               </tr> |;
468       }
469     }
470   }
471
472   $form->{oldinvtotal} = $form->{invtotal};
473
474   print $form->parse_html_template("oe/form_footer", {
475      %TMPL_VAR,
476      webdav          => $webdav,
477      print_options   => print_options(inline => 1),
478      label_edit      => $locale->text("Edit the $form->{type}"),
479      label_workflow  => $locale->text("Workflow $form->{type}"),
480   });
481
482   $lxdebug->leave_sub();
483 }
484
485 sub update {
486   $lxdebug->enter_sub();
487   
488   my ($recursive_call) = shift;
489
490   check_oe_access();
491
492   set_headings($form->{"id"} ? "edit" : "add");
493
494   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) } qw(exchangerate) unless $recursive_call;
495   $form->{update} = 1;
496       
497   $payment_id = $form->{payment_id} if $form->{payment_id};
498   
499   &check_name($form->{vc});
500   
501   $form->{payment_id} = $payment_id if $form->{payment_id} eq "";
502   
503   $buysell              = 'buy';
504   $buysell              = 'sell' if ($form->{vc} eq 'vendor');
505   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{transdate}, $buysell);
506   $form->{exchangerate} = $form->{forex} if $form->{forex};
507
508   $exchangerate = $form->{exchangerate} || 1;
509
510 ##################### process items ######################################
511   # for pricegroups
512   $i = $form->{rowcount};
513   if (   ($form->{"partnumber_$i"} eq "")
514       && ($form->{"description_$i"} eq "")
515       && ($form->{"partsgroup_$i"}  eq "")) {
516
517     $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
518     &check_form;
519
520   } else {
521
522     if ($form->{type} =~ /^sales/) {
523       IS->retrieve_item(\%myconfig, \%$form);
524     } else {
525       IR->retrieve_item(\%myconfig, \%$form);
526     }
527
528     my $rows = scalar @{ $form->{item_list} };
529
530     $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{discount} * 100);
531
532     if ($rows) {
533       $form->{"qty_$i"} = 1 unless ($form->{"qty_$i"});
534
535       if ($rows > 1) {
536
537         &select_item;
538         exit;
539
540       } else {
541
542         $sellprice             = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
543         $form->{"discount_$i"} = 0 if $form->{"not_discountable_$i"};
544         map { $form->{item_list}[$i]{$_} =~ s/\"/&quot;/g }    qw(partnumber description unit);
545         map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
546         $form->{payment_id} = $form->{"part_payment_id_$i"} if $form->{"part_payment_id_$i"} ne "";
547
548         $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
549
550         ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
551         $decimalplaces = max 2, length $1;
552
553         if ($sellprice) {
554           $form->{"sellprice_$i"} = $sellprice;
555         } else {
556           $form->{"sellprice_$i"} *= (1 - $form->{tradediscount});
557           $form->{"sellprice_$i"} /= $exchangerate;   # if there is an exchange rate adjust sellprice
558         }
559
560         $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"} / 100);
561         map { $form->{"${_}_base"} = 0 }                                 split / /, $form->{taxaccounts};
562         map { $form->{"${_}_base"} += $amount }                          split / /, $form->{"taxaccounts_$i"};
563         map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{taxaccounts} if !$form->{taxincluded};
564
565         $form->{creditremaining} -= $amount;
566
567         $form->{"sellprice_$i"} = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
568         $form->{"qty_$i"}       = $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
569
570         # get pricegroups for parts
571         IS->get_pricegroups_for_parts(\%myconfig, \%$form);
572
573         # build up html code for prices_$i
574         &set_pricegroup($i);
575       }
576
577       display_form();
578     } else {
579
580       # ok, so this is a new part
581       # ask if it is a part or service item
582
583       if (   $form->{"partsgroup_$i"}
584           && ($form->{"partsnumber_$i"} eq "")
585           && ($form->{"description_$i"} eq "")) {
586         $form->{rowcount}--;
587         $form->{"discount_$i"} = "";
588
589         display_form();
590       } else {
591         $form->{"id_$i"}   = 0;
592         new_item();
593       }
594     }
595   }
596 ##################### process items ######################################
597
598
599   $lxdebug->leave_sub();
600 }
601
602 sub search {
603   $lxdebug->enter_sub();
604
605   check_oe_access();
606
607   if ($form->{type} eq 'purchase_order') {
608     $form->{title} = $locale->text('Purchase Orders');
609     $form->{vc}    = 'vendor';
610     $ordlabel      = $locale->text('Order Number');
611     $ordnumber     = 'ordnumber';
612     $employee      = $locale->text('Employee');
613   }
614
615   if ($form->{type} eq 'request_quotation') {
616     $form->{title} = $locale->text('Request for Quotations');
617     $form->{vc}    = 'vendor';
618     $ordlabel      = $locale->text('RFQ Number');
619     $ordnumber     = 'quonumber';
620     $employee      = $locale->text('Employee');
621   }
622
623   if ($form->{type} eq 'sales_order') {
624     $form->{title} = $locale->text('Sales Orders');
625     $form->{vc}    = 'customer';
626     $ordlabel      = $locale->text('Order Number');
627     $ordnumber     = 'ordnumber';
628     $employee      = $locale->text('Employee');
629   }
630
631   if ($form->{type} eq 'sales_quotation') {
632     $form->{title} = $locale->text('Quotations');
633     $form->{vc}    = 'customer';
634     $ordlabel      = $locale->text('Quotation Number');
635     $ordnumber     = 'quonumber';
636     $employee      = $locale->text('Employee');
637   }
638
639   # setup vendor / customer selection
640   $form->all_vc(\%myconfig, $form->{vc},
641                 ($form->{vc} eq 'customer') ? "AR" : "AP");
642
643   # departments
644   if (@{ $form->{all_departments} }) {
645     $form->{selectdepartment} = "<option>\n";
646
647     map {
648       $form->{selectdepartment} .=
649         "<option>$_->{description}--$_->{id}</option>\n"
650     } (@{ $form->{all_departments} });
651   }
652
653   $department = qq|
654         <tr>
655           <th align=right nowrap>| . $locale->text('Department') . qq|</th>
656           <td colspan=3><select name=department>$form->{selectdepartment}</select></td>
657         </tr>
658 | if $form->{selectdepartment};
659
660   my $delivered;
661   if (($form->{"type"} eq "sales_order") ||
662       ($form->{"type"} eq "purchase_order")) {
663     $delivered = qq|
664         <tr>
665           <td><input name="notdelivered" id="notdelivered" class="checkbox" type="checkbox" value="1" checked>
666             <label for="notdelivered">|. $locale->text('Not delivered') . qq|</label></td>
667           <td><input name="delivered" id="delivered" class="checkbox" type="checkbox" value="1" checked>
668             <label for="delivered">| . $locale->text('Delivered') . qq|</label></td>
669         </tr>
670 |;
671   }
672
673   # use JavaScript Calendar or not
674   $form->{jsscript} = 1;
675   $jsscript = "";
676
677   $button1 = qq|
678      <td><input name=transdatefrom id=transdatefrom size=11 title="$myconfig{dateformat}" onBlur=\"check_right_date_format(this)\">
679      <input type=button name=transdatefrom id="trigger3" value=|
680     . $locale->text('button') . qq|></td>
681     |;
682   $button2 = qq|
683      <td><input name=transdateto id=transdateto size=11 title="$myconfig{dateformat}" onBlur=\"check_right_date_format(this)\">
684      <input type=button name=transdateto name=transdateto id="trigger4" value=|
685     . $locale->text('button') . qq|></td>
686    |;
687
688   #write Trigger
689   $jsscript =
690     Form->write_trigger(\%myconfig, "2", "transdatefrom", "BR", "trigger3",
691                         "transdateto", "BL", "trigger4");
692
693   my $vc = $form->{vc} eq "customer" ? "customers" : "vendors";
694
695   $form->get_lists("projects"  => { "key" => "ALL_PROJECTS",
696                                     "all" => 1 },
697                    "employees" => "ALL_EMPLOYEES",
698                    "salesmen"  => "ALL_SALESMEN",
699                    $vc         => "ALL_" . uc($vc)
700                   );
701
702   my %labels = ();
703   my @values = ("");
704   foreach my $item (@{ $form->{"ALL_PROJECTS"} }) {
705     push(@values, $item->{"id"});
706     $labels{$item->{"id"}} = $item->{"projectnumber"};
707   }
708   my $projectnumber =
709     NTI($cgi->popup_menu('-name' => 'project_id', '-values' => \@values,
710                          '-labels' => \%labels));
711
712   #employees
713   %labels = ();
714   @values = ("");
715   foreach my $item (@{ $form->{"ALL_EMPLOYEES"} }) {
716     push(@values, $item->{"id"});
717     $labels{$item->{"id"}} = $item->{"name"} ne "" ? $item->{"name"} : $item->{"login"};
718   }
719   
720   #salesmen
721   my %labels_salesmen = ();
722   my @values_salesmen = ('');
723   foreach my $item (@{ $form->{"ALL_SALESMEN"} }) {
724     push(@values_salesmen, $item->{"id"});
725     $labels_salesmen{$item->{"id"}} = $item->{"name"} ne "" ? $item->{"name"} : $item->{"login"};
726   }
727
728   my $employee_block = qq|
729     <tr>
730       <th align="right">| . $locale->text('Employee') . qq|</th>
731       <td>| .  NTI($cgi->popup_menu('-name'   => 'employee_id', '-values' => \@values, '-labels' => \%labels)) . qq|</td>
732     </tr>
733     <tr>
734       <th align="right">| . $locale->text('Salesman') . qq|</th>
735       <td>| .
736         NTI($cgi->popup_menu('-name'   => 'salesman_id',
737                              '-values' => \@values_salesmen,
738                              '-labels' => \%labels_salesmen)) . qq|
739       </td>
740     </tr>|;
741
742   %labels = ();
743   @values = ("");
744
745   foreach my $item (@{ $form->{($form->{vc} eq "customer" ? "ALL_CUSTOMERS" : "ALL_VENDORS")}}) {
746     push(@values, $item->{name}.qq|--|.$item->{"id"});
747     $labels{$item->{name}.qq|--|.$item->{"id"}} = $item->{"name"};
748   }
749
750   my $vc_label = $form->{vc} eq "customer" ? $locale->text('Customer') : $locale->text('Vendor');
751   $vc =
752     $myconfig{vclimit} <=  scalar(@values)
753     ? qq|<input type="text" value="| . H(($form->{"old$form->{vc}"} =~ /^(.*)\-\-.*$/)) . qq|" name="$form->{vc}">| 
754     : NTI($cgi->popup_menu('-name' => "$form->{vc}",
755                            '-default' => $form->{"old$form->{vc}"},
756                            '-onChange' => 'document.getElementById(\'update_button\').click();',
757                            '-values' => \@values,
758                            '-labels' => \%labels));
759   $form->header;
760
761   print qq|
762 <body>
763
764 <form method=post action=$form->{script}>
765
766 <table width=100%>
767   <tr>
768     <th class=listtop>$form->{title}</th>
769   </tr>
770   <tr height="5"></tr>
771   <tr>
772     <td>
773       <table>
774         <tr>
775           <th align=right>$vc_label</th>
776           <td colspan=3>$vc</td>
777         </tr>
778 $department
779         <tr>
780           <th align=right>$ordlabel</th>
781           <td colspan=3><input name="$ordnumber" size=20></td>
782         </tr>
783 $employee_block
784         <tr>
785           <th align="right">| . $locale->text('Transaction description') . qq|</th>
786           <td colspan="3"><input name="transaction_description" size=20></td>
787         </tr>
788         <tr>
789           <th align="right">| . $locale->text("Project Number") . qq|</th>
790           <td colspan="3">$projectnumber</td>
791         </tr>
792         <tr>
793           <th align=right>| . $locale->text('From') . qq|</th> $button1
794           <th align=right>| . $locale->text('Bis') . qq|</th> $button2
795         </tr>
796         <input type=hidden name=sort value=transdate>
797         <tr>
798           <th align=right>| . $locale->text('Include in Report') . qq|</th>
799           <td colspan=5>
800             <table>
801         <tr>
802           <td><input type="checkbox" name="open" value="1" id="open" checked> <label for="open">| . $locale->text("Open") . qq|</td>
803           <td><input type="checkbox" name="closed" value="1" id="closed"> <label for="closed">| . $locale->text("Closed") . qq|</td>
804         </tr>
805         $delivered
806               <tr>
807                 <td><input name="l_id" class=checkbox type=checkbox value=Y> | . $locale->text('ID') . qq|</td>
808                 <td><input name="l_$ordnumber" class=checkbox type=checkbox value=Y checked> $ordlabel</td>
809               </tr>
810               <tr>
811                 <td><input name="l_transdate" class=checkbox type=checkbox value=Y checked> | . $locale->text('Date') . qq|</td>
812                 <td><input name="l_reqdate" class=checkbox type=checkbox value=Y checked> | . $locale->text('Required by') . qq|</td>
813               </tr>
814               <tr>
815                 <td><input name="l_name" class=checkbox type=checkbox value=Y checked> $vc_label</td>
816                 <td><input name="l_employee" class=checkbox type=checkbox value=Y checked> $employee</td>
817                 
818                 <td><input name="l_shipvia" class=checkbox type=checkbox value=Y> | . $locale->text('Ship via') . qq|</td>
819               </tr>
820               <tr>
821                 <td><input name="l_netamount" class=checkbox type=checkbox value=Y> | . $locale->text('Amount') . qq|</td>
822                 <td><input name="l_tax" class=checkbox type=checkbox value=Y> | . $locale->text('Tax') . qq|</td>
823                 <td><input name="l_amount" class=checkbox type=checkbox value=Y checked> | . $locale->text('Total') . qq|</td>
824               </tr>
825               <tr>
826                 <td><input name="l_marge_total" class=checkbox type=checkbox value=Y> | .             $locale->text('Ertrag') . qq|</td>
827                 <td><input name="l_marge_percent" class=checkbox type=checkbox value=Y> | .             $locale->text('Ertrag prozentual') . qq|</td>
828               </tr>
829               <tr>
830           <td><input name="l_globalprojectnumber" class=checkbox type=checkbox value=Y> | . $locale->text('Project Number') . qq|</td>
831           <td><input name="l_transaction_description" class=checkbox type=checkbox value=Y> | . $locale->text('Transaction description') . qq|</td>
832               </tr>
833               <tr>
834                 <td><input name="l_subtotal" class=checkbox type=checkbox value=Y> | . $locale->text('Subtotal') . qq|</td>
835                 <td><input name="l_salesman" class="checkbox" type="checkbox" value="Y"> | . $locale->text('Salesman') . qq|</td>
836               </tr>
837             </table>
838           </td>
839         </tr>
840       </table>
841     </td>
842   </tr>
843   <tr><td colspan=4><hr size=3 noshade></td></tr>
844 </table>
845
846 $jsscript
847
848 <br>
849 <input type=hidden name=nextsub value=orders>
850 <input type=hidden name=vc value=$form->{vc}>
851 <input type=hidden name=type value=$form->{type}>
852
853 <input class=submit type=submit name=action value="|
854     . $locale->text('Continue') . qq|">
855 </form>
856
857 </body>
858 </html>
859 |;
860
861   $lxdebug->leave_sub();
862 }
863
864 sub create_subtotal_row {
865   $lxdebug->enter_sub();
866
867   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
868
869   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
870
871   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
872
873   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
874
875   map { $totals->{$_} = 0 } @{ $subtotal_columns };
876
877   $lxdebug->leave_sub();
878
879   return $row;
880 }
881
882 sub orders {
883   $lxdebug->enter_sub();
884
885   check_oe_access();
886
887   $ordnumber = ($form->{type} =~ /_order$/) ? "ordnumber" : "quonumber";
888
889   ($form->{ $form->{vc} }, $form->{"${form->{vc}}_id"}) = split(/--/, $form->{ $form->{vc} });
890
891   report_generator_set_default_sort('transdate', 1);
892
893   OE->transactions(\%myconfig, \%$form);
894
895   $form->{rowcount} = scalar @{ $form->{OE} };
896
897   my @columns = (
898     "transdate",               "reqdate",
899     "id",                      $ordnumber,
900     "name",                    "netamount",
901     "tax",                     "amount",
902     "curr",                    "employee",
903     "salesman",
904     "shipvia",                 "globalprojectnumber",
905     "transaction_description", "open",
906     "delivered", "marge_total", "marge_percent"
907   );
908
909   # only show checkboxes if gotten here via sales_order form.
910   my $allow_multiple_orders = $form->{type} eq 'sales_order';
911   if ($allow_multiple_orders) {
912     unshift @columns, "ids";
913   }
914
915   $form->{l_open}      = $form->{l_closed} = "Y" if ($form->{open}      && $form->{closed});
916   $form->{l_delivered} = "Y"                     if ($form->{delivered} && $form->{notdelivered});
917
918   my $attachment_basename;
919   if ($form->{vc} eq 'vendor') {
920     if ($form->{type} eq 'purchase_order') {
921       $form->{title}       = $locale->text('Purchase Orders');
922       $attachment_basename = $locale->text('purchase_order_list');
923     } else {
924       $form->{title}       = $locale->text('Request for Quotations');
925       $attachment_basename = $locale->text('rfq_list');
926     }
927
928   } else {
929     if ($form->{type} eq 'sales_order') {
930       $form->{title}       = $locale->text('Sales Orders');
931       $attachment_basename = $locale->text('sales_order_list');
932     } else {
933       $form->{title}       = $locale->text('Quotations');
934       $attachment_basename = $locale->text('quotation_list');
935     }
936   }
937
938   my $report = SL::ReportGenerator->new(\%myconfig, $form);
939
940   my @hidden_variables = map { "l_${_}" } @columns;
941   push @hidden_variables, "l_subtotal", $form->{vc}, qw(l_closed l_notdelivered open closed delivered notdelivered ordnumber quonumber
942                                                         transaction_description transdatefrom transdateto type vc employee_id salesman_id);
943
944   my $href = build_std_url('action=orders', grep { $form->{$_} } @hidden_variables);
945
946   my %column_defs = (
947     'ids'                     => { 'text' => '', },
948     'transdate'               => { 'text' => $locale->text('Date'), },
949     'reqdate'                 => { 'text' => $locale->text('Required by'), },
950     'id'                      => { 'text' => $locale->text('ID'), },
951     'ordnumber'               => { 'text' => $locale->text('Order'), },
952     'quonumber'               => { 'text' => $form->{type} eq "request_quotation" ? $locale->text('RFQ') : $locale->text('Quotation'), },
953     'name'                    => { 'text' => $form->{vc} eq 'customer' ? $locale->text('Customer') : $locale->text('Vendor'), },
954     'netamount'               => { 'text' => $locale->text('Amount'), },
955     'tax'                     => { 'text' => $locale->text('Tax'), },
956     'amount'                  => { 'text' => $locale->text('Total'), },
957     'curr'                    => { 'text' => $locale->text('Curr'), },
958     'employee'                => { 'text' => $locale->text('Employee'), },
959     'salesman'                => { 'text' => $locale->text('Salesman'), },
960     'shipvia'                 => { 'text' => $locale->text('Ship via'), },
961     'globalprojectnumber'     => { 'text' => $locale->text('Project Number'), },
962     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
963     'open'                    => { 'text' => $locale->text('Open'), },
964     'delivered'               => { 'text' => $locale->text('Delivered'), },
965     'marge_total'             => { 'text' => $locale->text('Ertrag'), },
966     'marge_percent'           => { 'text' => $locale->text('Ertrag prozentual'), }
967   );
968
969   foreach my $name (qw(id transdate reqdate quonumber ordnumber name employee salesman shipvia)) {
970     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
971     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
972   }
973
974   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount curr);
975
976   $form->{"l_type"} = "Y";
977   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
978   $column_defs{ids}->{visible} = $allow_multiple_orders ? 'HTML' : 0;
979
980   $report->set_columns(%column_defs);
981   $report->set_column_order(@columns);
982   $report->set_export_options('orders', @hidden_variables);
983   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
984
985   my @options;
986   my ($department) = split m/--/, $form->{department};
987
988   push @options, $locale->text('Customer')                . " : $form->{customer}"                        if $form->{customer};
989   push @options, $locale->text('Vendor')                  . " : $form->{vendor}"                          if $form->{vendor};
990   push @options, $locale->text('Department')              . " : $department"                              if $form->{department};
991   push @options, $locale->text('Order Number')            . " : $form->{ordnumber}"                       if $form->{ordnumber};
992   push @options, $locale->text('Notes')                   . " : $form->{notes}"                           if $form->{notes};
993   push @options, $locale->text('Transaction description') . " : $form->{transaction_description}"         if $form->{transaction_description};
994   push @options, $locale->text('From') . "&nbsp;" . $locale->date(\%myconfig, $form->{transdatefrom}, 1)  if $form->{transdatefrom};
995   push @options, $locale->text('Bis')  . "&nbsp;" . $locale->date(\%myconfig, $form->{transdateto},   1)  if $form->{transdateto};
996   push @options, $locale->text('Open')                                                                    if $form->{open};
997   push @options, $locale->text('Closed')                                                                  if $form->{closed};
998   push @options, $locale->text('Delivered')                                                               if $form->{delivered};
999   push @options, $locale->text('Not delivered')                                                           if $form->{notdelivered};
1000
1001   $report->set_options('top_info_text'        => join("\n", @options),
1002                        'raw_top_info_text'    => $form->parse_html_template('oe/orders_top'),
1003                        'raw_bottom_info_text' => $form->parse_html_template('oe/orders_bottom', { 'SHOW_CONTINUE_BUTTON' => $allow_multiple_orders }),
1004                        'output_format'        => 'HTML',
1005                        'title'                => $form->{title},
1006                        'attachment_basename'  => $attachment_basename . strftime('_%Y%m%d', localtime time),
1007     );
1008   $report->set_options_from_form();
1009
1010   # add sort and escape callback, this one we use for the add sub
1011   $form->{callback} = $href .= "&sort=$form->{sort}";
1012
1013   # escape callback for href
1014   $callback = $form->escape($href);
1015
1016   my @subtotal_columns = qw(netamount amount marge_total marge_percent);
1017
1018   my %totals    = map { $_ => 0 } @subtotal_columns;
1019   my %subtotals = map { $_ => 0 } @subtotal_columns;
1020
1021   my $idx = 0;
1022
1023   my $edit_url = build_std_url('action=edit', 'type', 'vc');
1024
1025   foreach $oe (@{ $form->{OE} }) {
1026     map { $oe->{$_} *= $oe->{exchangerate} } @subtotal_columns;
1027
1028     $oe->{tax}       = $oe->{amount} - $oe->{netamount};
1029     $oe->{open}      = $oe->{closed}    ? $locale->text('No')  : $locale->text('Yes');
1030     $oe->{delivered} = $oe->{delivered} ? $locale->text('Yes') : $locale->text('No');
1031
1032     map { $subtotals{$_} += $oe->{$_};
1033           $totals{$_}    += $oe->{$_} } @subtotal_columns;
1034
1035     $subtotals{marge_percent} = $subtotals{netamount} ? ($subtotals{marge_total} * 100 / $subtotals{netamount}) : 0;
1036     $totals{marge_percent}    = $totals{netamount}    ? ($totals{marge_total}    * 100 / $totals{netamount}   ) : 0;
1037
1038     map { $oe->{$_} = $form->format_amount(\%myconfig, $oe->{$_}, 2) } qw(netamount tax amount marge_total marge_percent);
1039
1040     my $row = { };
1041
1042     foreach my $column (@columns) {
1043       next if ($column eq 'ids');
1044       $row->{$column} = {
1045         'data'  => $oe->{$column},
1046         'align' => $column_alignment{$column},
1047       };
1048     }
1049
1050     $row->{ids} = {
1051       'raw_data' =>   $cgi->hidden('-name' => "trans_id_${idx}", '-value' => $oe->{id})
1052                     . $cgi->checkbox('-name' => "multi_id_${idx}", '-value' => 1, '-label' => ''),
1053       'valign'   => 'center',
1054       'align'    => 'center',
1055     };
1056
1057     $row->{$ordnumber}->{link} = $edit_url . "&id=" . E($oe->{id}) . "&callback=${callback}";
1058
1059     my $row_set = [ $row ];
1060
1061     if (($form->{l_subtotal} eq 'Y')
1062         && (($idx == (scalar @{ $form->{OE} } - 1))
1063             || ($oe->{ $form->{sort} } ne $form->{OE}->[$idx + 1]->{ $form->{sort} }))) {
1064       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
1065     }
1066
1067     $report->add_data($row_set);
1068
1069     $idx++;
1070   }
1071
1072   $report->add_separator();
1073   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
1074
1075   $report->generate_with_headers();
1076
1077   $lxdebug->leave_sub();
1078 }
1079
1080 sub check_delivered_flag {
1081   $lxdebug->enter_sub();
1082
1083   check_oe_access();
1084
1085   if (($form->{type} ne 'sales_order') && ($form->{type} ne 'purchase_order')) {
1086     return $lxdebug->leave_sub();
1087   }
1088
1089   my $all_delivered = 0;
1090
1091   foreach my $i (1 .. $form->{rowcount}) {
1092     next if (!$form->{"id_$i"});
1093
1094     if ($form->parse_amount(\%myconfig, $form->{"qty_$i"}) == $form->parse_amount(\%myconfig, $form->{"ship_$i"})) {
1095       $all_delivered = 1;
1096       next;
1097     }
1098
1099     $all_delivered = 0;
1100     last;
1101   }
1102
1103   $form->{delivered} = 1 if $all_delivered;
1104
1105   $lxdebug->leave_sub();
1106 }
1107
1108 sub save_and_close {
1109   $lxdebug->enter_sub();
1110
1111   check_oe_access();
1112
1113   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
1114
1115   if ($form->{type} =~ /_order$/) {
1116     $form->isblank("transdate", $locale->text('Order Date missing!'));
1117   } else {
1118     $form->isblank("transdate", $locale->text('Quotation Date missing!'));
1119   }
1120
1121   my $idx = $form->{type} =~ /_quotation$/ ? "quonumber" : "ordnumber";
1122   $form->{$idx} =~ s/^\s*//g;
1123   $form->{$idx} =~ s/\s*$//g;
1124
1125   $msg = ucfirst $form->{vc};
1126   $form->isblank($form->{vc}, $locale->text($msg . " missing!"));
1127
1128   # $locale->text('Customer missing!');
1129   # $locale->text('Vendor missing!');
1130
1131   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
1132     if ($form->{currency} ne $form->{defaultcurrency});
1133
1134   &validate_items;
1135   
1136   if($form->{payment_id}) { 
1137     $payment_id = $form->{payment_id};
1138   }
1139   
1140   # if the name changed get new values
1141   if (&check_name($form->{vc})) {
1142     if($form->{payment_id} eq "") { 
1143       $form->{payment_id} = $payment_id;
1144     }
1145     &update;
1146     exit;
1147   }
1148
1149   $form->{id} = 0 if $form->{saveasnew};
1150
1151   # this is for the internal notes section for the [email] Subject
1152   if ($form->{type} =~ /_order$/) {
1153     if ($form->{type} eq 'sales_order') {
1154       $form->{label} = $locale->text('Sales Order');
1155
1156       $numberfld = "sonumber";
1157       $ordnumber = "ordnumber";
1158     } else {
1159       $form->{label} = $locale->text('Purchase Order');
1160
1161       $numberfld = "ponumber";
1162       $ordnumber = "ordnumber";
1163     }
1164
1165     $err = $locale->text('Cannot save order!');
1166
1167     check_delivered_flag();
1168
1169   } else {
1170     if ($form->{type} eq 'sales_quotation') {
1171       $form->{label} = $locale->text('Quotation');
1172
1173       $numberfld = "sqnumber";
1174       $ordnumber = "quonumber";
1175     } else {
1176       $form->{label} = $locale->text('Request for Quotation');
1177
1178       $numberfld = "rfqnumber";
1179       $ordnumber = "quonumber";
1180     }
1181
1182     $err = $locale->text('Cannot save quotation!');
1183
1184   }
1185
1186   # get new number in sequence if no number is given or if saveasnew was requested
1187   if (!$form->{$ordnumber} || $form->{saveasnew}) {
1188     $form->{$ordnumber} = $form->update_defaults(\%myconfig, $numberfld);
1189   }
1190
1191   relink_accounts();
1192
1193   $form->error($err) if (!OE->save(\%myconfig, \%$form));
1194
1195   # saving the history
1196   if(!exists $form->{addition}) {
1197     $form->{snumbers} = qq|ordnumber_| . $form->{ordnumber};
1198         $form->{addition} = "SAVED";
1199         $form->save_history($form->dbconnect(\%myconfig));
1200   }
1201   # /saving the history
1202
1203   $form->redirect($form->{label} . " $form->{$ordnumber} " .
1204                   $locale->text('saved!'));
1205
1206   $lxdebug->leave_sub();
1207 }
1208
1209 sub save {
1210   $lxdebug->enter_sub();
1211
1212   check_oe_access();
1213
1214   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
1215
1216
1217   if ($form->{type} =~ /_order$/) {
1218     $form->isblank("transdate", $locale->text('Order Date missing!'));
1219   } else {
1220     $form->isblank("transdate", $locale->text('Quotation Date missing!'));
1221   }
1222
1223   my $idx = $form->{type} =~ /_quotation$/ ? "quonumber" : "ordnumber";
1224   $form->{$idx} =~ s/^\s*//g;
1225   $form->{$idx} =~ s/\s*$//g;
1226
1227   $msg = ucfirst $form->{vc};
1228   $form->isblank($form->{vc}, $locale->text($msg . " missing!"));
1229
1230   # $locale->text('Customer missing!');
1231   # $locale->text('Vendor missing!');
1232
1233   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
1234     if ($form->{currency} ne $form->{defaultcurrency});
1235
1236   &validate_items;
1237   
1238   if($form->{payment_id}) { 
1239     $payment_id = $form->{payment_id};
1240   }
1241   
1242   # if the name changed get new values
1243   if (&check_name($form->{vc})) {
1244     if($form->{payment_id} eq "") { 
1245       $form->{payment_id} = $payment_id;
1246     }
1247     &update;
1248     exit;
1249   }
1250
1251   $form->{id} = 0 if $form->{saveasnew};
1252
1253   # this is for the internal notes section for the [email] Subject
1254   if ($form->{type} =~ /_order$/) {
1255     if ($form->{type} eq 'sales_order') {
1256       $form->{label} = $locale->text('Sales Order');
1257
1258       $numberfld = "sonumber";
1259       $ordnumber = "ordnumber";
1260     } else {
1261       $form->{label} = $locale->text('Purchase Order');
1262
1263       $numberfld = "ponumber";
1264       $ordnumber = "ordnumber";
1265     }
1266
1267     $err = $locale->text('Cannot save order!');
1268
1269     check_delivered_flag();
1270
1271   } else {
1272     if ($form->{type} eq 'sales_quotation') {
1273       $form->{label} = $locale->text('Quotation');
1274
1275       $numberfld = "sqnumber";
1276       $ordnumber = "quonumber";
1277     } else {
1278       $form->{label} = $locale->text('Request for Quotation');
1279
1280       $numberfld = "rfqnumber";
1281       $ordnumber = "quonumber";
1282     }
1283
1284     $err = $locale->text('Cannot save quotation!');
1285
1286   }
1287
1288   $form->{$ordnumber} = $form->update_defaults(\%myconfig, $numberfld)
1289     unless $form->{$ordnumber};
1290
1291   relink_accounts();
1292
1293   OE->save(\%myconfig, \%$form);
1294
1295   # saving the history
1296   if(!exists $form->{addition}) {
1297     $form->{snumbers} = qq|ordnumber_| . $form->{ordnumber};
1298         $form->{addition} = "SAVED";
1299         $form->save_history($form->dbconnect(\%myconfig));
1300   }
1301   # /saving the history 
1302
1303   $form->{simple_save} = 1;
1304   if(!$form->{print_and_save}) {
1305     set_headings("edit");
1306     &update;
1307     exit;
1308   }
1309   $lxdebug->leave_sub();
1310 }
1311
1312 sub delete {
1313   $lxdebug->enter_sub();
1314
1315   check_oe_access();
1316
1317   $form->header;
1318
1319   if ($form->{type} =~ /_order$/) {
1320     $msg       = $locale->text('Are you sure you want to delete Order Number');
1321     $ordnumber = 'ordnumber';
1322   } else {
1323     $msg = $locale->text('Are you sure you want to delete Quotation Number');
1324     $ordnumber = 'quonumber';
1325   }
1326
1327   print qq|
1328 <body>
1329
1330 <form method=post action=$form->{script}>
1331 |;
1332
1333   # delete action variable
1334   map { delete $form->{$_} } qw(action header);
1335
1336   foreach $key (keys %$form) {
1337     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
1338     $form->{$key} =~ s/\"/&quot;/g;
1339     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
1340   }
1341
1342   print qq|
1343 <h2 class=confirm>| . $locale->text('Confirm!') . qq|</h2>
1344
1345 <h4>$msg $form->{$ordnumber}</h4>
1346 <p>
1347 <input type="hidden" name="yes_nextsub" value="delete_order_quotation">
1348 <input name=action class=submit type=submit value="|
1349     . $locale->text('Yes') . qq|">
1350 <button class=submit type=button onclick="history.back()">|
1351     . $locale->text('No') . qq|</button>
1352 </form>
1353
1354 </body>
1355 </html>
1356 |;
1357
1358   $lxdebug->leave_sub();
1359 }
1360
1361 sub delete_order_quotation {
1362   $lxdebug->enter_sub();
1363
1364   check_oe_access();
1365
1366   if ($form->{type} =~ /_order$/) {
1367     $msg = $locale->text('Order deleted!');
1368     $err = $locale->text('Cannot delete order!');
1369   } else {
1370     $msg = $locale->text('Quotation deleted!');
1371     $err = $locale->text('Cannot delete quotation!');
1372   }
1373   if (OE->delete(\%myconfig, \%$form, $spool)){
1374     # saving the history
1375     if(!exists $form->{addition}) {
1376       $form->{snumbers} = qq|ordnumber_| . $form->{ordnumber};
1377           $form->{addition} = "DELETED";
1378           $form->save_history($form->dbconnect(\%myconfig));
1379     }
1380     # /saving the history 
1381     $form->info($msg);
1382     exit();
1383   }
1384   $form->error($err);
1385
1386   $lxdebug->leave_sub();
1387 }
1388
1389 sub invoice {
1390   $lxdebug->enter_sub();
1391
1392   check_oe_access();
1393   $auth->assert($form->{type} eq 'purchase_order' || $form->{type} eq 'request_quotation' ? 'vendor_invoice_edit' : 'invoice_edit');
1394
1395   $form->{old_employee_id} = $form->{employee_id};
1396   $form->{old_salesman_id} = $form->{salesman_id};
1397
1398   if ($form->{type} =~ /_order$/) {
1399
1400     # these checks only apply if the items don't bring their own ordnumbers/transdates.
1401     # The if clause ensures that by searching for empty ordnumber_#/transdate_# fields.
1402     $form->isblank("ordnumber", $locale->text('Order Number missing!'))
1403       if (+{ map { $form->{"ordnumber_$_"}, 1 } (1 .. $form->{rowcount} - 1) }->{''});
1404     $form->isblank("transdate", $locale->text('Order Date missing!'))
1405       if (+{ map { $form->{"transdate_$_"}, 1 } (1 .. $form->{rowcount} - 1) }->{''});
1406
1407     # also copy deliverydate from the order
1408     $form->{deliverydate} = $form->{reqdate} if $form->{reqdate};
1409     $form->{orddate}      = $form->{transdate};
1410   } else {
1411     $form->isblank("quonumber", $locale->text('Quotation Number missing!'));
1412     $form->isblank("transdate", $locale->text('Quotation Date missing!'));
1413     $form->{ordnumber}    = "";
1414     $form->{quodate}      = $form->{transdate};
1415   }
1416   
1417   $payment_id = $form->{payment_id} if $form->{payment_id};
1418   
1419   # if the name changed get new values
1420   if (&check_name($form->{vc})) {
1421     $form->{payment_id} = $payment_id if $form->{payment_id} eq "";
1422     &update;
1423     exit;
1424   }
1425
1426   $form->{cp_id} *= 1;
1427
1428   for $i (1 .. $form->{rowcount}) {
1429     for (qw(ship qty sellprice listprice basefactor)) {
1430       $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"}) if $form->{"${_}_${i}"};
1431     }
1432   }
1433
1434   if (   $form->{type} =~ /_order/
1435       && $form->{currency} ne $form->{defaultcurrency}) {
1436
1437     # check if we need a new exchangerate
1438     $buysell = ($form->{type} eq 'sales_order') ? "buy" : "sell";
1439
1440     $orddate      = $form->current_date(\%myconfig);
1441     $exchangerate = $form->check_exchangerate(\%myconfig, $form->{currency}, $orddate, $buysell);
1442
1443     if (!$exchangerate) {
1444       &backorder_exchangerate($orddate, $buysell);
1445       exit;
1446     }
1447   }
1448
1449   # close orders/quotations
1450   $form->{closed} = 1;
1451
1452   # save order if one ordnumber has been given
1453   # if not it's most likely a collective order, which can't be saved back
1454   # so they just have to be closed
1455   if (($form->{ordnumber} ne '') || ($form->{quonumber} ne '')) {
1456     OE->close_order(\%myconfig, \%$form) if ($form->{id});
1457   } else {
1458     OE->close_orders(\%myconfig, \%$form);
1459   }
1460
1461   $form->{convert_from_oe_ids} = $form->{id};
1462   $form->{transdate}           = $form->{invdate} = $form->current_date(\%myconfig);
1463   $form->{duedate}             = $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
1464   $form->{shipto}              = 1;
1465   $form->{defaultcurrency}     = $form->get_default_currency(\%myconfig);
1466
1467   delete @{$form}{qw(id closed)};
1468   $form->{rowcount}--;
1469
1470   if ($form->{type} =~ /_order$/) {
1471     $form->{exchangerate} = $exchangerate;
1472     &create_backorder;
1473   }
1474
1475   if (   $form->{type} eq 'purchase_order'
1476       || $form->{type} eq 'request_quotation') {
1477     $form->{title}  = $locale->text('Add Vendor Invoice');
1478     $form->{script} = 'ir.pl';
1479     $script         = "ir";
1480     $buysell        = 'sell';
1481   }
1482
1483   if (   $form->{type} eq 'sales_order' 
1484       || $form->{type} eq 'sales_quotation') {
1485     $form->{title}  = $locale->text('Add Sales Invoice');
1486     $form->{script} = 'is.pl';
1487     $script         = "is";
1488     $buysell        = 'buy';
1489   }
1490
1491   # bo creates the id, reset it
1492   map { delete $form->{$_} } qw(id subject message cc bcc printed emailed queued);
1493   $form->{ $form->{vc} } =~ s/--.*//g;
1494   $form->{type} = "invoice";
1495
1496   # locale messages
1497   $locale = new Locale "$myconfig{countrycode}", "$script";
1498
1499   require "bin/mozilla/$form->{script}";
1500
1501   map { $form->{"select$_"} = "" } ($form->{vc}, currency);
1502
1503   $currency = $form->{currency};
1504   &invoice_links;
1505
1506   $form->{currency}     = $currency;
1507   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, $buysell);
1508   $form->{exchangerate} = $form->{forex} || '';
1509
1510   $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
1511
1512   &prepare_invoice;
1513
1514   # format amounts
1515   for $i (1 .. $form->{rowcount}) {
1516     $form->{"discount_$i"} =
1517       $form->format_amount(\%myconfig, $form->{"discount_$i"});
1518
1519     ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
1520     $dec           = length $dec;
1521     $decimalplaces = ($dec > 2) ? $dec : 2;
1522
1523     # copy delivery date from reqdate for order -> invoice conversion
1524     $form->{"deliverydate_$i"} = $form->{"reqdate_$i"}
1525       unless $form->{"deliverydate_$i"};
1526
1527     $form->{"sellprice_$i"} =
1528       $form->format_amount(\%myconfig, $form->{"sellprice_$i"},
1529                            $decimalplaces);
1530
1531     (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
1532     $dec_qty = length $dec_qty;
1533     $form->{"qty_$i"} =
1534       $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
1535
1536     map { $form->{"${_}_$i"} =~ s/\"/&quot;/g }
1537       qw(partnumber description unit);
1538
1539   }
1540
1541   &display_form;
1542
1543   $lxdebug->leave_sub();
1544 }
1545
1546 sub backorder_exchangerate {
1547   $lxdebug->enter_sub();
1548
1549   check_oe_access();
1550
1551   my ($orddate, $buysell) = @_;
1552
1553   $form->header;
1554
1555   print qq|
1556 <body>
1557
1558 <form method=post action=$form->{script}>
1559 |;
1560
1561   # delete action variable
1562   map { delete $form->{$_} } qw(action header exchangerate);
1563
1564   foreach $key (keys %$form) {
1565     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
1566     $form->{$key} =~ s/\"/&quot;/g;
1567     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
1568   }
1569
1570   $form->{title} = $locale->text('Add Exchangerate');
1571
1572   print qq|
1573
1574 <input type=hidden name=exchangeratedate value=$orddate>
1575 <input type=hidden name=buysell value=$buysell>
1576
1577 <table width=100%>
1578   <tr><th class=listtop>$form->{title}</th></tr>
1579   <tr height="5"></tr>
1580   <tr>
1581     <td>
1582       <table>
1583         <tr>
1584           <th align=right>| . $locale->text('Currency') . qq|</th>
1585           <td>$form->{currency}</td>
1586         </tr>
1587         <tr>
1588           <th align=right>| . $locale->text('Date') . qq|</th>
1589           <td>$orddate</td>
1590         </tr>
1591         <tr>
1592           <th align=right>| . $locale->text('Exchangerate') . qq|</th>
1593           <td><input name=exchangerate size=11></td>
1594         </tr>
1595       </table>
1596     </td>
1597   </tr>
1598 </table>
1599
1600 <hr size=3 noshade>
1601
1602 <br>
1603 <input type=hidden name=nextsub value=save_exchangerate>
1604
1605 <input name=action class=submit type=submit value="|
1606     . $locale->text('Continue') . qq|">
1607
1608 </form>
1609
1610 </body>
1611 </html>
1612 |;
1613
1614   $lxdebug->leave_sub();
1615 }
1616
1617 sub save_exchangerate {
1618   $lxdebug->enter_sub();
1619
1620   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'));
1621   $form->{exchangerate} =
1622     $form->parse_amount(\%myconfig, $form->{exchangerate});
1623   $form->save_exchangerate(\%myconfig, $form->{currency},
1624                            $form->{exchangeratedate},
1625                            $form->{exchangerate}, $form->{buysell});
1626
1627   &invoice;
1628
1629   $lxdebug->leave_sub();
1630 }
1631
1632 sub create_backorder {
1633   $lxdebug->enter_sub();
1634
1635   $form->{shipped} = 1;
1636
1637   # figure out if we need to create a backorder
1638   # items aren't saved if qty != 0
1639
1640   for $i (1 .. $form->{rowcount}) {
1641     $totalqty  += $qty  = $form->{"qty_$i"};
1642     $totalship += $ship = $form->{"ship_$i"};
1643
1644     $form->{"qty_$i"} = $qty - $ship;
1645   }
1646
1647   if ($totalship == 0) {
1648     map { $form->{"ship_$_"} = $form->{"qty_$_"} } (1 .. $form->{rowcount});
1649     $form->{ordtotal} = 0;
1650     $form->{shipped}  = 0;
1651     return;
1652   }
1653
1654   if ($totalqty == $totalship) {
1655     map { $form->{"qty_$_"} = $form->{"ship_$_"} } (1 .. $form->{rowcount});
1656     $form->{ordtotal} = 0;
1657     return;
1658   }
1659
1660   @flds = (
1661     qw(partnumber description qty ship unit sellprice discount id inventory_accno bin income_accno expense_accno listprice assembly taxaccounts partsgroup)
1662   );
1663
1664   for $i (1 .. $form->{rowcount}) {
1665     map {
1666       $form->{"${_}_$i"} =
1667         $form->format_amount(\%myconfig, $form->{"${_}_$i"})
1668     } qw(sellprice discount);
1669   }
1670
1671   relink_accounts();
1672
1673   OE->save(\%myconfig, \%$form);
1674
1675   # rebuild rows for invoice
1676   @a     = ();
1677   $count = 0;
1678
1679   for $i (1 .. $form->{rowcount}) {
1680     $form->{"qty_$i"} = $form->{"ship_$i"};
1681
1682     if ($form->{"qty_$i"}) {
1683       push @a, {};
1684       $j = $#a;
1685       map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
1686       $count++;
1687     }
1688   }
1689
1690   $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
1691   $form->{rowcount} = $count;
1692
1693   $lxdebug->leave_sub();
1694 }
1695
1696 sub save_as_new {
1697   $lxdebug->enter_sub();
1698
1699   check_oe_access();
1700
1701   $form->{saveasnew} = 1;
1702   $form->{closed}    = 0;
1703   map { delete $form->{$_} } qw(printed emailed queued);
1704
1705   # Let Lx-Office assign a new order number if the user hasn't changed the
1706   # previous one. If it has been changed manually then use it as-is.
1707   my $idx = $form->{type} =~ /_quotation$/ ? "quonumber" : "ordnumber";
1708   $form->{$idx} =~ s/^\s*//g;
1709   $form->{$idx} =~ s/\s*$//g;
1710   if ($form->{saved_xyznumber} &&
1711       ($form->{saved_xyznumber} eq $form->{$idx})) {
1712     delete($form->{$idx});
1713   }
1714
1715   &save;
1716
1717   $lxdebug->leave_sub();
1718 }
1719
1720 sub check_for_direct_delivery_yes {
1721   $lxdebug->enter_sub();
1722
1723   check_oe_access();
1724
1725   $form->{direct_delivery_checked} = 1;
1726   delete @{$form}{grep /^shipto/, keys %{ $form }};
1727   map { s/^CFDD_//; $form->{$_} = $form->{"CFDD_${_}"} } grep /^CFDD_/, keys %{ $form };
1728   $form->{shipto} = 1;
1729   purchase_order();
1730   $lxdebug->leave_sub();
1731 }
1732
1733 sub check_for_direct_delivery_no {
1734   $lxdebug->enter_sub();
1735
1736   check_oe_access();
1737
1738   $form->{direct_delivery_checked} = 1;
1739   delete @{$form}{grep /^shipto/, keys %{ $form }};
1740   purchase_order();
1741
1742   $lxdebug->leave_sub();
1743 }
1744
1745 sub check_for_direct_delivery {
1746   $lxdebug->enter_sub();
1747
1748   check_oe_access();
1749
1750   if ($form->{direct_delivery_checked}
1751       || (!$form->{shiptoname} && !$form->{shiptostreet} && !$form->{shipto_id})) {
1752     $lxdebug->leave_sub();
1753     return;
1754   }
1755
1756   if ($form->{shipto_id}) {
1757     Common->get_shipto_by_id(\%myconfig, $form, $form->{shipto_id}, "CFDD_");
1758
1759   } else {
1760     map { $form->{"CFDD_${_}"} = $form->{$_ } } grep /^shipto/, keys %{ $form };
1761   }
1762
1763   delete $form->{action};
1764   $form->{VARIABLES} = [ map { { "key" => $_, "value" => $form->{$_} } } grep { ($_ ne 'login') && ($_ ne 'password') && (ref $_ eq "") } keys %{ $form } ];
1765
1766   $form->header();
1767   print $form->parse_html_template("oe/check_for_direct_delivery");
1768
1769   $lxdebug->leave_sub();
1770
1771   exit 0;
1772 }
1773
1774 sub purchase_order {
1775   $lxdebug->enter_sub();
1776
1777   check_oe_access();
1778   $auth->assert('purchase_order_edit');
1779
1780   if ($form->{type} eq 'sales_order') {
1781     check_for_direct_delivery();
1782   }
1783
1784   if (   $form->{type} eq 'sales_quotation'
1785       || $form->{type} eq 'request_quotation') {
1786     OE->close_order(\%myconfig, \%$form);
1787   }
1788
1789   if ($form->{type} =~ /^sales_/) {
1790     delete($form->{ordnumber});
1791   }
1792
1793   $form->{cp_id} *= 1;
1794
1795   $form->{title} = $locale->text('Add Purchase Order');
1796   $form->{vc}    = "vendor";
1797   $form->{type}  = "purchase_order";
1798
1799   &poso;
1800
1801   $lxdebug->leave_sub();
1802 }
1803
1804 sub sales_order {
1805   $lxdebug->enter_sub();
1806
1807   check_oe_access();
1808   $auth->assert('sales_order_edit');
1809
1810   if (   $form->{type} eq 'sales_quotation'
1811       || $form->{type} eq 'request_quotation') {
1812     OE->close_order(\%myconfig, $form);
1813   }
1814
1815   if ($form->{type} eq "purchase_order") {
1816     delete($form->{ordnumber});
1817   }
1818
1819   $form->{cp_id} *= 1;
1820
1821   $form->{title}  = $locale->text('Add Sales Order');
1822   $form->{vc}     = "customer";
1823   $form->{type}   = "sales_order";
1824
1825   &poso;
1826
1827   $lxdebug->leave_sub();
1828 }
1829
1830 sub poso {
1831   $lxdebug->enter_sub();
1832
1833   check_oe_access();
1834   $auth->assert('purchase_order_edit | sales_order_edit');
1835
1836   $form->{transdate} = $form->current_date(\%myconfig);
1837   delete $form->{duedate};
1838
1839   $form->{convert_from_oe_ids} = $form->{id};
1840   $form->{closed}              = 0;
1841
1842   $form->{old_employee_id}     = $form->{employee_id};
1843   $form->{old_salesman_id}     = $form->{salesman_id};
1844
1845   # reset
1846   map { delete $form->{$_} } qw(id subject message cc bcc printed emailed queued customer vendor creditlimit creditremaining discount tradediscount oldinvtotal delivered);
1847
1848   for $i (1 .. $form->{rowcount}) {
1849     map { $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"}) if ($form->{"${_}_${i}"}) } qw(ship qty sellprice listprice basefactor);
1850   }
1851
1852   my %saved_vars = map { $_ => $form->{$_} } grep { $form->{$_} } qw(currency);
1853
1854   &order_links;
1855
1856   map { $form->{$_} = $saved_vars{$_} } keys %saved_vars;
1857
1858   &prepare_order;
1859
1860   # format amounts
1861   for $i (1 .. $form->{rowcount} - 1) {
1862     map { $form->{"${_}_$i"} =~ s/\"/&quot;/g } qw(partnumber description unit);
1863   }
1864
1865   &update;
1866
1867   $lxdebug->leave_sub();
1868 }
1869
1870 sub delivery_order {
1871   $lxdebug->enter_sub();
1872
1873   if ($form->{type} =~ /^sales/) {
1874     $auth->assert('sales_delivery_order_edit');
1875
1876     $form->{vc}    = 'customer';
1877     $form->{type}  = 'sales_delivery_order';
1878
1879   } else {
1880     $auth->assert('purchase_delivery_order_edit');
1881
1882     $form->{vc}    = 'vendor';
1883     $form->{type}  = 'purchase_delivery_order';
1884   }
1885
1886   require "bin/mozilla/do.pl";
1887
1888   $form->{cp_id}               *= 1;
1889   $form->{convert_from_oe_ids}  = $form->{id};
1890   $form->{transdate}            = $form->current_date(\%myconfig);
1891   delete $form->{duedate};
1892
1893   $form->{old_employee_id}  = $form->{employee_id};
1894   $form->{old_salesman_id}  = $form->{salesman_id};
1895
1896   # reset
1897   delete @{$form}{qw(id subject message cc bcc printed emailed queued creditlimit creditremaining discount tradediscount oldinvtotal closed delivered)};
1898
1899   for $i (1 .. $form->{rowcount}) {
1900     map { $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"}) if ($form->{"${_}_${i}"}) } qw(ship qty sellprice listprice basefactor);
1901   }
1902
1903   my %old_values = map { $_ => $form->{$_} } qw(customer_id oldcustomer customer vendor_id oldvendor vendor);
1904
1905   order_links();
1906
1907   prepare_order();
1908
1909   map { $form->{$_} = $old_values{$_} if ($old_values{$_}) } keys %old_values;
1910
1911   update();
1912
1913   $lxdebug->leave_sub();
1914 }
1915
1916 sub e_mail {
1917   $lxdebug->enter_sub();
1918
1919   check_oe_access();
1920
1921   $form->{print_and_save} = 1;
1922
1923   $print_post = 1;
1924
1925   my $saved_form = save_form();
1926
1927   save();
1928
1929   restore_form($saved_form, 0, qw(id ordnumber quonumber));
1930
1931   edit_e_mail();
1932
1933   $lxdebug->leave_sub();
1934 }
1935
1936 sub yes {
1937   call_sub($form->{yes_nextsub});
1938 }
1939
1940 sub no {
1941   call_sub($form->{no_nextsub});
1942 }
1943
1944 ######################################################################################################
1945 # IO ENTKOPPLUNG
1946 # ###############################################################################################
1947 sub display_form {
1948   $lxdebug->enter_sub();
1949
1950   check_oe_access();
1951
1952   retrieve_partunits() if ($form->{type} =~ /_delivery_order$/);
1953
1954   $form->{"taxaccounts"} =~ s/\s*$//;
1955   $form->{"taxaccounts"} =~ s/^\s*//;
1956   foreach my $accno (split(/\s*/, $form->{"taxaccounts"})) {
1957     map({ delete($form->{"${accno}_${_}"}); } qw(rate description taxnumber));
1958   }
1959   $form->{"taxaccounts"} = "";
1960
1961   for my $i (1 .. $form->{"rowcount"}) {
1962     IC->retrieve_accounts(\%myconfig, $form, $form->{"id_$i"}, $i, 1) if $form->{"id_$i"};
1963   }
1964
1965   $form->{rowcount}++;
1966   $form->{"project_id_$form->{rowcount}"} = $form->{globalproject_id};
1967
1968   $form->language_payment(\%myconfig);
1969
1970   Common::webdav_folder($form) if ($webdav);
1971
1972   &form_header;
1973
1974   # create rows
1975   display_row($form->{rowcount}) if $form->{rowcount};
1976
1977   &form_footer;
1978
1979   $lxdebug->leave_sub();
1980 }
1981
1982 sub report_for_todo_list {
1983   $lxdebug->enter_sub();
1984
1985   my $quotations = OE->transactions_for_todo_list();
1986   my $content;
1987
1988   if (@{ $quotations }) {
1989     my $edit_url = build_std_url('script=oe.pl', 'action=edit', 'type=sales_quotation', 'vc=customer');
1990
1991     $content     = $form->parse_html_template('oe/report_for_todo_list', { 'QUOTATIONS' => $quotations,
1992                                                                            'edit_url'   => $edit_url });
1993   }
1994
1995   $lxdebug->leave_sub();
1996
1997   return $content;
1998 }
1999