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