5c1a9c2462e22c2b5077e4c8fff2a3accea25b9a
[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   $form->{sort}    ||= 'transdate';
892   $form->{sortdir}   = 1 unless (defined $form->{sortdir});
893   $form->{sortdir}   = $form->{sortdir} ? 1 : 0;
894
895   OE->transactions(\%myconfig, \%$form);
896
897   $form->{rowcount} = scalar @{ $form->{OE} };
898
899   my @columns = (
900     "transdate",               "reqdate",
901     "id",                      $ordnumber,
902     "name",                    "netamount",
903     "tax",                     "amount",
904     "curr",                    "employee",
905     "salesman",
906     "shipvia",                 "globalprojectnumber",
907     "transaction_description", "open",
908     "delivered", "marge_total", "marge_percent"
909   );
910
911   # only show checkboxes if gotten here via sales_order form.
912   my $allow_multiple_orders = $form->{type} eq 'sales_order';
913   if ($allow_multiple_orders) {
914     unshift @columns, "ids";
915   }
916
917   $form->{l_open}      = $form->{l_closed} = "Y" if ($form->{open}      && $form->{closed});
918   $form->{l_delivered} = "Y"                     if ($form->{delivered} && $form->{notdelivered});
919
920   my $attachment_basename;
921   if ($form->{vc} eq 'vendor') {
922     if ($form->{type} eq 'purchase_order') {
923       $form->{title}       = $locale->text('Purchase Orders');
924       $attachment_basename = $locale->text('purchase_order_list');
925     } else {
926       $form->{title}       = $locale->text('Request for Quotations');
927       $attachment_basename = $locale->text('rfq_list');
928     }
929
930   } else {
931     if ($form->{type} eq 'sales_order') {
932       $form->{title}       = $locale->text('Sales Orders');
933       $attachment_basename = $locale->text('sales_order_list');
934     } else {
935       $form->{title}       = $locale->text('Quotations');
936       $attachment_basename = $locale->text('quotation_list');
937     }
938   }
939
940   my $report = SL::ReportGenerator->new(\%myconfig, $form);
941
942   my @hidden_variables = map { "l_${_}" } @columns;
943   push @hidden_variables, "l_subtotal", $form->{vc}, qw(l_closed l_notdelivered open closed delivered notdelivered ordnumber quonumber
944                                                         transaction_description transdatefrom transdateto type vc employee_id salesman_id);
945
946   my $href = build_std_url('action=orders', grep { $form->{$_} } @hidden_variables);
947
948   my %column_defs = (
949     'ids'                     => { 'text' => '', },
950     'transdate'               => { 'text' => $locale->text('Date'), },
951     'reqdate'                 => { 'text' => $locale->text('Required by'), },
952     'id'                      => { 'text' => $locale->text('ID'), },
953     'ordnumber'               => { 'text' => $locale->text('Order'), },
954     'quonumber'               => { 'text' => $form->{type} eq "request_quotation" ? $locale->text('RFQ') : $locale->text('Quotation'), },
955     'name'                    => { 'text' => $form->{vc} eq 'customer' ? $locale->text('Customer') : $locale->text('Vendor'), },
956     'netamount'               => { 'text' => $locale->text('Amount'), },
957     'tax'                     => { 'text' => $locale->text('Tax'), },
958     'amount'                  => { 'text' => $locale->text('Total'), },
959     'curr'                    => { 'text' => $locale->text('Curr'), },
960     'employee'                => { 'text' => $locale->text('Employee'), },
961     'salesman'                => { 'text' => $locale->text('Salesman'), },
962     'shipvia'                 => { 'text' => $locale->text('Ship via'), },
963     'globalprojectnumber'     => { 'text' => $locale->text('Project Number'), },
964     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
965     'open'                    => { 'text' => $locale->text('Open'), },
966     'delivered'               => { 'text' => $locale->text('Delivered'), },
967     'marge_total'             => { 'text' => $locale->text('Ertrag'), },
968     'marge_percent'           => { 'text' => $locale->text('Ertrag prozentual'), }
969   );
970
971   foreach my $name (qw(id transdate reqdate quonumber ordnumber name employee salesman shipvia)) {
972     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
973     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
974   }
975
976   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount curr);
977
978   $form->{"l_type"} = "Y";
979   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
980   $column_defs{ids}->{visible} = $allow_multiple_orders ? 'HTML' : 0;
981
982   $report->set_columns(%column_defs);
983   $report->set_column_order(@columns);
984   $report->set_export_options('orders', @hidden_variables);
985   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
986
987   my @options;
988   my ($department) = split m/--/, $form->{department};
989
990   push @options, $locale->text('Customer')                . " : $form->{customer}"                        if $form->{customer};
991   push @options, $locale->text('Vendor')                  . " : $form->{vendor}"                          if $form->{vendor};
992   push @options, $locale->text('Department')              . " : $department"                              if $form->{department};
993   push @options, $locale->text('Order Number')            . " : $form->{ordnumber}"                       if $form->{ordnumber};
994   push @options, $locale->text('Notes')                   . " : $form->{notes}"                           if $form->{notes};
995   push @options, $locale->text('Transaction description') . " : $form->{transaction_description}"         if $form->{transaction_description};
996   push @options, $locale->text('From') . "&nbsp;" . $locale->date(\%myconfig, $form->{transdatefrom}, 1)  if $form->{transdatefrom};
997   push @options, $locale->text('Bis')  . "&nbsp;" . $locale->date(\%myconfig, $form->{transdateto},   1)  if $form->{transdateto};
998   push @options, $locale->text('Open')                                                                    if $form->{open};
999   push @options, $locale->text('Closed')                                                                  if $form->{closed};
1000   push @options, $locale->text('Delivered')                                                               if $form->{delivered};
1001   push @options, $locale->text('Not delivered')                                                           if $form->{notdelivered};
1002
1003   $report->set_options('top_info_text'        => join("\n", @options),
1004                        'raw_top_info_text'    => $form->parse_html_template('oe/orders_top'),
1005                        'raw_bottom_info_text' => $form->parse_html_template('oe/orders_bottom', { 'SHOW_CONTINUE_BUTTON' => $allow_multiple_orders }),
1006                        'output_format'        => 'HTML',
1007                        'title'                => $form->{title},
1008                        'attachment_basename'  => $attachment_basename . strftime('_%Y%m%d', localtime time),
1009     );
1010   $report->set_options_from_form();
1011
1012   # add sort and escape callback, this one we use for the add sub
1013   $form->{callback} = $href .= "&sort=$form->{sort}";
1014
1015   # escape callback for href
1016   $callback = $form->escape($href);
1017
1018   my @subtotal_columns = qw(netamount amount marge_total marge_percent);
1019
1020   my %totals    = map { $_ => 0 } @subtotal_columns;
1021   my %subtotals = map { $_ => 0 } @subtotal_columns;
1022
1023   my $idx = 0;
1024
1025   my $edit_url = build_std_url('action=edit', 'type', 'vc');
1026
1027   foreach $oe (@{ $form->{OE} }) {
1028     map { $oe->{$_} *= $oe->{exchangerate} } @subtotal_columns;
1029
1030     $oe->{tax}       = $oe->{amount} - $oe->{netamount};
1031     $oe->{open}      = $oe->{closed}    ? $locale->text('No')  : $locale->text('Yes');
1032     $oe->{delivered} = $oe->{delivered} ? $locale->text('Yes') : $locale->text('No');
1033
1034     map { $subtotals{$_} += $oe->{$_};
1035           $totals{$_}    += $oe->{$_} } @subtotal_columns;
1036
1037     $subtotals{marge_percent} = $subtotals{netamount} ? ($subtotals{marge_total} * 100 / $subtotals{netamount}) : 0;
1038     $totals{marge_percent}    = $totals{netamount}    ? ($totals{marge_total}    * 100 / $totals{netamount}   ) : 0;
1039
1040     map { $oe->{$_} = $form->format_amount(\%myconfig, $oe->{$_}, 2) } qw(netamount tax amount marge_total marge_percent);
1041
1042     my $row = { };
1043
1044     foreach my $column (@columns) {
1045       next if ($column eq 'ids');
1046       $row->{$column} = {
1047         'data'  => $oe->{$column},
1048         'align' => $column_alignment{$column},
1049       };
1050     }
1051
1052     $row->{ids} = {
1053       'raw_data' =>   $cgi->hidden('-name' => "trans_id_${idx}", '-value' => $oe->{id})
1054                     . $cgi->checkbox('-name' => "multi_id_${idx}", '-value' => 1, '-label' => ''),
1055       'valign'   => 'center',
1056       'align'    => 'center',
1057     };
1058
1059     $row->{$ordnumber}->{link} = $edit_url . "&id=" . E($oe->{id}) . "&callback=${callback}";
1060
1061     my $row_set = [ $row ];
1062
1063     if (($form->{l_subtotal} eq 'Y')
1064         && (($idx == (scalar @{ $form->{OE} } - 1))
1065             || ($oe->{ $form->{sort} } ne $form->{OE}->[$idx + 1]->{ $form->{sort} }))) {
1066       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
1067     }
1068
1069     $report->add_data($row_set);
1070
1071     $idx++;
1072   }
1073
1074   $report->add_separator();
1075   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
1076
1077   $report->generate_with_headers();
1078
1079   $lxdebug->leave_sub();
1080 }
1081
1082 sub check_delivered_flag {
1083   $lxdebug->enter_sub();
1084
1085   check_oe_access();
1086
1087   if (($form->{type} ne 'sales_order') && ($form->{type} ne 'purchase_order')) {
1088     return $lxdebug->leave_sub();
1089   }
1090
1091   my $all_delivered = 0;
1092
1093   foreach my $i (1 .. $form->{rowcount}) {
1094     next if (!$form->{"id_$i"});
1095
1096     if ($form->parse_amount(\%myconfig, $form->{"qty_$i"}) == $form->parse_amount(\%myconfig, $form->{"ship_$i"})) {
1097       $all_delivered = 1;
1098       next;
1099     }
1100
1101     $all_delivered = 0;
1102     last;
1103   }
1104
1105   $form->{delivered} = 1 if $all_delivered;
1106
1107   $lxdebug->leave_sub();
1108 }
1109
1110 sub save_and_close {
1111   $lxdebug->enter_sub();
1112
1113   check_oe_access();
1114
1115   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
1116
1117   if ($form->{type} =~ /_order$/) {
1118     $form->isblank("transdate", $locale->text('Order Date missing!'));
1119   } else {
1120     $form->isblank("transdate", $locale->text('Quotation Date missing!'));
1121   }
1122
1123   my $idx = $form->{type} =~ /_quotation$/ ? "quonumber" : "ordnumber";
1124   $form->{$idx} =~ s/^\s*//g;
1125   $form->{$idx} =~ s/\s*$//g;
1126
1127   $msg = ucfirst $form->{vc};
1128   $form->isblank($form->{vc}, $locale->text($msg . " missing!"));
1129
1130   # $locale->text('Customer missing!');
1131   # $locale->text('Vendor missing!');
1132
1133   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
1134     if ($form->{currency} ne $form->{defaultcurrency});
1135
1136   &validate_items;
1137   
1138   if($form->{payment_id}) { 
1139     $payment_id = $form->{payment_id};
1140   }
1141   
1142   # if the name changed get new values
1143   if (&check_name($form->{vc})) {
1144     if($form->{payment_id} eq "") { 
1145       $form->{payment_id} = $payment_id;
1146     }
1147     &update;
1148     exit;
1149   }
1150
1151   $form->{id} = 0 if $form->{saveasnew};
1152
1153   # this is for the internal notes section for the [email] Subject
1154   if ($form->{type} =~ /_order$/) {
1155     if ($form->{type} eq 'sales_order') {
1156       $form->{label} = $locale->text('Sales Order');
1157
1158       $numberfld = "sonumber";
1159       $ordnumber = "ordnumber";
1160     } else {
1161       $form->{label} = $locale->text('Purchase Order');
1162
1163       $numberfld = "ponumber";
1164       $ordnumber = "ordnumber";
1165     }
1166
1167     $err = $locale->text('Cannot save order!');
1168
1169     check_delivered_flag();
1170
1171   } else {
1172     if ($form->{type} eq 'sales_quotation') {
1173       $form->{label} = $locale->text('Quotation');
1174
1175       $numberfld = "sqnumber";
1176       $ordnumber = "quonumber";
1177     } else {
1178       $form->{label} = $locale->text('Request for Quotation');
1179
1180       $numberfld = "rfqnumber";
1181       $ordnumber = "quonumber";
1182     }
1183
1184     $err = $locale->text('Cannot save quotation!');
1185
1186   }
1187
1188   # get new number in sequence if no number is given or if saveasnew was requested
1189   if (!$form->{$ordnumber} || $form->{saveasnew}) {
1190     $form->{$ordnumber} = $form->update_defaults(\%myconfig, $numberfld);
1191   }
1192
1193   relink_accounts();
1194
1195   $form->error($err) if (!OE->save(\%myconfig, \%$form));
1196
1197   # saving the history
1198   if(!exists $form->{addition}) {
1199     $form->{snumbers} = qq|ordnumber_| . $form->{ordnumber};
1200         $form->{addition} = "SAVED";
1201         $form->save_history($form->dbconnect(\%myconfig));
1202   }
1203   # /saving the history
1204
1205   $form->redirect($form->{label} . " $form->{$ordnumber} " .
1206                   $locale->text('saved!'));
1207
1208   $lxdebug->leave_sub();
1209 }
1210
1211 sub save {
1212   $lxdebug->enter_sub();
1213
1214   check_oe_access();
1215
1216   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
1217
1218
1219   if ($form->{type} =~ /_order$/) {
1220     $form->isblank("transdate", $locale->text('Order Date missing!'));
1221   } else {
1222     $form->isblank("transdate", $locale->text('Quotation Date missing!'));
1223   }
1224
1225   my $idx = $form->{type} =~ /_quotation$/ ? "quonumber" : "ordnumber";
1226   $form->{$idx} =~ s/^\s*//g;
1227   $form->{$idx} =~ s/\s*$//g;
1228
1229   $msg = ucfirst $form->{vc};
1230   $form->isblank($form->{vc}, $locale->text($msg . " missing!"));
1231
1232   # $locale->text('Customer missing!');
1233   # $locale->text('Vendor missing!');
1234
1235   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
1236     if ($form->{currency} ne $form->{defaultcurrency});
1237
1238   &validate_items;
1239   
1240   if($form->{payment_id}) { 
1241     $payment_id = $form->{payment_id};
1242   }
1243   
1244   # if the name changed get new values
1245   if (&check_name($form->{vc})) {
1246     if($form->{payment_id} eq "") { 
1247       $form->{payment_id} = $payment_id;
1248     }
1249     &update;
1250     exit;
1251   }
1252
1253   $form->{id} = 0 if $form->{saveasnew};
1254
1255   # this is for the internal notes section for the [email] Subject
1256   if ($form->{type} =~ /_order$/) {
1257     if ($form->{type} eq 'sales_order') {
1258       $form->{label} = $locale->text('Sales Order');
1259
1260       $numberfld = "sonumber";
1261       $ordnumber = "ordnumber";
1262     } else {
1263       $form->{label} = $locale->text('Purchase Order');
1264
1265       $numberfld = "ponumber";
1266       $ordnumber = "ordnumber";
1267     }
1268
1269     $err = $locale->text('Cannot save order!');
1270
1271     check_delivered_flag();
1272
1273   } else {
1274     if ($form->{type} eq 'sales_quotation') {
1275       $form->{label} = $locale->text('Quotation');
1276
1277       $numberfld = "sqnumber";
1278       $ordnumber = "quonumber";
1279     } else {
1280       $form->{label} = $locale->text('Request for Quotation');
1281
1282       $numberfld = "rfqnumber";
1283       $ordnumber = "quonumber";
1284     }
1285
1286     $err = $locale->text('Cannot save quotation!');
1287
1288   }
1289
1290   $form->{$ordnumber} = $form->update_defaults(\%myconfig, $numberfld)
1291     unless $form->{$ordnumber};
1292
1293   relink_accounts();
1294
1295   OE->save(\%myconfig, \%$form);
1296
1297   # saving the history
1298   if(!exists $form->{addition}) {
1299     $form->{snumbers} = qq|ordnumber_| . $form->{ordnumber};
1300         $form->{addition} = "SAVED";
1301         $form->save_history($form->dbconnect(\%myconfig));
1302   }
1303   # /saving the history 
1304
1305   $form->{simple_save} = 1;
1306   if(!$form->{print_and_save}) {
1307     set_headings("edit");
1308     &update;
1309     exit;
1310   }
1311   $lxdebug->leave_sub();
1312 }
1313
1314 sub delete {
1315   $lxdebug->enter_sub();
1316
1317   check_oe_access();
1318
1319   $form->header;
1320
1321   if ($form->{type} =~ /_order$/) {
1322     $msg       = $locale->text('Are you sure you want to delete Order Number');
1323     $ordnumber = 'ordnumber';
1324   } else {
1325     $msg = $locale->text('Are you sure you want to delete Quotation Number');
1326     $ordnumber = 'quonumber';
1327   }
1328
1329   print qq|
1330 <body>
1331
1332 <form method=post action=$form->{script}>
1333 |;
1334
1335   # delete action variable
1336   map { delete $form->{$_} } qw(action header);
1337
1338   foreach $key (keys %$form) {
1339     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
1340     $form->{$key} =~ s/\"/&quot;/g;
1341     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
1342   }
1343
1344   print qq|
1345 <h2 class=confirm>| . $locale->text('Confirm!') . qq|</h2>
1346
1347 <h4>$msg $form->{$ordnumber}</h4>
1348 <p>
1349 <input type="hidden" name="yes_nextsub" value="delete_order_quotation">
1350 <input name=action class=submit type=submit value="|
1351     . $locale->text('Yes') . qq|">
1352 <button class=submit type=button onclick="history.back()">|
1353     . $locale->text('No') . qq|</button>
1354 </form>
1355
1356 </body>
1357 </html>
1358 |;
1359
1360   $lxdebug->leave_sub();
1361 }
1362
1363 sub delete_order_quotation {
1364   $lxdebug->enter_sub();
1365
1366   check_oe_access();
1367
1368   if ($form->{type} =~ /_order$/) {
1369     $msg = $locale->text('Order deleted!');
1370     $err = $locale->text('Cannot delete order!');
1371   } else {
1372     $msg = $locale->text('Quotation deleted!');
1373     $err = $locale->text('Cannot delete quotation!');
1374   }
1375   if (OE->delete(\%myconfig, \%$form, $spool)){
1376     # saving the history
1377     if(!exists $form->{addition}) {
1378       $form->{snumbers} = qq|ordnumber_| . $form->{ordnumber};
1379           $form->{addition} = "DELETED";
1380           $form->save_history($form->dbconnect(\%myconfig));
1381     }
1382     # /saving the history 
1383     $form->info($msg);
1384     exit();
1385   }
1386   $form->error($err);
1387
1388   $lxdebug->leave_sub();
1389 }
1390
1391 sub invoice {
1392   $lxdebug->enter_sub();
1393
1394   check_oe_access();
1395   $auth->assert($form->{type} eq 'purchase_order' || $form->{type} eq 'request_quotation' ? 'vendor_invoice_edit' : 'invoice_edit');
1396
1397   $form->{old_employee_id} = $form->{employee_id};
1398   $form->{old_salesman_id} = $form->{salesman_id};
1399
1400   if ($form->{type} =~ /_order$/) {
1401
1402     # these checks only apply if the items don't bring their own ordnumbers/transdates.
1403     # The if clause ensures that by searching for empty ordnumber_#/transdate_# fields.
1404     $form->isblank("ordnumber", $locale->text('Order Number missing!'))
1405       if (+{ map { $form->{"ordnumber_$_"}, 1 } (1 .. $form->{rowcount} - 1) }->{''});
1406     $form->isblank("transdate", $locale->text('Order Date missing!'))
1407       if (+{ map { $form->{"transdate_$_"}, 1 } (1 .. $form->{rowcount} - 1) }->{''});
1408
1409     # also copy deliverydate from the order
1410     $form->{deliverydate} = $form->{reqdate} if $form->{reqdate};
1411     $form->{orddate}      = $form->{transdate};
1412   } else {
1413     $form->isblank("quonumber", $locale->text('Quotation Number missing!'));
1414     $form->isblank("transdate", $locale->text('Quotation Date missing!'));
1415     $form->{ordnumber}    = "";
1416     $form->{quodate}      = $form->{transdate};
1417   }
1418   
1419   $payment_id = $form->{payment_id} if $form->{payment_id};
1420   
1421   # if the name changed get new values
1422   if (&check_name($form->{vc})) {
1423     $form->{payment_id} = $payment_id if $form->{payment_id} eq "";
1424     &update;
1425     exit;
1426   }
1427
1428   $form->{cp_id} *= 1;
1429
1430   for $i (1 .. $form->{rowcount}) {
1431     for (qw(ship qty sellprice listprice basefactor)) {
1432       $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"}) if $form->{"${_}_${i}"};
1433     }
1434   }
1435
1436   if (   $form->{type} =~ /_order/
1437       && $form->{currency} ne $form->{defaultcurrency}) {
1438
1439     # check if we need a new exchangerate
1440     $buysell = ($form->{type} eq 'sales_order') ? "buy" : "sell";
1441
1442     $orddate      = $form->current_date(\%myconfig);
1443     $exchangerate = $form->check_exchangerate(\%myconfig, $form->{currency}, $orddate, $buysell);
1444
1445     if (!$exchangerate) {
1446       &backorder_exchangerate($orddate, $buysell);
1447       exit;
1448     }
1449   }
1450
1451   # close orders/quotations
1452   $form->{closed} = 1;
1453
1454   # save order if one ordnumber has been given
1455   # if not it's most likely a collective order, which can't be saved back
1456   # so they just have to be closed
1457   if (($form->{ordnumber} ne '') || ($form->{quonumber} ne '')) {
1458     OE->close_order(\%myconfig, \%$form) if ($form->{id});
1459   } else {
1460     OE->close_orders(\%myconfig, \%$form);
1461   }
1462
1463   $form->{convert_from_oe_ids} = $form->{id};
1464   $form->{transdate}           = $form->{invdate} = $form->current_date(\%myconfig);
1465   $form->{duedate}             = $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
1466   $form->{shipto}              = 1;
1467   $form->{defaultcurrency}     = $form->get_default_currency(\%myconfig);
1468
1469   delete @{$form}{qw(id closed)};
1470   $form->{rowcount}--;
1471
1472   if ($form->{type} =~ /_order$/) {
1473     $form->{exchangerate} = $exchangerate;
1474     &create_backorder;
1475   }
1476
1477   if (   $form->{type} eq 'purchase_order'
1478       || $form->{type} eq 'request_quotation') {
1479     $form->{title}  = $locale->text('Add Vendor Invoice');
1480     $form->{script} = 'ir.pl';
1481     $script         = "ir";
1482     $buysell        = 'sell';
1483   }
1484
1485   if (   $form->{type} eq 'sales_order' 
1486       || $form->{type} eq 'sales_quotation') {
1487     $form->{title}  = $locale->text('Add Sales Invoice');
1488     $form->{script} = 'is.pl';
1489     $script         = "is";
1490     $buysell        = 'buy';
1491   }
1492
1493   # bo creates the id, reset it
1494   map { delete $form->{$_} } qw(id subject message cc bcc printed emailed queued);
1495   $form->{ $form->{vc} } =~ s/--.*//g;
1496   $form->{type} = "invoice";
1497
1498   # locale messages
1499   $locale = new Locale "$myconfig{countrycode}", "$script";
1500
1501   require "bin/mozilla/$form->{script}";
1502
1503   map { $form->{"select$_"} = "" } ($form->{vc}, currency);
1504
1505   $currency = $form->{currency};
1506   &invoice_links;
1507
1508   $form->{currency}     = $currency;
1509   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, $buysell);
1510   $form->{exchangerate} = $form->{forex} || '';
1511
1512   $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
1513
1514   &prepare_invoice;
1515
1516   # format amounts
1517   for $i (1 .. $form->{rowcount}) {
1518     $form->{"discount_$i"} =
1519       $form->format_amount(\%myconfig, $form->{"discount_$i"});
1520
1521     ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
1522     $dec           = length $dec;
1523     $decimalplaces = ($dec > 2) ? $dec : 2;
1524
1525     # copy delivery date from reqdate for order -> invoice conversion
1526     $form->{"deliverydate_$i"} = $form->{"reqdate_$i"}
1527       unless $form->{"deliverydate_$i"};
1528
1529     $form->{"sellprice_$i"} =
1530       $form->format_amount(\%myconfig, $form->{"sellprice_$i"},
1531                            $decimalplaces);
1532
1533     (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
1534     $dec_qty = length $dec_qty;
1535     $form->{"qty_$i"} =
1536       $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
1537
1538     map { $form->{"${_}_$i"} =~ s/\"/&quot;/g }
1539       qw(partnumber description unit);
1540
1541   }
1542
1543   &display_form;
1544
1545   $lxdebug->leave_sub();
1546 }
1547
1548 sub backorder_exchangerate {
1549   $lxdebug->enter_sub();
1550
1551   check_oe_access();
1552
1553   my ($orddate, $buysell) = @_;
1554
1555   $form->header;
1556
1557   print qq|
1558 <body>
1559
1560 <form method=post action=$form->{script}>
1561 |;
1562
1563   # delete action variable
1564   map { delete $form->{$_} } qw(action header exchangerate);
1565
1566   foreach $key (keys %$form) {
1567     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
1568     $form->{$key} =~ s/\"/&quot;/g;
1569     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
1570   }
1571
1572   $form->{title} = $locale->text('Add Exchangerate');
1573
1574   print qq|
1575
1576 <input type=hidden name=exchangeratedate value=$orddate>
1577 <input type=hidden name=buysell value=$buysell>
1578
1579 <table width=100%>
1580   <tr><th class=listtop>$form->{title}</th></tr>
1581   <tr height="5"></tr>
1582   <tr>
1583     <td>
1584       <table>
1585         <tr>
1586           <th align=right>| . $locale->text('Currency') . qq|</th>
1587           <td>$form->{currency}</td>
1588         </tr>
1589         <tr>
1590           <th align=right>| . $locale->text('Date') . qq|</th>
1591           <td>$orddate</td>
1592         </tr>
1593         <tr>
1594           <th align=right>| . $locale->text('Exchangerate') . qq|</th>
1595           <td><input name=exchangerate size=11></td>
1596         </tr>
1597       </table>
1598     </td>
1599   </tr>
1600 </table>
1601
1602 <hr size=3 noshade>
1603
1604 <br>
1605 <input type=hidden name=nextsub value=save_exchangerate>
1606
1607 <input name=action class=submit type=submit value="|
1608     . $locale->text('Continue') . qq|">
1609
1610 </form>
1611
1612 </body>
1613 </html>
1614 |;
1615
1616   $lxdebug->leave_sub();
1617 }
1618
1619 sub save_exchangerate {
1620   $lxdebug->enter_sub();
1621
1622   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'));
1623   $form->{exchangerate} =
1624     $form->parse_amount(\%myconfig, $form->{exchangerate});
1625   $form->save_exchangerate(\%myconfig, $form->{currency},
1626                            $form->{exchangeratedate},
1627                            $form->{exchangerate}, $form->{buysell});
1628
1629   &invoice;
1630
1631   $lxdebug->leave_sub();
1632 }
1633
1634 sub create_backorder {
1635   $lxdebug->enter_sub();
1636
1637   $form->{shipped} = 1;
1638
1639   # figure out if we need to create a backorder
1640   # items aren't saved if qty != 0
1641
1642   for $i (1 .. $form->{rowcount}) {
1643     $totalqty  += $qty  = $form->{"qty_$i"};
1644     $totalship += $ship = $form->{"ship_$i"};
1645
1646     $form->{"qty_$i"} = $qty - $ship;
1647   }
1648
1649   if ($totalship == 0) {
1650     map { $form->{"ship_$_"} = $form->{"qty_$_"} } (1 .. $form->{rowcount});
1651     $form->{ordtotal} = 0;
1652     $form->{shipped}  = 0;
1653     return;
1654   }
1655
1656   if ($totalqty == $totalship) {
1657     map { $form->{"qty_$_"} = $form->{"ship_$_"} } (1 .. $form->{rowcount});
1658     $form->{ordtotal} = 0;
1659     return;
1660   }
1661
1662   @flds = (
1663     qw(partnumber description qty ship unit sellprice discount id inventory_accno bin income_accno expense_accno listprice assembly taxaccounts partsgroup)
1664   );
1665
1666   for $i (1 .. $form->{rowcount}) {
1667     map {
1668       $form->{"${_}_$i"} =
1669         $form->format_amount(\%myconfig, $form->{"${_}_$i"})
1670     } qw(sellprice discount);
1671   }
1672
1673   relink_accounts();
1674
1675   OE->save(\%myconfig, \%$form);
1676
1677   # rebuild rows for invoice
1678   @a     = ();
1679   $count = 0;
1680
1681   for $i (1 .. $form->{rowcount}) {
1682     $form->{"qty_$i"} = $form->{"ship_$i"};
1683
1684     if ($form->{"qty_$i"}) {
1685       push @a, {};
1686       $j = $#a;
1687       map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
1688       $count++;
1689     }
1690   }
1691
1692   $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
1693   $form->{rowcount} = $count;
1694
1695   $lxdebug->leave_sub();
1696 }
1697
1698 sub save_as_new {
1699   $lxdebug->enter_sub();
1700
1701   check_oe_access();
1702
1703   $form->{saveasnew} = 1;
1704   $form->{closed}    = 0;
1705   map { delete $form->{$_} } qw(printed emailed queued);
1706
1707   # Let Lx-Office assign a new order number if the user hasn't changed the
1708   # previous one. If it has been changed manually then use it as-is.
1709   my $idx = $form->{type} =~ /_quotation$/ ? "quonumber" : "ordnumber";
1710   $form->{$idx} =~ s/^\s*//g;
1711   $form->{$idx} =~ s/\s*$//g;
1712   if ($form->{saved_xyznumber} &&
1713       ($form->{saved_xyznumber} eq $form->{$idx})) {
1714     delete($form->{$idx});
1715   }
1716
1717   &save;
1718
1719   $lxdebug->leave_sub();
1720 }
1721
1722 sub check_for_direct_delivery_yes {
1723   $lxdebug->enter_sub();
1724
1725   check_oe_access();
1726
1727   $form->{direct_delivery_checked} = 1;
1728   delete @{$form}{grep /^shipto/, keys %{ $form }};
1729   map { s/^CFDD_//; $form->{$_} = $form->{"CFDD_${_}"} } grep /^CFDD_/, keys %{ $form };
1730   $form->{shipto} = 1;
1731   purchase_order();
1732   $lxdebug->leave_sub();
1733 }
1734
1735 sub check_for_direct_delivery_no {
1736   $lxdebug->enter_sub();
1737
1738   check_oe_access();
1739
1740   $form->{direct_delivery_checked} = 1;
1741   delete @{$form}{grep /^shipto/, keys %{ $form }};
1742   purchase_order();
1743
1744   $lxdebug->leave_sub();
1745 }
1746
1747 sub check_for_direct_delivery {
1748   $lxdebug->enter_sub();
1749
1750   check_oe_access();
1751
1752   if ($form->{direct_delivery_checked}
1753       || (!$form->{shiptoname} && !$form->{shiptostreet} && !$form->{shipto_id})) {
1754     $lxdebug->leave_sub();
1755     return;
1756   }
1757
1758   if ($form->{shipto_id}) {
1759     Common->get_shipto_by_id(\%myconfig, $form, $form->{shipto_id}, "CFDD_");
1760
1761   } else {
1762     map { $form->{"CFDD_${_}"} = $form->{$_ } } grep /^shipto/, keys %{ $form };
1763   }
1764
1765   delete $form->{action};
1766   $form->{VARIABLES} = [ map { { "key" => $_, "value" => $form->{$_} } } grep { ($_ ne 'login') && ($_ ne 'password') && (ref $_ eq "") } keys %{ $form } ];
1767
1768   $form->header();
1769   print $form->parse_html_template("oe/check_for_direct_delivery");
1770
1771   $lxdebug->leave_sub();
1772
1773   exit 0;
1774 }
1775
1776 sub purchase_order {
1777   $lxdebug->enter_sub();
1778
1779   check_oe_access();
1780   $auth->assert('purchase_order_edit');
1781
1782   if ($form->{type} eq 'sales_order') {
1783     check_for_direct_delivery();
1784   }
1785
1786   if (   $form->{type} eq 'sales_quotation'
1787       || $form->{type} eq 'request_quotation') {
1788     OE->close_order(\%myconfig, \%$form);
1789   }
1790
1791   if ($form->{type} =~ /^sales_/) {
1792     delete($form->{ordnumber});
1793   }
1794
1795   $form->{cp_id} *= 1;
1796
1797   $form->{title} = $locale->text('Add Purchase Order');
1798   $form->{vc}    = "vendor";
1799   $form->{type}  = "purchase_order";
1800
1801   &poso;
1802
1803   $lxdebug->leave_sub();
1804 }
1805
1806 sub sales_order {
1807   $lxdebug->enter_sub();
1808
1809   check_oe_access();
1810   $auth->assert('sales_order_edit');
1811
1812   if (   $form->{type} eq 'sales_quotation'
1813       || $form->{type} eq 'request_quotation') {
1814     OE->close_order(\%myconfig, $form);
1815   }
1816
1817   if ($form->{type} eq "purchase_order") {
1818     delete($form->{ordnumber});
1819   }
1820
1821   $form->{cp_id} *= 1;
1822
1823   $form->{title}  = $locale->text('Add Sales Order');
1824   $form->{vc}     = "customer";
1825   $form->{type}   = "sales_order";
1826
1827   &poso;
1828
1829   $lxdebug->leave_sub();
1830 }
1831
1832 sub poso {
1833   $lxdebug->enter_sub();
1834
1835   check_oe_access();
1836   $auth->assert('purchase_order_edit | sales_order_edit');
1837
1838   $form->{transdate} = $form->current_date(\%myconfig);
1839   delete $form->{duedate};
1840
1841   $form->{convert_from_oe_ids} = $form->{id};
1842   $form->{closed}              = 0;
1843
1844   $form->{old_employee_id}     = $form->{employee_id};
1845   $form->{old_salesman_id}     = $form->{salesman_id};
1846
1847   # reset
1848   map { delete $form->{$_} } qw(id subject message cc bcc printed emailed queued customer vendor creditlimit creditremaining discount tradediscount oldinvtotal delivered);
1849
1850   for $i (1 .. $form->{rowcount}) {
1851     map { $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"}) if ($form->{"${_}_${i}"}) } qw(ship qty sellprice listprice basefactor);
1852   }
1853
1854   my %saved_vars = map { $_ => $form->{$_} } grep { $form->{$_} } qw(currency);
1855
1856   &order_links;
1857
1858   map { $form->{$_} = $saved_vars{$_} } keys %saved_vars;
1859
1860   &prepare_order;
1861
1862   # format amounts
1863   for $i (1 .. $form->{rowcount} - 1) {
1864     map { $form->{"${_}_$i"} =~ s/\"/&quot;/g } qw(partnumber description unit);
1865   }
1866
1867   &update;
1868
1869   $lxdebug->leave_sub();
1870 }
1871
1872 sub delivery_order {
1873   $lxdebug->enter_sub();
1874
1875   if ($form->{type} =~ /^sales/) {
1876     $auth->assert('sales_delivery_order_edit');
1877
1878     $form->{vc}    = 'customer';
1879     $form->{type}  = 'sales_delivery_order';
1880
1881   } else {
1882     $auth->assert('purchase_delivery_order_edit');
1883
1884     $form->{vc}    = 'vendor';
1885     $form->{type}  = 'purchase_delivery_order';
1886   }
1887
1888   require "bin/mozilla/do.pl";
1889
1890   $form->{cp_id}               *= 1;
1891   $form->{convert_from_oe_ids}  = $form->{id};
1892   $form->{transdate}            = $form->current_date(\%myconfig);
1893   delete $form->{duedate};
1894
1895   $form->{old_employee_id}  = $form->{employee_id};
1896   $form->{old_salesman_id}  = $form->{salesman_id};
1897
1898   # reset
1899   delete @{$form}{qw(id subject message cc bcc printed emailed queued creditlimit creditremaining discount tradediscount oldinvtotal closed delivered)};
1900
1901   for $i (1 .. $form->{rowcount}) {
1902     map { $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"}) if ($form->{"${_}_${i}"}) } qw(ship qty sellprice listprice basefactor);
1903   }
1904
1905   my %old_values = map { $_ => $form->{$_} } qw(customer_id oldcustomer customer vendor_id oldvendor vendor);
1906
1907   order_links();
1908
1909   prepare_order();
1910
1911   map { $form->{$_} = $old_values{$_} if ($old_values{$_}) } keys %old_values;
1912
1913   update();
1914
1915   $lxdebug->leave_sub();
1916 }
1917
1918 sub e_mail {
1919   $lxdebug->enter_sub();
1920
1921   check_oe_access();
1922
1923   $form->{print_and_save} = 1;
1924
1925   $print_post = 1;
1926
1927   my $saved_form = save_form();
1928
1929   save();
1930
1931   restore_form($saved_form, 0, qw(id ordnumber quonumber));
1932
1933   edit_e_mail();
1934
1935   $lxdebug->leave_sub();
1936 }
1937
1938 sub yes {
1939   call_sub($form->{yes_nextsub});
1940 }
1941
1942 sub no {
1943   call_sub($form->{no_nextsub});
1944 }
1945
1946 ######################################################################################################
1947 # IO ENTKOPPLUNG
1948 # ###############################################################################################
1949 sub display_form {
1950   $lxdebug->enter_sub();
1951
1952   check_oe_access();
1953
1954   retrieve_partunits() if ($form->{type} =~ /_delivery_order$/);
1955
1956   $form->{"taxaccounts"} =~ s/\s*$//;
1957   $form->{"taxaccounts"} =~ s/^\s*//;
1958   foreach my $accno (split(/\s*/, $form->{"taxaccounts"})) {
1959     map({ delete($form->{"${accno}_${_}"}); } qw(rate description taxnumber));
1960   }
1961   $form->{"taxaccounts"} = "";
1962
1963   for my $i (1 .. $form->{"rowcount"}) {
1964     IC->retrieve_accounts(\%myconfig, $form, $form->{"id_$i"}, $i, 1) if $form->{"id_$i"};
1965   }
1966
1967   $form->{rowcount}++;
1968   $form->{"project_id_$form->{rowcount}"} = $form->{globalproject_id};
1969
1970   $form->language_payment(\%myconfig);
1971
1972   Common::webdav_folder($form) if ($webdav);
1973
1974   &form_header;
1975
1976   # create rows
1977   display_row($form->{rowcount}) if $form->{rowcount};
1978
1979   &form_footer;
1980
1981   $lxdebug->leave_sub();
1982 }
1983
1984 sub report_for_todo_list {
1985   $lxdebug->enter_sub();
1986
1987   my $quotations = OE->transactions_for_todo_list();
1988   my $content;
1989
1990   if (@{ $quotations }) {
1991     my $edit_url = build_std_url('script=oe.pl', 'action=edit', 'type=sales_quotation', 'vc=customer');
1992
1993     $content     = $form->parse_html_template('oe/report_for_todo_list', { 'QUOTATIONS' => $quotations,
1994                                                                            'edit_url'   => $edit_url });
1995   }
1996
1997   $lxdebug->leave_sub();
1998
1999   return $content;
2000 }
2001