]> wagnertech.de Git - mfinanz.git/blob - bin/mozilla/oe.pl
restart apache2 in postinst
[mfinanz.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., 51 Franklin Street, Fifth Floor, Boston,
28 # MA 02110-1335, USA.
29 #======================================================================
30 #
31 # Order entry module
32 # Quotation module
33 #======================================================================
34
35
36 use Carp;
37 use POSIX qw(strftime);
38 use Try::Tiny;
39
40 use SL::DB::Order;
41 use SL::DB::OrderItem;
42 use SL::DO;
43 use SL::FU;
44 use SL::OE;
45 use SL::IR;
46 use SL::IS;
47 use SL::Helper::Flash qw(flash_later);
48 use SL::Helper::UserPreferences::DisplayPreferences;
49 use SL::Helper::ShippedQty;
50 use SL::MoreCommon qw(ary_diff restore_form save_form);
51 use SL::Presenter::ItemsList;
52 use SL::ReportGenerator;
53 use SL::YAML;
54 use List::MoreUtils qw(uniq any none);
55 use List::Util qw(min max reduce sum);
56 use Data::Dumper;
57
58 use SL::Controller::Order;
59 use SL::DB::Customer;
60 use SL::DB::TaxZone;
61 use SL::DB::PaymentTerm;
62 use SL::DB::ValidityToken;
63 use SL::DB::Vendor;
64
65 require "bin/mozilla/common.pl";
66 require "bin/mozilla/io.pl";
67 require "bin/mozilla/reportgenerator.pl";
68
69 use strict;
70
71 1;
72
73 # end of main
74
75 # For locales.pl:
76 # $locale->text('Edit the purchase_order');
77 # $locale->text('Edit the sales_order');
78 # $locale->text('Edit the request_quotation');
79 # $locale->text('Edit the sales_quotation');
80
81 # $locale->text('Workflow purchase_order');
82 # $locale->text('Workflow sales_order');
83 # $locale->text('Workflow request_quotation');
84 # $locale->text('Workflow sales_quotation');
85
86 my $oe_access_map = {
87   'sales_order_intake'          => 'sales_order_edit',
88   'sales_order'                 => 'sales_order_edit',
89   'purchase_order'              => 'purchase_order_edit',
90   'purchase_order_confirmation' => 'purchase_order_edit',
91   'request_quotation'           => 'request_quotation_edit',
92   'sales_quotation'             => 'sales_quotation_edit',
93   'purchase_quotation_intake'   => 'request_quotation_edit',
94 };
95
96 my $oe_view_access_map = {
97   'sales_order_intake'          => 'sales_order_edit       | sales_order_view',
98   'sales_order'                 => 'sales_order_edit       | sales_order_view',
99   'purchase_order'              => 'purchase_order_edit    | purchase_order_view',
100   'purchase_order_confirmation' => 'purchase_order_edit  | purchase_order_view',
101   'request_quotation'           => 'request_quotation_edit | request_quotation_view',
102   'sales_quotation'             => 'sales_quotation_edit   | sales_quotation_view',
103   'purchase_quotation_intake'   => 'request_quotation_edit | request_quotation_view',
104 };
105
106 sub check_oe_access {
107   my (%params) = @_;
108   my $form     = $main::form;
109
110   my $right   = ($params{with_view}) ? $oe_view_access_map->{$form->{type}} : $oe_access_map->{$form->{type}};
111   $right    ||= 'DOES_NOT_EXIST';
112
113   $main::auth->assert($right);
114 }
115
116 sub check_oe_conversion_to_sales_invoice_allowed {
117   return 1 if  $::form->{type} !~ m/^sales/;
118   return 1 if ($::form->{type} =~ m/quotation/) && $::instance_conf->get_allow_sales_invoice_from_sales_quotation;
119   return 1 if ($::form->{type} =~ m/order/)     && $::instance_conf->get_allow_sales_invoice_from_sales_order;
120
121   $::form->show_generic_error($::locale->text("You do not have the permissions to access this function."));
122
123   return 0;
124 }
125
126 sub new_sales_order {
127   $main::lxdebug->enter_sub();
128
129   check_oe_access();
130
131   my $c = SL::Controller::Order->new;
132   $c->action_edit_collective();
133
134   $main::lxdebug->leave_sub();
135   $::dispatcher->end_request;
136 }
137
138 sub convert_to_delivery_orders {
139   # collect order ids
140   my @multi_ids = map {
141     $_ =~ m{^multi_id_(\d+)$} && $::form->{'multi_id_' . $1} && $::form->{'trans_id_' . $1}
142   } grep { $_ =~ m{^multi_id_\d+$} } keys %$::form;
143
144   # make new delivery orders from given orders
145   my @orders = map { SL::DB::Order->new(id => $_)->load } @multi_ids;
146   my @do_ids;
147   my @failed;
148   foreach my $order (@orders) {
149     # Only consider not delivered quantities.
150     SL::Helper::ShippedQty->new->calculate($order)->write_to(\@{$order->items});
151
152     my @items_with_not_delivered_qty =
153       grep {$_->qty > 0}
154       map  {$_->qty($_->qty - $_->shipped_qty); $_}
155       @{$order->items_sorted};
156
157     my $delivery_order;
158     try {
159       die t8('no undelivered items') if !@items_with_not_delivered_qty;
160       $delivery_order = $order->convert_to_delivery_order(items => \@items_with_not_delivered_qty);
161     } catch {
162       push @failed, {ordnumber => $order->ordnumber, error => $_};
163     };
164     push @do_ids, $delivery_order->id if $delivery_order;
165   }
166
167   require "bin/mozilla/do.pl";
168   $::form->{script}        = 'do.pl';
169   $::form->{type}          = 'sales_delivery_order';
170   $::form->{ids}           = \@do_ids;
171   $::form->{"l_$_"}        = 'Y' for qw(donumber ordnumber cusordnumber transdate reqdate name employee);
172   $::form->{top_info_text} = $::locale->text('Converted delivery orders');
173
174   flash('info', t8('#1 salses orders were converted to #2 delivery orders', scalar @orders, scalar @do_ids));
175   if (@failed) {
176     flash('error', t8('The following orders could not be converted to delivery orders:'));
177     flash('error', $_->{ordnumber} . ': ' . $_->{error}) for @failed;
178   }
179
180   orders();
181 }
182
183 sub order_links {
184   $main::lxdebug->enter_sub();
185
186   my (%params) = @_;
187
188   my $form     = $main::form;
189   my %myconfig = %main::myconfig;
190   my $locale   = $main::locale;
191
192   check_oe_access();
193
194   # retrieve order/quotation
195   my $editing = $form->{id};
196
197   OE->retrieve(\%myconfig, \%$form);
198
199   # if multiple rowcounts (== collective order) then check if the
200   # there were more than one customer (in that case OE::retrieve removes
201   # the content from the field)
202   $form->error($locale->text('Collective Orders only work for orders from one customer!'))
203     if          $form->{rowcount}  && $form->{type}     eq 'sales_order'
204      && defined $form->{customer}  && $form->{customer} eq '';
205
206   $form->backup_vars(qw(payment_id language_id taxzone_id salesman_id taxincluded cp_id intnotes shipto_id delivery_term_id currency));
207
208   # get customer / vendor
209   if ($form->{type} =~ /(purchase_order|request_quotation)/) {
210     IR->get_vendor(\%myconfig, \%$form);
211   } else {
212     IS->get_customer(\%myconfig, \%$form);
213     $form->{billing_address_id} = $form->{default_billing_address_id} if $params{is_new};
214   }
215
216   $form->restore_vars(qw(payment_id language_id taxzone_id intnotes cp_id shipto_id delivery_term_id));
217   $form->restore_vars(qw(currency))    if $form->{id};
218   $form->restore_vars(qw(taxincluded)) if $form->{id};
219   $form->restore_vars(qw(salesman_id)) if $editing;
220   $form->{forex}       = $form->{exchangerate};
221   $form->{employee}    = "$form->{employee}--$form->{employee_id}";
222
223   $main::lxdebug->leave_sub();
224 }
225
226 sub prepare_order {
227   $main::lxdebug->enter_sub();
228
229   my $form     = $main::form;
230   my %myconfig = %main::myconfig;
231
232   check_oe_access();
233
234   $form->{formname} ||= $form->{type};
235
236   # format discounts if values come from db. either as single id, or as a collective order
237   my $format_discounts = $form->{id} || $form->{convert_from_oe_ids};
238
239   for my $i (1 .. $form->{rowcount}) {
240     $form->{"reqdate_$i"} ||= $form->{"deliverydate_$i"};
241     $form->{"discount_$i"}  = $form->format_amount(\%myconfig, $form->{"discount_$i"} * ($format_discounts ? 100 : 1));
242     $form->{"sellprice_$i"} = $form->format_amount(\%myconfig, $form->{"sellprice_$i"});
243     $form->{"lastcost_$i"}  = $form->format_amount(\%myconfig, $form->{"lastcost_$i"});
244     $form->{"qty_$i"}       = $form->format_amount(\%myconfig, $form->{"qty_$i"});
245   }
246
247   $main::lxdebug->leave_sub();
248 }
249
250 sub setup_oe_search_action_bar {
251   my %params = @_;
252
253   for my $bar ($::request->layout->get('actionbar')) {
254     $bar->add(
255       action => [
256         t8('Search'),
257         submit    => [ '#form' ],
258         accesskey => 'enter',
259         checks    => [ 'kivi.validate_form' ],
260       ],
261     );
262   }
263   $::request->layout->add_javascripts('kivi.Validator.js');
264 }
265
266 sub setup_oe_orders_action_bar {
267   my %params = @_;
268
269   return unless $::form->{type} eq 'sales_order';
270
271   for my $bar ($::request->layout->get('actionbar')) {
272     $bar->add(
273       combobox => [
274         action => [
275           t8('Actions'),
276         ],
277         action => [
278           t8('New sales order'),
279           submit    => [ '#form', { action => 'new_sales_order' } ],
280           checks    => [ [ 'kivi.check_if_entries_selected', '[name^=multi_id_]' ] ],
281         ],
282         action => [
283           t8('Convert to delivery orders'),
284           submit => [ '#form', { action => 'convert_to_delivery_orders' } ],
285           checks => [ [ 'kivi.check_if_entries_selected', '[name^=multi_id_]' ] ],
286         ],
287       ],
288     );
289   }
290 }
291
292 sub search {
293   $main::lxdebug->enter_sub();
294
295   my $form     = $main::form;
296   my %myconfig = %main::myconfig;
297   my $locale   = $main::locale;
298
299   check_oe_access(with_view => 1);
300
301   if ($form->{type} eq 'purchase_order') {
302     $form->{vc}        = 'vendor';
303     $form->{ordnrname} = 'ordnumber';
304     $form->{title}     = $locale->text('Purchase Orders');
305     $form->{ordlabel}  = $locale->text('Order Number');
306
307   } elsif ($form->{type} eq 'purchase_order_confirmation') {
308     $form->{vc}        = 'vendor';
309     $form->{ordnrname} = 'ordnumber';
310     $form->{title}     = $locale->text('Purchase Order Confirmations');
311     $form->{ordlabel}  = $locale->text('Order Confirmation Number');
312
313   } elsif ($form->{type} eq 'request_quotation') {
314     $form->{vc}        = 'vendor';
315     $form->{ordnrname} = 'quonumber';
316     $form->{title}     = $locale->text('Request for Quotations');
317     $form->{ordlabel}  = $locale->text('RFQ Number');
318
319   } elsif ($form->{type} eq 'purchase_quotation_intake') {
320     $form->{vc}        = 'vendor';
321     $form->{ordnrname} = 'quonumber';
322     $form->{title}     = $locale->text('Purchase Quotation Intakes');
323     $form->{ordlabel}  = $locale->text('Quotation Number');
324
325   } elsif ($form->{type} eq 'sales_order_intake') {
326     $form->{vc}        = 'customer';
327     $form->{ordnrname} = 'ordnumber';
328     $form->{title}     = $locale->text('Sales Order Intakes');
329     $form->{ordlabel}  = $locale->text('Order Number');
330
331   } elsif ($form->{type} eq 'sales_order') {
332     $form->{vc}        = 'customer';
333     $form->{ordnrname} = 'ordnumber';
334     $form->{title}     = $locale->text('Sales Order Confirmations');
335     $form->{ordlabel}  = $locale->text('Order Number');
336
337   } elsif ($form->{type} eq 'sales_quotation') {
338     $form->{vc}        = 'customer';
339     $form->{ordnrname} = 'quonumber';
340     $form->{title}     = $locale->text('Quotations');
341     $form->{ordlabel}  = $locale->text('Quotation Number');
342
343   } else {
344     $form->show_generic_error($locale->text('oe.pl::search called with unknown type'));
345   }
346
347   # setup vendor / customer data
348   $form->get_lists("projects"     => { "key" => "ALL_PROJECTS", "all" => 1 },
349                    "taxzones"     => "ALL_TAXZONES",
350                    "business_types" => "ALL_BUSINESS_TYPES",);
351   $form->{ALL_EMPLOYEES}      = SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]);
352   $form->{ALL_DEPARTMENTS}    = SL::DB::Manager::Department->get_all;
353   $form->{ALL_ORDER_STATUSES} = SL::DB::Manager::OrderStatus->get_all_sorted;
354
355   $form->{CT_CUSTOM_VARIABLES}                  = CVar->get_configs('module' => 'CT');
356   ($form->{CT_CUSTOM_VARIABLES_FILTER_CODE},
357    $form->{CT_CUSTOM_VARIABLES_INCLUSION_CODE}) = CVar->render_search_options('variables'      => $form->{CT_CUSTOM_VARIABLES},
358                                                                               'include_prefix' => 'l_',
359                                                                               'include_value'  => 'Y');
360
361   # constants and subs for template
362   $form->{vc_keys}         = sub { "$_[0]->{name}--$_[0]->{id}" };
363
364   $form->{ORDER_PROBABILITIES} = [ map { { title => ($_ * 10) . '%', id => $_ * 10 } } (0..10) ];
365
366   $::request->{layout}->use_javascript(map { "${_}.js" } qw(autocomplete_project));
367
368   setup_oe_search_action_bar();
369
370   $form->header();
371
372   print $form->parse_html_template('oe/search', {
373     is_order => scalar($form->{type} =~ /_order/),
374   });
375
376   $main::lxdebug->leave_sub();
377 }
378
379 sub create_subtotal_row {
380   $main::lxdebug->enter_sub();
381
382   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
383
384   my $form     = $main::form;
385   my %myconfig = %main::myconfig;
386
387   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
388
389   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
390
391   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
392
393   map { $totals->{$_} = 0 } @{ $subtotal_columns };
394
395   $main::lxdebug->leave_sub();
396
397   return $row;
398 }
399
400 sub orders {
401   $main::lxdebug->enter_sub();
402
403   my $form     = $main::form;
404   my %myconfig = %main::myconfig;
405   my $locale   = $main::locale;
406   my $cgi      = $::request->{cgi};
407
408   my %params   = @_;
409   check_oe_access(with_view => 1);
410
411   my $ordnumber = ($form->{type} =~ /_order_intake$|_order$|purchase_order_confirmation/) ? "ordnumber" : "quonumber";
412
413   ($form->{ $form->{vc} }, $form->{"$form->{vc}_id"}) = split(/--/, $form->{ $form->{vc} });
414   report_generator_set_default_sort('transdate', 1);
415   OE->transactions(\%myconfig, \%$form);
416
417   $form->{rowcount} = scalar @{ $form->{OE} };
418
419   my @columns = (
420     "transdate",               "reqdate",
421     "id",                      $ordnumber,
422     "cusordnumber",            "vendor_confirmation_number",
423     "customernumber",
424     "name",                    "netamount",
425     "tax",                     "amount",
426     "remaining_netamount",     "remaining_amount",
427     "curr",                    "employee",
428     "salesman",
429     "shipvia",                 "globalprojectnumber",
430     "transaction_description", "department",            "open",
431     "delivered",               "periodic_invoices",
432     "marge_total",             "marge_percent",
433     "vcnumber",                "ustid",
434     "country",                 "shippingpoint",
435     "taxzone",                 "insertdate",
436     "order_probability",       "expected_billing_date", "expected_netamount",
437     "payment_terms",           "intnotes",              "order_status",
438     "items",
439     "shiptoname", "shiptodepartment_1", "shiptodepartment_2", "shiptostreet",
440     "shiptozipcode", "shiptocity", "shiptocountry",
441   );
442
443   # only show checkboxes if gotten here via sales_order form.
444   my $allow_multiple_orders = $form->{type} eq 'sales_order';
445   if ($allow_multiple_orders) {
446     unshift @columns, "ids";
447   }
448
449   $form->{l_open}              = $form->{l_closed} = "Y" if ($form->{open}      && $form->{closed});
450   $form->{l_delivered}         = "Y"                     if ($form->{delivered} && $form->{notdelivered});
451   $form->{l_periodic_invoices} = "Y"                     if ($form->{periodic_invoices_active} && $form->{periodic_invoices_inactive});
452   map { $form->{"l_${_}"} = 'Y' } qw(order_probability expected_billing_date expected_netamount) if $form->{l_order_probability_expected_billing_date};
453
454   my $attachment_basename;
455   if ($form->{vc} eq 'vendor') {
456     if ($form->{type} eq 'purchase_order') {
457       $form->{title}       = $locale->text('Purchase Orders');
458       $attachment_basename = $locale->text('purchase_order_list');
459     } elsif ($form->{type} eq 'purchase_order_confirmation') {
460       $form->{title}       = $locale->text('Purchase Order Confirmations');
461       $attachment_basename = $locale->text('purchase_order_confirmation_list');
462     } elsif ($form->{type} eq 'purchase_quotation_intake') {
463       $form->{title}       = $locale->text('Purchase Quotation Intakes');
464       $attachment_basename = $locale->text('purchase_quotation_intake_list');
465     } else {
466       $form->{title}       = $locale->text('Request for Quotations');
467       $attachment_basename = $locale->text('rfq_list');
468     }
469
470   } else {
471     if ($form->{type} eq 'sales_order_intake') {
472       $form->{title}       = $locale->text('Sales Order Intakes');
473       $attachment_basename = $locale->text('sales_order_intake_list');
474     } elsif ($form->{type} eq 'sales_order') {
475       $form->{title}       = $locale->text('Sales Orders');
476       $attachment_basename = $locale->text('sales_order_list');
477     } else {
478       $form->{title}       = $locale->text('Quotations');
479       $attachment_basename = $locale->text('quotation_list');
480     }
481   }
482
483   my $report = SL::ReportGenerator->new(\%myconfig, $form);
484
485   my $ct_cvar_configs = CVar->get_configs('module' => 'CT');
486   my @ct_includeable_custom_variables = grep { $_->{includeable} } @{ $ct_cvar_configs };
487   my @ct_searchable_custom_variables  = grep { $_->{searchable} }  @{ $ct_cvar_configs };
488
489   my %column_defs_cvars            = map { +"cvar_$_->{name}" => { 'text' => $_->{description} } } @ct_includeable_custom_variables;
490   push @columns, map { "cvar_$_->{name}" } @ct_includeable_custom_variables;
491
492   my @hidden_variables = map { "l_${_}" } @columns;
493   push @hidden_variables, "l_subtotal", $form->{vc}, qw(
494     l_closed l_notdelivered open closed delivered notdelivered ordnumber
495     quonumber cusordnumber transaction_description transdatefrom transdateto
496     type vc employee_id salesman_id reqdatefrom reqdateto projectnumber
497     project_id periodic_invoices_active periodic_invoices_inactive
498     business_id shippingpoint taxzone_id reqdate_unset_or_old insertdatefrom
499     insertdateto order_probability_op order_probability_value
500     expected_billing_date_from expected_billing_date_to parts_partnumber
501     parts_description all department_id intnotes phone_notes fulltext
502     order_status_id shiptoname shiptodepartment_1 shiptodepartment_2
503     shiptostreet shiptozipcode shiptocity shiptocountry
504     vendor_confirmation_number
505   );
506   push @hidden_variables, map { "cvar_$_->{name}" } @ct_searchable_custom_variables;
507
508   my   @keys_for_url = grep { $form->{$_} } @hidden_variables;
509   push @keys_for_url, 'taxzone_id' if $form->{taxzone_id} ne ''; # taxzone_id could be 0
510
511   my $href = $params{want_binary_pdf} ? '' : build_std_url('action=orders', @keys_for_url);
512
513   my %column_defs = (
514     'ids'                     => { raw_header_data => SL::Presenter::Tag::checkbox_tag("", id => "multi_all", checkall => "[data-checkall=1]"), align => 'center' },
515     'transdate'               => { 'text' => $locale->text('Date'), },
516     'reqdate'                 => { 'text' => $form->{type} =~ /_order/ ? $locale->text('Required by') : $locale->text('Valid until') },
517     'id'                      => { 'text' => $locale->text('ID'), },
518     'ordnumber'               => { 'text' => $form->{type} eq "purchase_order_confirmation" ? $locale->text('Confirmation'): $locale->text('Order'), },
519     'quonumber'               => { 'text' => $form->{type} eq "request_quotation" ? $locale->text('RFQ') : $locale->text('Quotation'), },
520     'cusordnumber'            => { 'text' => $locale->text('Customer Order Number'), },
521     'name'                    => { 'text' => $form->{vc} eq 'customer' ? $locale->text('Customer') : $locale->text('Vendor'), },
522     'customernumber'          => { 'text' => $locale->text('Customer Number'), },
523     'netamount'               => { 'text' => $locale->text('Amount'), },
524     'tax'                     => { 'text' => $locale->text('Tax'), },
525     'amount'                  => { 'text' => $locale->text('Total'), },
526     'remaining_amount'        => { 'text' => $locale->text('Remaining Amount'), },
527     'remaining_netamount'     => { 'text' => $locale->text('Remaining Net Amount'), },
528     'curr'                    => { 'text' => $locale->text('Curr'), },
529     'employee'                => { 'text' => $locale->text('Employee'), },
530     'salesman'                => { 'text' => $locale->text('Salesman'), },
531     'shipvia'                 => { 'text' => $locale->text('Ship via'), },
532     'globalprojectnumber'     => { 'text' => $locale->text('Project Number'), },
533     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
534     'department'              => { 'text' => $locale->text('Department'), },
535     'open'                    => { 'text' => $locale->text('Open'), },
536     'delivered'               => { 'text' => $locale->text('Delivery Order created'), },
537     'marge_total'             => { 'text' => $locale->text('Ertrag'), },
538     'marge_percent'           => { 'text' => $locale->text('Ertrag prozentual'), },
539     'vcnumber'                => { 'text' => $form->{vc} eq 'customer' ? $locale->text('Customer Number') : $locale->text('Vendor Number'), },
540     'country'                 => { 'text' => $locale->text('Country'), },
541     'ustid'                   => { 'text' => $locale->text('USt-IdNr.'), },
542     'periodic_invoices'       => { 'text' => $locale->text('Per. Inv.'), },
543     'shippingpoint'           => { 'text' => $locale->text('Shipping Point'), },
544     'taxzone'                 => { 'text' => $locale->text('Steuersatz'), },
545     'insertdate'              => { 'text' => $locale->text('Insert Date'), },
546     'order_probability'       => { 'text' => $locale->text('Order probability'), },
547     'expected_billing_date'   => { 'text' => $locale->text('Exp. bill. date'), },
548     'expected_netamount'      => { 'text' => $locale->text('Exp. netamount'), },
549     'payment_terms'           => { 'text' => $locale->text('Payment Terms'), },
550     'intnotes'                => { 'text' => $locale->text('Internal Notes'), },
551     'order_status'            => { 'text' => $locale->text('Status'), },
552     'items'                   => { 'text' => $locale->text('Positions'), },
553     shiptoname                => { 'text' => $locale->text('Name (Shipping)'), },
554     shiptodepartment_1        => { 'text' => $locale->text('Department 1 (Shipping)'), },
555     shiptodepartment_2        => { 'text' => $locale->text('Department 2 (Shipping)'), },
556     shiptostreet              => { 'text' => $locale->text('Street (Shipping)'), },
557     shiptozipcode             => { 'text' => $locale->text('Zipcode (Shipping)'), },
558     shiptocity                => { 'text' => $locale->text('City (Shipping)'), },
559     shiptocountry             => { 'text' => $locale->text('Country (Shipping)'), },
560     vendor_confirmation_number => { 'text' => $locale->text('Vendor Confirmation Number'), },
561     %column_defs_cvars,
562   );
563
564   foreach my $name (qw(id transdate reqdate quonumber ordnumber cusordnumber
565                        name employee salesman shipvia transaction_description
566                        shippingpoint taxzone insertdate payment_terms department
567                        intnotes order_status vendor_confirmation_number)) {
568     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
569     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
570   }
571
572   my %column_alignment =
573     map { $_ => 'right' } qw(netamount tax amount curr
574                              remaining_amount remaining_netamount
575                              order_probability expected_billing_date
576                              expected_netamount);
577
578   $form->{"l_type"} = "Y";
579
580   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
581   $column_defs{ids}->{visible} = $allow_multiple_orders ? 'HTML' : 0;
582
583   $report->set_columns(%column_defs);
584   $report->set_column_order(@columns);
585   $report->set_export_options('orders', @hidden_variables, qw(sort sortdir));
586   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
587
588   CVar->add_custom_variables_to_report('module'         => 'CT',
589                                        'trans_id_field' => "$form->{vc}_id",
590                                        'configs'        => $ct_cvar_configs,
591                                        'column_defs'    => \%column_defs,
592                                        'data'           => $form->{OE});
593
594   my @options;
595
596   push @options, $locale->text('Customer')                . " : $form->{customer}"                        if $form->{customer};
597   push @options, $locale->text('Vendor')                  . " : $form->{vendor}"                          if $form->{vendor};
598   push @options, $locale->text('Contact Person')          . " : $form->{cp_name}"                         if $form->{cp_name};
599   push @options, $locale->text('Department')              . " : $form->{department}"                      if $form->{department};
600   push @options, $locale->text('Order Number')            . " : $form->{ordnumber}"                       if $form->{ordnumber};
601   push @options, $locale->text('Vendor Confirmation Number') . " : $form->{vendor_confirmation_number}"   if $form->{vendor_confirmation_number};
602   push @options, $locale->text('Customer Order Number')   . " : $form->{cusordnumber}"                    if $form->{cusordnumber};
603   push @options, $locale->text('Notes')                   . " : $form->{notes}"                           if $form->{notes};
604   push @options, $locale->text('Internal Notes')          . " : $form->{intnotes}"                        if $form->{intnotes};
605   push @options, $locale->text('Transaction description') . " : $form->{transaction_description}"         if $form->{transaction_description};
606   push @options, $locale->text('Quick Search')            . " : $form->{all}"                             if $form->{all};
607   push @options, $locale->text('Shipping Point')          . " : $form->{shippingpoint}"                   if $form->{shippingpoint};
608   push @options, $locale->text('Name (Shipping)')         . " : $form->{shiptoname}"
609                   if $form->{shiptoname};
610   push @options, $locale->text('Department 1 (Shipping)') . " : $form->{shiptodepartment_1}"
611                   if $form->{shiptodepartment_1};
612   push @options, $locale->text('Department 2 (Shipping)') . " : $form->{shiptodepartment_2}"
613                   if $form->{shiptodepartment_2};
614   push @options, $locale->text('Street (Shipping)')       . " : $form->{shiptostreet}"
615                   if $form->{shiptostreet};
616   push @options, $locale->text('Zipcode (Shipping)')      . " : $form->{shiptozipcode}"
617                   if $form->{shiptozipcode};
618   push @options, $locale->text('City (Shipping)')         . " : $form->{shiptocity}"
619                   if $form->{shiptocity};
620   push @options, $locale->text('Country (Shipping)')      . " : $form->{shiptocountry}"
621                   if $form->{shiptocountry};
622   push @options, $locale->text('Part Description')        . " : $form->{parts_description}"               if $form->{parts_description};
623   push @options, $locale->text('Part Number')             . " : $form->{parts_partnumber}"                if $form->{parts_partnumber};
624   push @options, $locale->text('Phone Notes')             . " : $form->{phone_notes}"                     if $form->{phone_notes};
625   push @options, $locale->text('Full Text')               . " : $form->{fulltext}"                        if $form->{fulltext};
626   if ( $form->{transdatefrom} or $form->{transdateto} ) {
627     push @options, $locale->text('Order Date');
628     push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1)     if $form->{transdatefrom};
629     push @options, $locale->text('Bis')  . " " . $locale->date(\%myconfig, $form->{transdateto},   1)     if $form->{transdateto};
630   };
631   if ( $form->{reqdatefrom} or $form->{reqdateto} ) {
632     push @options, $locale->text('Delivery Date');
633     push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{reqdatefrom}, 1)       if $form->{reqdatefrom};
634     push @options, $locale->text('Bis')  . " " . $locale->date(\%myconfig, $form->{reqdateto},   1)       if $form->{reqdateto};
635   };
636   if ( $form->{insertdatefrom} or $form->{insertdateto} ) {
637     push @options, $locale->text('Insert Date');
638     push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{insertdatefrom}, 1)    if $form->{insertdatefrom};
639     push @options, $locale->text('Bis')  . " " . $locale->date(\%myconfig, $form->{insertdateto},   1)    if $form->{insertdateto};
640   };
641   push @options, $locale->text('Open')                                                                    if $form->{open};
642   push @options, $locale->text('Closed')                                                                  if $form->{closed};
643   push @options, $locale->text('Delivery Order created')                                                               if $form->{delivered};
644   push @options, $locale->text('Not delivered')                                                           if $form->{notdelivered};
645   push @options, $locale->text('Periodic invoices active')                                                if $form->{periodic_invoices_active};
646   push @options, $locale->text('Reqdate not set or before current month')                                 if $form->{reqdate_unset_or_old};
647
648   if ($form->{business_id}) {
649     my $vc_type_label = $form->{vc} eq 'customer' ? $locale->text('Customer type') : $locale->text('Vendor type');
650     push @options, $vc_type_label . " : " . SL::DB::Business->new(id => $form->{business_id})->load->description;
651   }
652   if ($form->{taxzone_id} ne '') { # taxzone_id could be 0
653     push @options, $locale->text('Steuersatz') . " : " . SL::DB::TaxZone->new(id => $form->{taxzone_id})->load->description;
654   }
655
656   if ($form->{department_id}) {
657     push @options, $locale->text('Department') . " : " . SL::DB::Department->new(id => $form->{department_id})->load->description;
658   }
659
660   if (($form->{order_probability_value} || '') ne '') {
661     push @options, $::locale->text('Order probability') . ' ' . ($form->{order_probability_op} eq 'le' ? '<=' : '>=') . ' ' . $form->{order_probability_value} . '%';
662   }
663
664   if ($form->{expected_billing_date_from} or $form->{expected_billing_date_to}) {
665     push @options, $locale->text('Expected billing date');
666     push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{expected_billing_date_from}, 1) if $form->{expected_billing_date_from};
667     push @options, $locale->text('Bis')  . " " . $locale->date(\%myconfig, $form->{expected_billing_date_to},   1) if $form->{expected_billing_date_to};
668   }
669
670   if ($form->{order_status_id}) {
671     push @options, $locale->text('Status') . " : " . SL::DB::OrderStatus->new(id => $form->{order_status_id})->load->name;
672   }
673
674   $report->set_options('top_info_text'        => join("\n", @options),
675                        'raw_top_info_text'    => $form->parse_html_template('oe/orders_top'),
676                        'raw_bottom_info_text' => $form->parse_html_template('oe/orders_bottom'),
677                        'output_format'        => 'HTML',
678                        'title'                => $form->{title},
679                        'attachment_basename'  => $attachment_basename . strftime('_%Y%m%d', localtime time),
680     );
681   $report->set_options_from_form();
682   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
683
684   # add sort and escape callback, this one we use for the add sub
685   $form->{callback} = $href .= "&sort=$form->{sort}";
686
687   # escape callback for href
688   my $callback = $form->escape($href);
689
690   my @subtotal_columns = qw(netamount amount marge_total marge_percent remaining_amount remaining_netamount);
691   push @subtotal_columns, 'expected_netamount' if $form->{l_order_probability_expected_billing_date};
692
693   my %totals    = map { $_ => 0 } @subtotal_columns;
694   my %subtotals = map { $_ => 0 } @subtotal_columns;
695
696   my $idx = 1;
697
698   my $edit_url = $params{want_binary_pdf}
699                ? ''
700                : build_std_url('script=controller.pl', 'action=Order/edit', 'type');
701   foreach my $oe (@{ $form->{OE} }) {
702     map { $oe->{$_} *= $oe->{exchangerate} } @subtotal_columns;
703
704     $oe->{tax}               = $oe->{amount} - $oe->{netamount};
705     $oe->{open}              = $oe->{closed}            ? $locale->text('No')  : $locale->text('Yes');
706     $oe->{delivered}         = $oe->{delivered}         ? $locale->text('Yes') : $locale->text('No');
707     $oe->{periodic_invoices} = $oe->{periodic_invoices} ? $locale->text('On')  : $locale->text('Off');
708
709     map { $subtotals{$_} += $oe->{$_};
710           $totals{$_}    += $oe->{$_} } @subtotal_columns;
711
712     $subtotals{marge_percent} = $subtotals{netamount} ? ($subtotals{marge_total} * 100 / $subtotals{netamount}) : 0;
713     $totals{marge_percent}    = $totals{netamount}    ? ($totals{marge_total}    * 100 / $totals{netamount}   ) : 0;
714
715     map { $oe->{$_} = $form->format_amount(\%myconfig, $oe->{$_}, 2) } qw(netamount tax amount marge_total marge_percent remaining_amount remaining_netamount expected_netamount);
716
717     $oe->{order_probability} = ($oe->{order_probability} || 0) . '%';
718
719     my $row = { };
720
721     foreach my $column (@columns) {
722       next if ($column eq 'ids');
723       next if ($column eq 'items');
724       $row->{$column} = {
725         'data'  => $oe->{$column},
726         'align' => $column_alignment{$column},
727       };
728     }
729
730     $row->{ids} = {
731       'raw_data' =>   $cgi->hidden('-name' => "trans_id_${idx}", '-value' => $oe->{id})
732                     . $cgi->checkbox('-name' => "multi_id_${idx}", '-value' => 1, 'data-checkall' => 1, '-label' => ''),
733       'valign'   => 'center',
734       'align'    => 'center',
735     };
736
737     if (!$form->{hide_links} || $oe->{is_own}) {
738       $row->{$ordnumber}->{link} = $edit_url . "&id=" . E($oe->{id}) . "&callback=${callback}" unless $params{want_binary_pdf};
739     }
740
741     if ($form->{l_items}) {
742       my $items = SL::DB::Manager::OrderItem->get_all_sorted(where => [id => $oe->{item_ids}]);
743       $row->{items}->{raw_data}  = SL::Presenter::ItemsList::items_list($items)               if lc($report->{options}->{output_format}) eq 'html';
744       $row->{items}->{data}      = SL::Presenter::ItemsList::items_list($items, as_text => 1) if lc($report->{options}->{output_format}) ne 'html';
745     }
746
747     my $row_set = [ $row ];
748
749     if (($form->{l_subtotal} eq 'Y')
750         && (($idx == (scalar @{ $form->{OE} }))
751             || ($oe->{ $form->{sort} } ne $form->{OE}->[$idx]->{ $form->{sort} }))) {
752       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
753     }
754
755     $report->add_data($row_set);
756
757     $idx++;
758   }
759
760   $report->add_separator();
761   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
762   if ($params{want_binary_pdf}) {
763     $report->generate_with_headers();
764     return $report->generate_pdf_content(want_binary_pdf => 1);
765   }
766   setup_oe_orders_action_bar();
767   $report->generate_with_headers();
768
769   $main::lxdebug->leave_sub();
770 }
771
772 sub invoice {
773   $main::lxdebug->enter_sub();
774
775   my $form     = $main::form;
776   my %myconfig = %main::myconfig;
777   my $locale   = $main::locale;
778
779   check_oe_access();
780   check_oe_conversion_to_sales_invoice_allowed();
781   $form->mtime_ischanged('oe');
782
783   $main::auth->assert($form->{type} eq 'purchase_order' || $form->{type} eq 'request_quotation' ? 'vendor_invoice_edit' : 'invoice_edit');
784
785   $form->{old_salesman_id} = $form->{salesman_id};
786   $form->get_employee();
787
788
789   if ($form->{type} =~ /_order$|purchase_order_confirmation/) {
790
791     # these checks only apply if the items don't bring their own ordnumbers/transdates.
792     # The if clause ensures that by searching for empty ordnumber_#/transdate_# fields.
793     $form->isblank("ordnumber", $locale->text('Order Number missing!'))
794       if (+{ map { $form->{"ordnumber_$_"}, 1 } (1 .. $form->{rowcount} - 1) }->{''});
795     $form->isblank("transdate", $locale->text('Order Date missing!'))
796       if (+{ map { $form->{"transdate_$_"}, 1 } (1 .. $form->{rowcount} - 1) }->{''});
797
798     # also copy deliverydate from the order
799     $form->{deliverydate} = $form->{reqdate} if $form->{reqdate};
800     $form->{orddate}      = $form->{transdate};
801   } else {
802     $form->isblank("quonumber", $locale->text('Quotation Number missing!'));
803     $form->isblank("transdate", $locale->text('Quotation Date missing!'));
804     $form->{ordnumber}    = "";
805     $form->{quodate}      = $form->{transdate};
806   }
807
808   my $vc = $form->{vc};
809   if (($form->{"previous_${vc}_id"} || $form->{"${vc}_id"}) != $form->{"${vc}_id"}) {
810     $::form->{salesman_id} = SL::DB::Manager::Employee->current->id if exists $::form->{salesman_id};
811
812     IS->get_customer(\%myconfig, $form) if $vc eq 'customer';
813     IR->get_vendor(\%myconfig, $form)   if $vc eq 'vendor';
814
815     update();
816     $::dispatcher->end_request;
817   }
818
819   _oe_remove_delivered_or_billed_rows(id => $form->{id}, type => 'billed') if $form->{new_invoice_type} ne 'final_invoice';
820
821   $form->{cp_id} *= 1;
822
823   for my $i (1 .. $form->{rowcount}) {
824     for (qw(ship qty sellprice basefactor discount)) {
825       $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"}) if $form->{"${_}_${i}"};
826     }
827     $form->{"converted_from_orderitems_id_$i"} = delete $form->{"orderitems_id_$i"};
828   }
829
830   my ($buysell, $orddate, $exchangerate);
831   if (   $form->{type} =~ /_order/
832       && $form->{currency} ne $form->{defaultcurrency}) {
833
834     # check if we need a new exchangerate
835     $buysell = ($form->{type} eq 'sales_order') ? "buy" : "sell";
836
837     $orddate      = $form->current_date(\%myconfig);
838     $exchangerate = $form->check_exchangerate(\%myconfig, $form->{currency}, $orddate, $buysell);
839
840     if (!$exchangerate) {
841       $exchangerate = 0;
842     }
843   }
844
845   $form->{convert_from_oe_ids} = $form->{id};
846   $form->{transdate}           = $form->{invdate} = $form->current_date(\%myconfig);
847   $form->{duedate}             = $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
848   $form->{defaultcurrency}     = $form->get_default_currency(\%myconfig);
849
850   delete @{$form}{qw(id closed)};
851   $form->{rowcount}--;
852
853   my ($script);
854   if (   $form->{type} eq 'purchase_order'
855       || $form->{type} eq 'purchase_order_confirmation'
856       || $form->{type} eq 'request_quotation') {
857     $form->{title}  = $locale->text('Add Vendor Invoice');
858     $form->{script} = 'ir.pl';
859     $script         = "ir";
860     $buysell        = 'sell';
861     $form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_PURCHASE_INVOICE_POST())->token;
862   }
863
864   if (   $form->{type} eq 'sales_order'
865       || $form->{type} eq 'sales_quotation') {
866     $form->{title}  = ($form->{new_invoice_type} eq 'invoice_for_advance_payment') ? $locale->text('Add Invoice for Advance Payment')
867                     : ($form->{new_invoice_type} eq 'final_invoice')               ? $locale->text('Add Final Invoice')
868                     : $locale->text('Add Sales Invoice');
869     $form->{script} = 'is.pl';
870     $script         = "is";
871     $buysell        = 'buy';
872     $form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_SALES_INVOICE_POST())->token;
873   }
874
875   # bo creates the id, reset it
876   map { delete $form->{$_} } qw(id subject message cc bcc printed emailed queued);
877   $form->{ $form->{vc} } =~ s/--.*//g;
878   $form->{type} = $form->{new_invoice_type} || "invoice";
879
880   # locale messages
881   $main::locale = Locale->new("$myconfig{countrycode}", "$script");
882   $locale = $main::locale;
883
884   require "bin/mozilla/$form->{script}";
885
886   my $currency = $form->{currency};
887   &invoice_links;
888
889   $form->{currency}     = $currency;
890   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, $buysell);
891   $form->{exchangerate} = $form->{forex} || '';
892
893   $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
894
895   &prepare_invoice;
896
897   # format amounts
898   for my $i (1 .. $form->{rowcount}) {
899     $form->{"discount_$i"} =
900       $form->format_amount(\%myconfig, $form->{"discount_$i"});
901
902     my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
903     $dec           = length $dec;
904     my $decimalplaces = ($dec > 2) ? $dec : 2;
905
906     # copy delivery date from reqdate for order -> invoice conversion
907     $form->{"deliverydate_$i"} = $form->{"reqdate_$i"}
908       unless $form->{"deliverydate_$i"};
909
910     $form->{"sellprice_$i"} =
911       $form->format_amount(\%myconfig, $form->{"sellprice_$i"},
912                            $decimalplaces);
913
914     (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
915     $dec_qty = length $dec_qty;
916     $form->{"qty_$i"} =
917       $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
918   }
919
920   &display_form;
921
922   $main::lxdebug->leave_sub();
923 }
924
925 sub oe_prepare_xyz_from_order {
926   return if !$::form->{id};
927
928   my $order = SL::DB::Order->new(id => $::form->{id})->load;
929
930   if (exists $::form->{only_items}) {
931     my @wanted_indexes = sort { $a <=> $b } map { $_ - 1 } split(",", $::form->{only_items} // "");
932     my @items          = @{ $order->items_sorted };
933     @items             = @items[@wanted_indexes];
934     $order->items(\@items);
935   }
936
937   $order->flatten_to_form($::form, format_amounts => 1);
938   $::form->{taxincluded_changed_by_user} = 1;
939
940   # hack: add partsgroup for first row if it does not exists,
941   # because _remove_billed_or_delivered_rows and _remove_full_delivered_rows
942   # determine fields to handled by existing fields for the first row. If partsgroup
943   # is missing there, for deleted rows the partsgroup_field is not emptied and in
944   # update_delivery_order it will not considered an empty row ...
945   $::form->{partsgroup_1} = '' if !exists $::form->{partsgroup_1};
946
947   # fake last empty row
948   $::form->{rowcount}++;
949
950   _update_ship();
951 }
952
953 sub oe_invoice_from_order {
954   oe_prepare_xyz_from_order();
955   invoice();
956 }
957
958 sub report_for_todo_list {
959   $main::lxdebug->enter_sub();
960
961   my $form     = $main::form;
962
963   my $is_for_sales    = $::auth->assert($oe_view_access_map->{'sales_quotation'},   'may fail');
964   my $is_for_purchase = $::auth->assert($oe_view_access_map->{'request_quotation'}, 'may fail');
965   my $quotations      = OE->transactions_for_todo_list(sales => $is_for_sales, purchase => $is_for_purchase);
966   my $content;
967
968   if (@{ $quotations }) {
969     my $callback = build_std_url('action');
970     my $edit_url = build_std_url('script=controller.pl', 'action=Order/edit', 'callback=' . E($callback));
971
972     $content     = $form->parse_html_template('oe/report_for_todo_list', { 'QUOTATIONS' => $quotations,
973                                                                            'edit_url'   => $edit_url,
974                                                                            'callback'   => $callback });
975   }
976
977   $main::lxdebug->leave_sub();
978
979   return $content;
980 }
981
982 sub _remove_full_delivered_rows {
983
984   my @fields = map { s/_1$//; $_ } grep { m/_1$/ } keys %{ $::form };
985   my @new_rows;
986
987   my $removed_rows = 0;
988   my $row          = 0;
989   while ($row < $::form->{rowcount}) {
990     $row++;
991     next unless $::form->{"id_$row"};
992     my $base_factor = SL::DB::Manager::Unit->find_by(name => $::form->{"unit_$row"})->base_factor;
993     my $base_qty = $::form->parse_amount(\%::myconfig, $::form->{"qty_$row"}) *  $base_factor;
994     my $ship_qty = $::form->{"ship_$row"} *  $base_factor;
995     #$main::lxdebug->message(LXDebug->DEBUG2(),"shipto=".$ship_qty." qty=".$base_qty);
996
997     if (!$ship_qty || ($ship_qty < $base_qty)) {
998       $::form->{"qty_$row"}  = $::form->format_amount(\%::myconfig, ($base_qty - $ship_qty) / $base_factor );
999       $::form->{"ship_$row"} = 0;
1000       push @new_rows, { map { $_ => $::form->{"${_}_${row}"} } @fields };
1001
1002     } else {
1003       $removed_rows++;
1004     }
1005   }
1006   $::form->redo_rows(\@fields, \@new_rows, scalar(@new_rows), $::form->{rowcount});
1007   $::form->{rowcount} -= $removed_rows;
1008 }
1009
1010 sub _oe_remove_delivered_or_billed_rows {
1011   my (%params) = @_;
1012
1013   return if !$params{id} || !$params{type};
1014
1015   my $ord_quot = SL::DB::Order->new(id => $params{id})->load;
1016   return if !$ord_quot;
1017
1018   # Prüfung ob itemlinks existieren, falls ja dann neue Implementierung
1019
1020   if (  $params{type} eq 'delivered' ) {
1021       my $orderitem = SL::DB::Manager::OrderItem->get_first( where => [trans_id => $ord_quot->id]);
1022       if ( $orderitem) {
1023           my @links = $orderitem->linked_records(to => 'SL::DB::DeliveryOrderItem');
1024           if ( scalar(@links ) > 0 ) {
1025               #$main::lxdebug->message(LXDebug->DEBUG2(),"item recordlinks vorhanden");
1026               return _remove_full_delivered_rows();
1027           }
1028       }
1029   }
1030   my %args    = (
1031     direction => 'to',
1032     to        =>   $params{type} eq 'delivered' ? 'DeliveryOrder' : 'Invoice',
1033     via       => [ $params{type} eq 'delivered' ? qw(Order)       : qw(Order DeliveryOrder) ],
1034   );
1035
1036   my %handled_base_qtys;
1037   foreach my $record (@{ $ord_quot->linked_records(%args) }) {
1038     next if $ord_quot->is_sales != $record->is_sales;
1039     next if $record->type eq 'invoice' && $record->storno;
1040
1041     foreach my $item (@{ $record->items }) {
1042       my $key  = $item->parts_id;
1043       $key    .= ':' . $item->serialnumber if $item->serialnumber;
1044       $handled_base_qtys{$key} += $item->qty * $item->unit_obj->base_factor;
1045     }
1046   }
1047
1048   _remove_billed_or_delivered_rows(quantities => \%handled_base_qtys);
1049 }