Create shipment programmatically

PHOTO EMBED

Mon Jan 10 2022 12:32:25 GMT+0000 (UTC)

Saved by @igor #drupal #php

// First we create order items.
    foreach ($lineItems as $lineItem) {
      $orderItem = OrderItem::create([
        'type' => 'default',
        'purchased_entity' => $lineItem['variation'],
        'quantity' => $lineItem['quantity'],
        'unit_price' => new Price($lineItem['price'], $currency),
        'overridden_unit_price' => TRUE,
      ]);
      $orderItem->save();
      $orderItems[] = $orderItem;
    }

// Than we create order.
    $order = Order::create([
      'type' => 'default',
      'mail' => $this->currentUser()->getEmail(),
      'uid' => $this->currentUser()->id(),
      'store_id' => 1,
      'order_items' => [$orderItems[0], $orderItems[1]],
      'placed' => \Drupal::time()->getCurrentTime(),
    ]);
    $order->save();

// Than we create shipment.
    if ($order->get('shipments')->count() == 0) {
      $first_shipment = Shipment::create([
        'type' => 'default',
        'order_id' => $order->id(),
        'title' => 'Shipment',
        'state' => 'ready'
      ]);
      $first_shipment->save();
    }

// After that we create data for shipment item and shipment items.
    foreach ($orderItems as $order_item) {
      $quantity = $order_item->getQuantity();
      $purchased_entity = $order_item->getPurchasedEntity();

      if ($purchased_entity->get('weight')->isEmpty()) {
        $weight = new Weight(1, WeightUnit::GRAM);
      } else {
        $weight_item = $purchased_entity->get('weight')->first();
        $weight = $weight_item->toMeasurement();
      }

      // Creating shipment item.
      $shipment_item = new ShipmentItem([
        'order_item_id' => $order_item ->id(),
        'title' => $purchased_entity->label(),
        'quantity' => $quantity,
        'weight' => $weight->multiply($quantity),
        'declared_value' => $order_item->getTotalPrice(),
      ]);
      $first_shipment->addItem($shipment_item);
    }

//Than we create shipping methods and add them to shipment.
    $shipping_method = ShippingMethod::create([
      'stores' => 1,
      'name' => $shipping_method_name,
      'plugin' => [
        'target_plugin_id' => 'flat_rate',
        'target_plugin_configuration' => [
          'rate_label' =>'Shipping GG',
          'rate_amount' => [
            'number' => $shipping_price, //TODO: Zameniti sa varijablom
            'currency_code' => $currency
          ]
        ],
      ],
      'status' => TRUE,
      'weight' => 0,
    ]);
    $shipping_method->save();
    // Adding newly created shipment method to shipment.
    $first_shipment->setShippingMethod($shipping_method);

// After that we add amount to shipment.
    $shipping_method_plugin = $shipping_method->getPlugin();
    $shipping_rates = $shipping_method_plugin->calculateRates($first_shipment);
    $shipping_rate = reset($shipping_rates);
    $shipping_service = $shipping_rate->getService()->getId();
    $amount = reset($shipping_rates)->getAmount();
    $first_shipment->setAmount($amount);
    $first_shipment->save();

    $order->set('shipments', [$first_shipment]);
    $order->save();

// And finally we create shipping and billing profile.
    $profile = Profile::create([
      'uid' => $order->getCustomerId(),
      'type' => 'customer',
    ]);
    $profile->address->given_name = $given_name;
    $profile->set('field_address_1', $name);
    $profile->address->family_name = $family_name;
    $profile->address->organization = $organization;
    $profile->set('field_company', $organization);
    $profile->address->country_code = $country_code;
    $profile->set('field_new_country', $country_code);
    $profile->address->locality = $locality;
    $profile->set('field_city', $locality);
    $profile->address->postal_code = $postal_code;
    $profile->set('field_zip_code', $postal_code);
    $profile->address->address_line1 = $address_line1;
    $profile->set('field_address_1', $address_line1);
    $profile->save();

    if(empty($order->getBillingProfile())) {
      $billing_profile = Profile::create([
        'type' => 'customer',
        'uid' => $order->getCustomerId(),
      ]);
      $billing_profile->save();
      $billing_profile->set('field_address_1', $billing_address);
      $billing_profile->set('field_city', $billing_city);
      $billing_profile->set('field_company', $billing_company);
      $billing_profile->set('field_zip_code', $billing_zip_code);
      $billing_profile->save();
      $order->setBillingProfile($billing_profile);
      $order->save();
    }

    //TODO: Add other data to profile.

    $first_shipment->setShippingProfile($profile);
    $first_shipment->setShippingService($shipping_service);
    $first_shipment->save();
    $order->set('shipments', $first_shipment);
    // Including tax into price.
    $priceWithTax = $order->getTotalPrice()->getNumber() + ($order->getTotalPrice()->getNumber() * $tax);
    $order->set('total_price', new Price($priceWithTax, $currency));
    $order->save();

content_copyCOPY