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