After struggling for 2 days on this, trying to understand what the problem was, studingstudying in deep also Magento core classes for module-sales, I found someone on Magento community who had similar problems with Magento API and developed a patch. The
The problem is from one year ago, but doesn't seem to have been addressed in subsequent versions of Magento, so I decided to adopt the same solution as the extension does, hence forcing the shipped quantity of order items to be equal to the quantity to ship, save order rows and then, save the order again. Well, it is just a patch and dunno if it is a general problem, but to me it has been the only way to make this work, and get finally the order in status of 'Complete'.
I added this after the first save of the order:
try {
$saveTransaction = $this->_transactionFactory->create();
$saveTransaction->addObject($shipment)
->addObject($shipment->getOrder())
->addObject($order);
$saveTransaction->save();
$itemsCheck = $order->getItemsCollection()->addAttributeToSelect('*')->load();
foreach ($itemsCheck as $item) {
if (! $item->getQtyToShip() || $item->getIsVirtual()) {
continue;
}
$item->setQtyShipped($item->getQtyToShip());
$item->save();
$Norder = $shipment->getOrder()->load( $shipment->getOrder()->getId() );
$Norder->save();
}
}
Hope it can be of help for someone else.