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