/** * Calculate downline snapshots up to requested date (including). * * @param Request\Calc $request * * @return Response\Calc */ public function calc(Request\Calc $request) { $result = new Response\Calc(); $this->_logger->info("New downline snapshot calculation is requested."); $periodTo = $request->getDatestampTo(); $def = $this->_manTrans->begin(); try { /* get the last date with calculated snapshots */ $reqLast = new Request\GetLastDate(); /** @var $resp Response\GetLastDate */ $respLast = $this->getLastDate($reqLast); $lastDatestamp = $respLast->getLastDate(); /* get the snapshot on the last date */ $snapshot = $this->_repoSnap->getStateOnDate($lastDatestamp); /* get change log for the period */ $tsFrom = $this->_toolPeriod->getTimestampNextFrom($lastDatestamp); $tsTo = $this->_toolPeriod->getTimestampTo($periodTo); $changelog = $this->_repoChange->getChangesForPeriod($tsFrom, $tsTo); /* calculate snapshots for the period */ $updates = $this->_subCalc->calcSnapshots($snapshot, $changelog); /* save new snapshots in DB */ $this->_repoSnap->saveCalculatedUpdates($updates); $this->_manTrans->commit($def); $result->markSucceed(); } finally { $this->_manTrans->end($def); } return $result; }
public function test_main() { $this->_logger->debug('Story02 in PV Integration tests is started.'); $def = $this->_manTrans->begin(); try { $this->_createMageCustomers(); $this->_createDownlineCustomers(); $CUST_1 = $this->_mapCustomerMageIdByIndex[1]; $CUST_2 = $this->_mapCustomerMageIdByIndex[2]; $VAL_1 = 12.34; $VAL_2 = 6.54; $VAL_3 = 5.8; $VAL_4 = 6; $VAL_5 = 0.54; $this->_transferToCustomer($CUST_1, $VAL_1); $this->_checkAccount($CUST_1, $VAL_1); $this->_transferBetweenCustomers($CUST_1, $CUST_2, $VAL_2); $this->_checkAccount($CUST_1, $VAL_3); $this->_checkAccount($CUST_2, $VAL_2); $this->_transferFromCustomer($CUST_2, $VAL_4); $this->_checkAccount($CUST_2, $VAL_5); } finally { $this->_manTrans->rollback($def); } $this->_logger->debug('Story02 in PV Integration tests is completed, all transactions are rolled back.'); }
public function registerSale(Request\RegisterSale $req) { $result = new Response\RegisterSale(); $def = $this->_manTrans->begin(); try { /** @var \Praxigento\Warehouse\Service\QtyDistributor\Data\Item[] $reqItems */ $reqItems = $req->getSaleItems(); foreach ($reqItems as $item) { $itemId = $item->getItemId(); $prodId = $item->getProductId(); $stockId = $item->getStockId(); $qty = $item->getQuantity(); if ($qty > 0) { /* get list of lots for the product */ $lots = $this->_subRepo->getLotsByProductId($prodId, $stockId); $this->_subRepo->registerSaleItemQty($itemId, $qty, $lots); } } $this->_manTrans->commit($def); $result->markSucceed(); } finally { // transaction will be rolled back if commit is not done (otherwise - do nothing) $this->_manTrans->end($def); } return $result; }
/** * @param AggWarehouse $data * @return null|AggWarehouse */ public function create($data) { $result = null; $def = $this->_manTrans->begin(); try { $tbl = Cfg::ENTITY_MAGE_CATALOGINVENTORY_STOCK; $stockId = $data->getId(); if ($stockId) { /* lookup for catalog inventory stock by ID */ $stockData = $this->_repoGeneric->getEntityByPk($tbl, [Cfg::E_CATINV_STOCK_A_STOCK_ID => $stockId]); if (!$stockData) { /* create top level object (catalog inventory stock) */ $bind = [Cfg::E_CATINV_STOCK_A_WEBSITE_ID => $data->getWebsiteId(), Cfg::E_CATINV_STOCK_A_STOCK_NAME => $data->getCode()]; $stockId = $this->_repoGeneric->addEntity($tbl, $bind); } } else { /* create top level object (catalog inventory stock) */ $bind = [Cfg::E_CATINV_STOCK_A_WEBSITE_ID => $data->getWebsiteId(), Cfg::E_CATINV_STOCK_A_STOCK_NAME => $data->getCode()]; $stockId = $this->_repoGeneric->addEntity($tbl, $bind); } /* then create next level object (warehouse) */ $tbl = EntityWarehouse::ENTITY_NAME; $bind = [EntityWarehouse::ATTR_STOCK_REF => $stockId, EntityWarehouse::ATTR_CODE => $data->getCode(), EntityWarehouse::ATTR_CURRENCY => $data->getCurrency(), EntityWarehouse::ATTR_COUNTRY_CODE => $data->getCountryCode(), EntityWarehouse::ATTR_NOTE => $data->getNote()]; $this->_repoGeneric->addEntity($tbl, $bind); /* commit changes and compose result data object */ $this->_manTrans->commit($def); $result = $data; $result->setId($stockId); } finally { $this->_manTrans->end($def); } return $result; }
/** * Add new transaction and update current balances. * * @param Request\Add $request * * @return Response\Add */ public function add(Request\Add $request) { $result = new Response\Add(); $debitAccId = $request->getDebitAccId(); $creditAccId = $request->getCreditAccId(); $operationId = $request->getOperationId(); $dateApplied = $request->getDateApplied(); $value = $request->getValue(); $def = $this->_manTrans->begin(); try { /* get account type for debit account */ $debitAcc = $this->_repoAcc->getById($debitAccId); $debitAssetTypeId = $debitAcc->getAssetTypeId(); /* get account type for credit account */ $creditAcc = $this->_repoAcc->getById($creditAccId); $creditAssetTypeId = $creditAcc->getAssetTypeId(); /* asset types should be equals */ if (!is_null($debitAssetTypeId) && $debitAssetTypeId == $creditAssetTypeId) { /* add transaction */ $toAdd = [Transaction::ATTR_OPERATION_ID => $operationId, Transaction::ATTR_DEBIT_ACC_ID => $debitAccId, Transaction::ATTR_CREDIT_ACC_ID => $creditAccId, Transaction::ATTR_VALUE => $value, Transaction::ATTR_DATE_APPLIED => $dateApplied]; $idCreated = $this->_repoTrans->create($toAdd); $result->setTransactionId($idCreated); } else { throw new \Exception("Asset type (#{$debitAssetTypeId}) for debit account #{$debitAccId} is not equal to " . "asset type (#{$creditAssetTypeId}) for credit account {$creditAccId}."); } $this->_manTrans->commit($def); $result->markSucceed(); } finally { $this->_manTrans->end($def); } return $result; }
protected function execute(\Symfony\Component\Console\Input\InputInterface $input, \Symfony\Component\Console\Output\OutputInterface $output) { $def = $this->manTrans->begin(); try { foreach ($this->DEFAULT_DWNL_TREE as $custId => $parentId) { $first = 'User' . $custId; $last = 'Last'; $email = "customer_{$custId}@test.com"; if ($custId != $parentId) { /* save parent ID to registry */ $referralCode = $this->mapCustomerMageIdByIndex[$parentId]; $this->toolReferral->replaceCodeInRegistry($referralCode); } /** @var \Magento\Customer\Api\Data\CustomerInterface $customer */ $customer = $this->_manObj->create(\Magento\Customer\Api\Data\CustomerInterface::class); $customer->setEmail($email); $customer->setFirstname($first); $customer->setLastname($last); /* MOBI-427: change group ID for retail customers */ if (in_array($custId, $this->GROUP_RETAIL)) { $customer->setGroupId(BusinessCodesManager::M_CUST_GROUP_RETAIL); } /** @var \Magento\Customer\Api\Data\CustomerInterface $saved */ $saved = $this->repoCustomer->save($customer, $this->DEFAULT_PASSWORD_HASH); $this->mapCustomerMageIdByIndex[$custId] = $saved->getId(); $this->mapCustomerIndexByMageId[$saved->getId()] = $custId; } /* MOBI-426 : rename customer groups according to Generic App scheme. */ $this->subCustomerGroups->renameGroups(); $this->manTrans->commit($def); } finally { // transaction will be rolled back if commit is not done (otherwise - do nothing) $this->manTrans->end($def); } }
/** * Update stock item on the stock and distribute qty by lots. * * @param \Magento\CatalogInventory\Model\StockManagement $subject * @param \Closure $proceed * @param array $items * @param int $websiteId is not used * @throws \Magento\Framework\Exception\LocalizedException * @return null */ public function aroundRegisterProductsSale(\Magento\CatalogInventory\Model\StockManagement $subject, \Closure $proceed, array $items, $websiteId) { /* This code is moved from original 'registerProductsSale' method. */ /* replace websiteId by stockId */ $stockId = $this->_manStock->getCurrentStockId(); $def = $this->_manTrans->begin(); $lockedItems = $this->_resourceStock->lockProductsStock(array_keys($items), $stockId); $fullSaveItems = $registeredItems = []; foreach ($lockedItems as $lockedItemRecord) { $productId = $lockedItemRecord['product_id']; $orderedQty = $items[$productId]; /** @var \Magento\CatalogInventory\Api\Data\StockItemInterface $stockItem */ $stockItem = $this->_providerStockRegistry->getStockItem($productId, $stockId); $stockItemId = $stockItem->getItemId(); $canSubtractQty = $stockItemId && $this->_canSubtractQty($stockItem); if (!$canSubtractQty || !$this->_configStock->isQty($lockedItemRecord['type_id'])) { continue; } if (!$stockItem->hasAdminArea() && !$this->_stockState->checkQty($productId, $orderedQty)) { $this->_manTrans->rollback($def); throw new \Magento\Framework\Exception\LocalizedException(__('Not all of your products are available in the requested quantity.')); } if ($this->_canSubtractQty($stockItem)) { $stockItem->setQty($stockItem->getQty() - $orderedQty); } $registeredItems[$productId] = $orderedQty; if (!$this->_stockState->verifyStock($productId) || $this->_stockState->verifyNotification($productId)) { $fullSaveItems[] = $stockItem; } } $this->_resourceStock->correctItemsQty($registeredItems, $stockId, '-'); $this->_manTrans->commit($def); return $fullSaveItems; }
/** * Add operation with list of transactions and change account balances. * * @param Request\Add $req * * @return Response\Add */ public function add(Request\Add $req) { $result = new Response\Add(); $operationTypeId = $req->getOperationTypeId(); $operationTypeCode = $req->getOperationTypeCode(); $datePerformed = $req->getDatePerformed(); $note = $req->getOperationNote(); $transactions = $req->getTransactions(); $asRef = $req->getAsTransRef(); $customerId = $req->getCustomerId(); $adminUserId = $req->getAdminUserId(); $def = $this->_manTrans->begin(); try { /* add operation itself */ if (!$operationTypeId) { $operationTypeId = $this->_repoTypeOper->getIdByCode($operationTypeCode); } $bindToAdd = [EntityOperation::ATTR_TYPE_ID => $operationTypeId, EntityOperation::ATTR_DATE_PREFORMED => $datePerformed]; if (!is_null($note)) { $bindToAdd[EntityOperation::ATTR_NOTE] = $note; } $operId = $this->_repoOper->create($bindToAdd); if ($operId) { $transIds = $this->_subAdd->transactions($operId, $transactions, $datePerformed, $asRef); $result->setOperationId($operId); $result->setTransactionsIds($transIds); /* log customer link */ if ($customerId) { $log = new \Praxigento\Accounting\Data\Entity\Log\Change\Customer(); $log->setCustomerRef($customerId); $log->setOperationRef($operId); $this->_repoELogChangeCust->create($log); } /* log admin link */ if ($adminUserId) { $log = new \Praxigento\Accounting\Data\Entity\Log\Change\Admin(); $log->setUserRef($adminUserId); $log->setOperationRef($operId); $this->_repoELogChangeAdmin->create($log); } $this->_manTrans->commit($def); $result->markSucceed(); } } finally { $this->_manTrans->end($def); } return $result; }
public function getForPvBasedCalc(Request\GetForPvBasedCalc $request) { $result = new Response\GetForPvBasedCalc(); $calcTypeCode = $request->getCalcTypeCode(); $periodType = $request->getPeriodType() ?? ToolPeriod::TYPE_MONTH; $msg = "'Get latest period for PV based calc' operation is started in bonus base module " . "(type code: {$calcTypeCode}; period: {$periodType})."; $this->_logger->info($msg); /* get calculation type ID by type code */ $calcTypeId = $this->_repoTypeCalc->getIdByCode($calcTypeCode); $def = $this->_manTrans->begin(); try { $reqLatest = new Request\GetLatest(); $reqLatest->setCalcTypeId($calcTypeId); $latestPeriod = $this->getLatest($reqLatest); $periodData = $latestPeriod->getPeriodData(); if (is_null($periodData)) { $result = $this->_subPvBased->getNewPeriodDataForPv($result, $periodType, $calcTypeId); } else { $result->setPeriodData($periodData); $periodId = $periodData->getId(); $this->_logger->info("There is registered period #{$periodId} for '{$calcTypeCode}' calculation."); $calcData = $latestPeriod->getCalcData(); $result = $this->_subPvBased->checkExistingPeriod($result, $calcTypeCode, $calcTypeId, $periodType, $periodData, $calcData); } /* mark succeed if period data exists */ if ($result->getPeriodData() && $result->getCalcData()) { $this->_manTrans->commit($def); $result->markSucceed(); } } finally { $this->_manTrans->end($def); } $this->_logger->info("'Get latest period for PV based calc' operation is completed in bonus base module."); return $result; }
/** * @inheritdoc */ public function create(Request\ICreate $data) { /** @var Response\Create $result */ $result = $this->_manObj->create(Response\Create::class); $def = $this->_manTrans->begin(); try { $warehouse = $data->getWarehouse(); $bind = [EntityWarehouse::ATTR_STOCK_REF => $warehouse->getStockRef(), EntityWarehouse::ATTR_CODE => $warehouse->getCode(), EntityWarehouse::ATTR_CURRENCY => $warehouse->getCurrency(), EntityWarehouse::ATTR_NOTE => $warehouse->getNote()]; $id = $this->_repoEntityWarehouse->create($bind); $result->setId($id); $result->markSucceed(); $this->_manTrans->commit($def); } finally { $this->_manTrans->end($def); } return $result; }
public function changeParent(Request\ChangeParent $request) { $result = new Response\ChangeParent(); $customerId = $request->getCustomerId(); $newParentId = $request->getNewParentId(); $formatted = $request->getDate(); $this->_logger->info("Set up new parent #{$newParentId} for customer #{$customerId}."); $def = $this->_manTrans->begin(); try { /* get customer's downline data */ $data = $this->_repoCustomer->getById($customerId); $currParentId = $data->getParentId(); $currDepth = $data->getDepth(); $currPath = $data->getPath(); if ($currParentId == $newParentId) { /* nothing to change */ $result->markSucceed(); $this->_manTrans->commit($def); $this->_logger->notice("Current parent is the same as new one. Nothing to do."); } else { if ($customerId == $newParentId) { /* change to root node */ $newCustomerDepth = Cfg::INIT_DEPTH; $newCustomerPath = Cfg::DTPS; } else { /* get new parent data */ $newParentData = $this->_repoCustomer->getById($newParentId); $newParentDepth = $newParentData->getDepth(); $newParentPath = $newParentData->getPath(); $newCustomerDepth = $newParentDepth + 1; $newCustomerPath = $newParentPath . $newParentId . Cfg::DTPS; } /* update customer with new data */ $bind = [Customer::ATTR_PARENT_ID => $newParentId, Customer::ATTR_DEPTH => $newCustomerDepth, Customer::ATTR_PATH => $newCustomerPath]; $updateRows = $this->_repoCustomer->updateById($customerId, $bind); if ($updateRows == 1) { /* update depths and paths in downline */ $deltaDepth = $newCustomerDepth - $currDepth; $pathKey = $currPath . $customerId . Cfg::DTPS; $pathReplace = $newCustomerPath . $customerId . Cfg::DTPS; $rowsUpdated = $this->_repoCustomer->updateChildrenPath($pathKey, $pathReplace, $deltaDepth); $this->_logger->info("Total '{$rowsUpdated}' customers in downline were updated."); /* save new record into change log */ $bind = [Change::ATTR_CUSTOMER_ID => $customerId, Change::ATTR_PARENT_ID => $newParentId, Change::ATTR_DATE_CHANGED => $formatted]; $insertedId = $this->_repoChange->create($bind); if ($insertedId) { $this->_logger->info("New change log record #{$insertedId} is inserted (customer: {$customerId}, parent: {$newParentId}, date: {$formatted})."); $this->_manTrans->commit($def); $result->markSucceed(); $this->_logger->info("New parent #{$newParentId} for customer #{$customerId} is set."); } } } } finally { $this->_manTrans->end($def); } return $result; }
public function change(Request\Change $request) { $result = new Response\Reset(); $accCustId = $request->getCustomerAccountId(); $adminUserId = $request->getAdminUserId(); $value = $request->getChangeValue(); $def = $this->_manTrans->begin(); try { /* get account's asset type by ID */ $assetTypeId = $this->_repoAccount->getAssetTypeId($accCustId); /* get representative account id for given asset type */ $accRepresId = $this->_repoMod->getRepresentativeAccountId($assetTypeId); /* get operation type by code and date performed */ $operTypeId = $this->_repoTypeOper->getIdByCode(Cfg::CODE_TYPE_OPER_CHANGE_BALANCE); $dateNow = $this->_toolDate->getUtcNowForDb(); /* create operation */ $operation = new \Praxigento\Accounting\Data\Entity\Operation(); $operation->setTypeId($operTypeId); $operation->setDatePerformed($dateNow); $operId = $this->_repoOperation->create($operation); /* create transaction */ $trans = new \Praxigento\Accounting\Data\Entity\Transaction(); $trans->setOperationId($operId); $trans->setDateApplied($dateNow); if ($value > 0) { $trans->setDebitAccId($accRepresId); $trans->setCreditAccId($accCustId); } else { $trans->setDebitAccId($accCustId); $trans->setCreditAccId($accRepresId); } $trans->setValue(abs($value)); $this->_repoTransaction->create($trans); /* log details (operator name who performs the operation) */ $log = new ELogChangeAdmin(); $log->setOperationRef($operId); $log->setUserRef($adminUserId); $this->_repoLogChangeAdmin->create($log); $this->_manTrans->commit($def); $result->markSucceed(); } finally { $this->_manTrans->end($def); } return $result; }
protected function execute(\Symfony\Component\Console\Input\InputInterface $input, \Symfony\Component\Console\Output\OutputInterface $output) { $def = $this->_manTrans->begin(); try { $customers = $this->_subSaleOrder->getAllCustomers(); /** @var \Magento\Customer\Api\Data\CustomerInterface $customerData */ foreach ($customers as $customerData) { $mail = $customerData->getEmail(); if ($mail != \Praxigento\Accounting\Config::CUSTOMER_REPRESENTATIVE_EMAIL) { $this->_subSaleOrder->addOrder($customerData, $this->DATA_ORDER_ITEMS); } } $this->_manTrans->commit($def); } finally { // transaction will be rolled back if commit is not done (otherwise - do nothing) $this->_manTrans->end($def); } }
public function shipmentTrackingSave(\Praxigento\Odoo\Api\Data\SaleOrder\Shipment\Tracking $data) { $result = false; /* replicate all data in one transaction */ $def = $this->_manTrans->begin(); try { $orderIdMage = $data->getSaleOrderIdMage(); $trackNumber = $data->getData('shipment/trackingInfo/trackingNumber'); $shippingMethodCode = $data->getData('shipment/trackingInfo/shippingCode'); $this->_shipmentLoader->setOrderId($orderIdMage); /** @var \Magento\Sales\Model\Order\Shipment $shipment */ $shipment = $this->_shipmentLoader->load(); if ($shipment) { $carrierCode = $this->_manBusCodes->getMagCodeForCarrier($shippingMethodCode); $title = $this->_manBusCodes->getTitleForCarrier($shippingMethodCode); $track = $this->_manObj->create(\Magento\Sales\Model\Order\Shipment\Track::class); $track->setNumber($trackNumber); $track->setCarrierCode($carrierCode); $track->setTitle($title); $shipment->addTrack($track); $shipment->register(); $shipment->save(); $order = $shipment->getOrder(); $invoice = $this->_manInvoice->prepareInvoice($order); $invoice->register(); $invoice->save(); $order->save(); $this->_manTrans->commit($def); $result = true; } } catch (\Exception $e) { $msg = 'Product replication from Odoo is failed. Error: ' . $e->getMessage(); $this->_logger->emergency($msg); $traceStr = $e->getTraceAsString(); $this->_logger->emergency($traceStr); throw $e; } finally { // transaction will be rolled back if commit is not done (otherwise - do nothing) $this->_manTrans->end($def); } return $result; }
/** @inheritdoc */ public function create($data) { /** @var $result AggWarehouse */ $result = null; $def = $this->_manTrans->begin(); try { $wrhsData = $this->_repoWrhsAggWarehouse->create($data); /* create odoo related entries */ $bind = [EntityWarehouse::ATTR_MAGE_REF => $wrhsData->getId(), EntityWarehouse::ATTR_ODOO_REF => $data->getOdooId()]; $this->_repoEntityWarehouse->create($bind); $this->_manTrans->commit($def); /* compose result from warehouse module's data and odoo module's data */ $result = $this->_manObj->create(AggWarehouse::class); $result->setData($wrhsData); $result->setOdooId($data->getOdooId()); } finally { $this->_manTrans->end($def); } return $result; }
/** @inheritdoc */ public function create($data) { $def = $this->_manTrans->begin(); try { /* register lot in Warehouse module */ $bind = [EntityWrhsLot::ATTR_CODE => $data->getCode(), EntityWrhsLot::ATTR_EXP_DATE => $data->getExpDate()]; $id = $this->_repoWrhsEntityLot->create($bind); /* register lot in Odoo module */ $bind = [EntityLot::ATTR_MAGE_REF => $id, EntityLot::ATTR_ODOO_REF => $data->getOdooId()]; $this->_repoEntityLot->create($bind); $this->_manTrans->commit($def); /* compose result from warehouse module's data and odoo module's data */ $result = $this->_manObj->create(AggLot::class); $result->setData($data); $result->setId($id); } finally { $this->_manTrans->end($def); } return $result; }
protected function execute(\Symfony\Component\Console\Input\InputInterface $input, \Symfony\Component\Console\Output\OutputInterface $output) { /* load JSON data */ $fileData = file_get_contents(__DIR__ . '/data.json'); $jsonData = json_decode($fileData, true); $bundle = $this->_serviceInputProcessor->convertValue($jsonData['data'], \Praxigento\Odoo\Data\Odoo\Inventory::class); $def = $this->_manTrans->begin(); try { /* create products using replication */ /** @var ProductSaveRequest $req */ $req = $this->_manObj->create(ProductSaveRequest::class); $req->setProductBundle($bundle); $this->_callReplicate->productSave($req); /* enable categories after replication */ $this->_subCats->enableForAllStoreViews(); $this->_manTrans->commit($def); } finally { // transaction will be rolled back if commit is not done (otherwise - do nothing) $this->_manTrans->end($def); } }
public function saveQualificationParams($updates) { $def = $this->_manTrans->begin(); try { foreach ($updates as $item) { $this->_repoBasic->addEntity(Qualification::ENTITY_NAME, $item); } $this->_manTrans->commit($def); } finally { $this->_manTrans->end($def); } }
/** * Get lot(s) with the closest expiration date and write off quantity from this lot(s). Register write off * quantity in 'prxgt_wrhs_qty_sale'. * * @param int $saleItemId * @param double $total * @param array $lotsData */ public function registerSaleItemQty($saleItemId, $total, $lotsData) { $rest = $total; $def = $this->_manTrans->begin(); try { foreach ($lotsData as $lot) { $stockItemId = $lot[Alias::AS_STOCK_ITEM_ID]; $lotId = $lot[Alias::AS_LOT_ID]; $qty = $lot[Alias::AS_QTY]; $qtyPk = [Quantity::ATTR_STOCK_ITEM_REF => $stockItemId, Quantity::ATTR_LOT_REF => $lotId]; if ($rest < $qty) { /* lot's $qty is greater than $total (or $rest) */ $qtySaleData = [QtySale::ATTR_SALE_ITEM_REF => $saleItemId, QtySale::ATTR_LOT_REF => $lotId, QtySale::ATTR_TOTAL => $rest]; $this->_repoQtySale->create($qtySaleData); /* decrease lot's qty */ $qtyRest = $qty - $rest; $qtyUpdateData = [Quantity::ATTR_TOTAL => $qtyRest]; $this->_repoQty->updateById($qtyPk, $qtyUpdateData); break; } else { /* lot's $qty is less or equal to $total (or $rest) */ $qtySaleData = [QtySale::ATTR_SALE_ITEM_REF => $saleItemId, QtySale::ATTR_LOT_REF => $lotId, QtySale::ATTR_TOTAL => $qty]; $this->_repoQtySale->create($qtySaleData); /* delete zero quantity records from 'prxgt_wrhs_qty' */ $this->_repoQty->deleteById($qtyPk); /* decrease $rest of $total*/ $rest -= $qty; } if ($rest <= 0) { break; } } $this->_manTrans->commit($def); } finally { // transaction will be rolled back if commit is not done (otherwise - do nothing) $this->_manTrans->end($def); } }
/** * Save PV data on sale order save. * * @param Request\Save $req * * @return Response\Save */ public function save(Request\Save $req) { $result = new Response\Save(); $orderId = $req->getSaleOrderId(); $datePaid = $req->getSaleOrderDatePaid(); $items = $req->getOrderItems(); $this->_logger->info("Save PV attributes for sale order #{$orderId}."); $def = $this->_manTrans->begin(); try { /* for all items get PV data by warehouse */ $orderTotal = 0; foreach ($items as $item) { $prodId = $item->getProductId(); $stockId = $item->getStockId(); $itemId = $item->getItemId(); $pv = $this->_repoStockItem->getPvByProductAndStock($prodId, $stockId); $qty = $item->getQuantity(); $total = $pv * $qty; $eItem = new \Praxigento\Pv\Data\Entity\Sale\Item(); $eItem->setSaleItemId($itemId); $eItem->setSubtotal($total); $eItem->setDiscount(0); $eItem->setTotal($total); $this->_repoSaleItem->replace($eItem); $orderTotal += $total; } /* save order data */ $eOrder = new \Praxigento\Pv\Data\Entity\Sale(); $eOrder->setSaleId($orderId); $eOrder->setSubtotal($orderTotal); $eOrder->setDiscount(0); $eOrder->setTotal($orderTotal); $eOrder->setDatePaid($datePaid); $this->_repoSale->replace($eOrder); $this->_manTrans->commit($def); $result->markSucceed(); $this->_logger->info("PV attributes for sale order #{$orderId} are saved."); } finally { $this->_manTrans->end($def); } return $result; }
protected function execute(\Symfony\Component\Console\Input\InputInterface $input, \Symfony\Component\Console\Output\OutputInterface $output) { $def = $this->_manTrans->begin(); try { /* init data */ $this->_initRanks(); $this->_initGenerationPercents(); $this->_initLoyaltyCfg(); /* calc bonus */ $periodTo = $this->_calcPeriod(); $this->_calcTreeSnapshots($periodTo); $this->_calcTreeCompression(); $this->_calcQualification(); $this->_calcBonus(); $this->_manTrans->commit($def); } finally { // transaction will be rolled back if commit is not done (otherwise - do nothing) $this->_manTrans->end($def); } }
public function qualification(Request\Qualification $req) { $result = new Response\Qualification(); $datePerformed = $req->getDatePerformed(); $dateApplied = $req->getDateApplied(); $gvMaxLevels = $req->getGvMaxLevels(); $msg = "'Qualification for Global Sales' calculation is started. " . "Performed at: {$datePerformed}, applied at: {$dateApplied}."; $this->_logger->info($msg); $reqGetPeriod = new PeriodGetForDependentCalcRequest(); $calcTypeBase = Cfg::CODE_TYPE_CALC_COMPRESSION; $calcType = Cfg::CODE_TYPE_CALC_QUALIFICATION; $reqGetPeriod->setBaseCalcTypeCode($calcTypeBase); $reqGetPeriod->setDependentCalcTypeCode($calcType); $respGetPeriod = $this->_callBasePeriod->getForDependentCalc($reqGetPeriod); if ($respGetPeriod->isSucceed()) { $def = $this->_manTrans->begin(); try { $periodDataDepend = $respGetPeriod->getDependentPeriodData(); $calcDataDepend = $respGetPeriod->getDependentCalcData(); $calcIdDepend = $calcDataDepend->getId(); $calcDataBase = $respGetPeriod->getBaseCalcData(); $dsBegin = $periodDataDepend->getDstampBegin(); $dsEnd = $periodDataDepend->getDstampEnd(); $calcIdBase = $calcDataBase->getId(); $tree = $this->_repoBonusCompress->getTreeByCalcId($calcIdBase); $qualData = $this->_repoMod->getQualificationData($dsBegin, $dsEnd); $cfgParams = $this->_repoMod->getConfigParams(); $updates = $this->_subQualification->calcParams($tree, $qualData, $cfgParams, $gvMaxLevels); $this->_repoMod->saveQualificationParams($updates); $this->_repoBonusService->markCalcComplete($calcIdDepend); $this->_manTrans->commit($def); $result->setPeriodId($periodDataDepend->getId()); $result->setCalcId($calcIdDepend); $result->markSucceed(); } finally { $this->_manTrans->end($def); } } $this->_logger->info("'Qualification for Global Sales' calculation is complete."); return $result; }
public function valueTv(Request\ValueTv $request) { $result = new Response\ValueTv(); $this->_logger->info("'TV Value' calculation is started."); $reqGetPeriod = new PeriodGetForDependentCalcRequest(); $reqGetPeriod->setBaseCalcTypeCode(Cfg::CODE_TYPE_CALC_COMPRESS_FOR_PTC); $reqGetPeriod->setDependentCalcTypeCode(Cfg::CODE_TYPE_CALC_VALUE_TV); $respGetPeriod = $this->_callPeriod->getForDependentCalc($reqGetPeriod); if ($respGetPeriod->isSucceed()) { $def = $this->_manTrans->begin(); try { /* working vars */ $thisPeriodData = $respGetPeriod->getDependentPeriodData(); $thisPeriodId = $thisPeriodData[Period::ATTR_ID]; $thisCalcData = $respGetPeriod->getDependentCalcData(); $thisCalcId = $thisCalcData[Calculation::ATTR_ID]; $basePeriodData = $respGetPeriod->getBasePeriodData(); $baseDsBegin = $basePeriodData->getDstampBegin(); $baseDsEnd = $basePeriodData->getDstampEnd(); $baseCalcData = $respGetPeriod->getBaseCalcData(); $baseCalcId = $baseCalcData->getId(); /* calculation itself */ $this->_logger->info("Processing period #{$thisPeriodId} ({$baseDsBegin}-{$baseDsEnd})"); /* get compressed data by calculation ID */ $compressPtc = $this->_subDb->getCompressedPtcData($baseCalcId); $updates = $this->_subCalc->valueTv($compressPtc); $this->_subDb->saveValueTv($updates, $baseCalcId); $this->_subDb->markCalcComplete($thisCalcId); $this->_manTrans->commit($def); $result->markSucceed(); $result->setPeriodId($thisPeriodId); $result->setCalcId($thisCalcId); } finally { $this->_manTrans->end($def); } } $this->_logMemoryUsage(); $this->_logger->info("'TV Value' calculation is completed."); return $result; }
public function productsFromOdoo(Request\ProductsFromOdoo $req) { $result = new Response\ProductsFromOdoo(); /* replicate all data in one transaction */ $def = $this->_manTrans->begin(); try { $ids = $req->getOdooIds(); /** @var $inventory Inventory */ $inventory = $this->_repoOdooInventory->get($ids); $this->_doProductReplication($inventory); $this->_manTrans->commit($def); $result->markSucceed(); } catch (\Exception $e) { $msg = 'Product replication from Odoo is failed. Error: ' . $e->getMessage(); $this->_logger->emergency($msg); $traceStr = $e->getTraceAsString(); $this->_logger->emergency($traceStr); throw $e; } finally { // transaction will be rolled back if commit is not done (otherwise - do nothing) $this->_manTrans->end($def); } return $result; }
/** * @param Request\QualifyByUserData $req * * @return Response\QualifyByUserData */ public function qualifyByUserData(Request\QualifyByUserData $req) { $result = new Response\QualifyByUserData(); /* parse request */ $calcId = $req->getCalcId(); $treeFlat = $req->getFlatTree(); $qualifier = $req->getQualifier(); $skipExpand = (bool) $req->getSkipTreeExpand(); $this->_logger->info("'QualifyByUserData' operation is started."); $treeCompressed = []; if ($skipExpand) { $treeExpanded = $treeFlat; } else { $treeExpanded = $this->_toolDownlineTree->expandMinimal($treeFlat, ESnap::ATTR_PARENT_ID); } $mapById = $this->_mapById($treeExpanded); $mapDepth = $this->_mapByTreeDepthDesc($treeExpanded); $mapTeams = $this->_mapByTeams($treeExpanded); foreach ($mapDepth as $depth => $levelCustomers) { foreach ($levelCustomers as $custId) { $custData = $mapById[$custId]; $ref = isset($custData[Customer::ATTR_HUMAN_REF]) ? $custData[Customer::ATTR_HUMAN_REF] : ''; if ($qualifier->isQualified($custData)) { $this->_logger->info("Customer #{$custId} ({$ref}) is qualified and added to compressed tree."); $treeCompressed[$custId] = $custData; } else { $this->_logger->info("Customer #{$custId} ({$ref}) is not qualified."); if (isset($mapTeams[$custId])) { $this->_logger->info("Customer #{$custId} ({$ref}) has own front team."); /* Lookup for the closest qualified parent */ $path = $treeExpanded[$custId][ESnap::ATTR_PATH]; $parents = $this->_toolDownlineTree->getParentsFromPathReversed($path); $foundParentId = null; foreach ($parents as $newParentId) { $parentData = $mapById[$newParentId]; if ($qualifier->isQualified($parentData)) { $foundParentId = $newParentId; break; } } /* Change parent for all siblings of the unqualified customer. */ $team = $mapTeams[$custId]; foreach ($team as $memberId) { if (isset($treeCompressed[$memberId])) { /* if null set customer own id to indicate root node */ $treeCompressed[$memberId][ESnap::ATTR_PARENT_ID] = is_null($foundParentId) ? $memberId : $foundParentId; } } } } } } unset($mapCustomer); unset($mapPv); unset($mapDepth); unset($mapTeams); /* save compressed tree */ $def = $this->_manTrans->begin(); try { foreach ($treeCompressed as $custId => $item) { $data = [ECompress::ATTR_CALC_ID => $calcId, ECompress::ATTR_CUSTOMER_ID => $custId, ECompress::ATTR_PARENT_ID => $item[ESnap::ATTR_PARENT_ID]]; $this->_repoBonusCompress->create($data); } $this->_manTrans->commit($def); } finally { $this->_manTrans->end($def); } $result->markSucceed(); $this->_logger->info("'QualifyByUserData' operation is completed."); return $result; }