0

How do I automatically duplicate an order? I use Drupal 8 and Drupal Commerce 2. I need to duplicate some orders, each week, automatically.

Orders have a Boolean field (recurrent_order). When the field is filled, the web site has to create the same order at the end of the week.

I have achieved this with rules and VBO on Drupal 7: On maintenance task, a rule finds an array filled by a VBO view, and a component duplicates the content.

In Drupal 8 there isn't VBO view access from a rule.

How can I achieve this? Regards,

0

Here is the code for duplicate order with a cron job:

function commande_et_paiement_cron() {
$query = \Drupal::entityQuery('node');
$query->condition('status', 1);
$query->condition('type', 'abonnement');
$query->condition('field_livraison', 3);//livraison le vendredi
$entity_ids = $query->execute();


foreach ($entity_ids as $entity_id) {
$abo = Node::load($entity_id);

//utilisateur
$user = $abo->get('field_utilisateur')->getValue()[0]['target_id'];
$utilisateur = \Drupal\user\Entity\User::load($user);


//profile
$entity_manager = \Drupal::entityTypeManager();
$profile = $entity_manager->getStorage('profile')->load($user);  


//abonnement
$nid= $abo->id();

//livraison
$date_livraison = new DateTime();
$date_livraison->modify('next friday');



//ligne de commande
$line_items = array();
$abo_array= $abo->get('field_abo_produits')->getValue();

foreach ($abo_array as $abo_item) {
    $ligne = $abo_item['target_id'];        
    //load produit abonnement      
    $item = \Drupal\commerce_order\Entity\OrderItem::load($ligne);
    $quantite = $item->getQuantity();
    $produit = $item->getPurchasedEntity();


    $order_item = \Drupal\commerce_order\Entity\OrderItem::create([
    'type' => 'default',
    'purchased_entity' => $produit,
    'quantity' => $quantite,
    //'unit_price' => $role_price,
    ]);

    $order_item->save();        
    array_push($line_items,$order_item);        
    }

//creation de la commande
$order = \Drupal\commerce_order\Entity\Order::create([
      'type' => 'default',
      'store_id' => 1,
      'checkout_flow' => 'boulangerie',      
      'uid' => $user,
      'billing_profile' =>$profile,
      'field_abonnement' => $nid,
      'placed' => time(),
      'field_date_livraison' =>$date_livraison->format('Y-m-d'),
      'order_items' =>$line_items,
      'state' => 'draft'
    //'completed' => time(),

    ]);        
    $order->save(); 
    $order->set('order_number', $order->id()); 
    $order->save(); 
    $order->set('state', 'complete');
    /*$comment = 'blabla';
     $logStorage = \Drupal::entityTypeManager()->getStorage('commerce_log');        
    $logStorage->generate($order, 'order_comment', ['comment' => $comment])->save();      */
    $order->save();
   }        
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.