+
+# Make item objects from form values. For items already existing read from db.
+# Create a new item else. And assign attributes.
+sub _make_item {
+ my ($record, $attr) = @_;
+
+ my $item;
+ $item = first { $_->id == $attr->{id} } @{$record->items} if $attr->{id};
+
+ my $is_new = !$item;
+
+ # add_custom_variables adds cvars to an orderitem with no cvars for saving, but
+ # they cannot be retrieved via custom_variables until the order/orderitem is
+ # saved. Adding empty custom_variables to new orderitem here solves this problem.
+ $item ||= SL::DB::OrderItem->new(custom_variables => []);
+
+ $item->assign_attributes(%$attr);
+ $item->longdescription($item->part->notes) if $is_new && !defined $attr->{longdescription};
+
+ return $item;
+}
+
+sub _new_item {
+ my ($record, $attr) = @_;
+
+ my $item = SL::DB::OrderItem->new;
+ $item->assign_attributes(%$attr);
+
+ my $part = SL::DB::Part->new(id => $attr->{parts_id})->load;
+ my $price_source = SL::PriceSource->new(record_item => $item, record => $record);
+
+ $item->unit($part->unit) if !$item->unit;
+
+ my $price_src;
+ if ($item->sellprice) {
+ $price_src = $price_source->price_from_source("");
+ $price_src->price($item->sellprice);
+ } else {
+ $price_src = $price_source->best_price
+ ? $price_source->best_price
+ : $price_source->price_from_source("");
+ $price_src->price(0) if !$price_source->best_price;
+ }
+
+ my $discount_src;
+ if ($item->discount) {
+ $discount_src = $price_source->discount_from_source("");
+ $discount_src->discount($item->discount);
+ } else {
+ $discount_src = $price_source->best_discount
+ ? $price_source->best_discount
+ : $price_source->discount_from_source("");
+ $discount_src->discount(0) if !$price_source->best_discount;
+ }
+
+ my %new_attr;
+ $new_attr{part} = $part;
+ $new_attr{description} = $part->description if ! $item->description;
+ $new_attr{qty} = 1.0 if ! $item->qty;
+ $new_attr{price_factor_id} = $part->price_factor_id if ! $item->price_factor_id;
+ $new_attr{sellprice} = $price_src->price;
+ $new_attr{discount} = $discount_src->discount;
+ $new_attr{active_price_source} = $price_src;
+ $new_attr{active_discount_source} = $discount_src;
+
+ $new_attr{longdescription} = $part->notes if ! defined $attr->{longdescription};
+
+ # add_custom_variables adds cvars to an orderitem with no cvars for saving, but
+ # they cannot be retrieved via custom_variables until the order/orderitem is
+ # saved. Adding empty custom_variables to new orderitem here solves this problem.
+ $new_attr{custom_variables} = [];
+
+ $item->assign_attributes(%new_attr);
+
+ return $item;
+}
+