public function LocalStockUpdater::createTransaction in Commerce Stock 8
Create a stock transaction.
Parameters
\Drupal\commerce\PurchasableEntityInterface $entity: The purchasable entity.
int $location_id: The location ID.
string $zone: The zone.
float $quantity: Tbe quantity.
float $unit_cost: The unit cost.
string $currency_code: The currency code.
int $transaction_type_id: The transaction type ID.
array $metadata: Holds all the optional values those are:
- related_tid: related transaction.
- related_oid: related order.
- related_uid: related user.
- data: Serialized data array.
Return value
int Return the ID of the transaction.
Overrides StockUpdateInterface::createTransaction
File
- modules/
local_storage/ src/ LocalStockUpdater.php, line 92
Class
- LocalStockUpdater
- Class LocalStockUpdater.
Namespace
Drupal\commerce_stock_localCode
public function createTransaction(PurchasableEntityInterface $entity, $location_id, $zone, $quantity, $unit_cost, $currency_code, $transaction_type_id, array $metadata) {
// Get optional fields.
$related_tid = isset($metadata['related_tid']) ? $metadata['related_tid'] : NULL;
$related_oid = isset($metadata['related_oid']) ? $metadata['related_oid'] : NULL;
$related_uid = isset($metadata['related_uid']) ? $metadata['related_uid'] : NULL;
$data = isset($metadata['data']) ? $metadata['data'] : NULL;
// Create a record.
$field_values = [
'entity_id' => $entity
->id(),
'entity_type' => $entity
->getEntityTypeId(),
'qty' => $quantity,
'location_id' => $location_id,
'location_zone' => $zone,
'unit_cost' => $unit_cost,
'currency_code' => $currency_code,
'transaction_time' => time(),
'transaction_type_id' => $transaction_type_id,
'related_tid' => $related_tid,
'related_oid' => $related_oid,
'related_uid' => $related_uid,
'data' => serialize($data),
];
$event = new LocalStockTransactionEvent($this->entityTypeManager, $field_values);
$this->eventDispatcher
->dispatch(LocalStockTransactionEvents::LOCAL_STOCK_TRANSACTION_CREATE, $event);
$insert = $this->database
->insert('commerce_stock_transaction')
->fields(array_keys($field_values))
->values(array_values($field_values))
->execute();
$this->eventDispatcher
->dispatch(LocalStockTransactionEvents::LOCAL_STOCK_TRANSACTION_INSERT, $event);
// Find out if we have real-time aggregation turned on.
$transactions_aggregation_mode = \Drupal::config('commerce_stock_local.transactions')
->get('transactions_aggregation_mode');
if ($transactions_aggregation_mode == 'real-time') {
// Aggregate if we do.
/** @var \Drupal\commerce_stock_local\StockLocationStorage $locationStorage */
$locationStorage = \Drupal::entityTypeManager()
->getStorage('commerce_stock_location');
$locations = $locationStorage
->loadEnabled($entity);
foreach ($locations as $location) {
$this
->updateLocationStockLevel($location
->getId(), $entity);
}
}
return $insert;
}