예제 #1
0
 /**
  * {@inheritdoc}
  */
 public function create($orderId)
 {
     $order = $this->orderRepository->get($orderId);
     if ($order->getCustomerId()) {
         throw new AlreadyExistsException(__("This order already has associated customer account"));
     }
     $customerData = $this->objectCopyService->copyFieldsetToTarget('order_address', 'to_customer', $order->getBillingAddress(), []);
     $addresses = $order->getAddresses();
     foreach ($addresses as $address) {
         $addressData = $this->objectCopyService->copyFieldsetToTarget('order_address', 'to_customer_address', $address, []);
         /** @var \Magento\Customer\Api\Data\AddressInterface $customerAddress */
         $customerAddress = $this->addressFactory->create(['data' => $addressData]);
         if (is_string($address->getRegion())) {
             /** @var \Magento\Customer\Api\Data\RegionInterface $region */
             $region = $this->regionFactory->create();
             $region->setRegion($address->getRegion());
             $region->setRegionCode($address->getRegionCode());
             $region->setRegionId($address->getRegionId());
             $customerAddress->setRegion($region);
         }
         $customerData['addresses'][] = $customerAddress;
     }
     /** @var \Magento\Customer\Api\Data\CustomerInterface $customer */
     $customer = $this->customerFactory->create(['data' => $customerData]);
     $account = $this->accountManagement->createAccount($customer);
     $order->setCustomerId($account->getId());
     $this->orderRepository->save($order);
     return $account;
 }
예제 #2
0
 public function test_orderSave()
 {
     $req = new Request\OrderSave();
     /* load Magento order */
     $mageOrder = $this->_mageRepoSaleOrder->get(70);
     $req->setSaleOrder($mageOrder);
     $resp = $this->obj->orderSave($req);
     $this->assertNotNull($resp);
 }
 public function test_execute()
 {
     $event = new \Magento\Framework\Event\Observer();
     /* load Magento order */
     $mageOrder = $this->repoSaleOrder->get(1);
     $event->setOrder($mageOrder);
     $resp = $this->obj->execute($event);
     $this->assertNotNull($resp);
 }
 public function test_execute()
 {
     /** @var \Magento\Framework\Event\Observer $event */
     $event = $this->_manObj->create(\Magento\Framework\Event\Observer::class);
     /** @var \Magento\Sales\Api\Data\OrderInterface $order */
     $order = $this->_mageRepoSaleOrder->get(1);
     $event->setData(CheckoutSubmitAllAfter::DATA_ORDER, $order);
     $this->obj->execute($event);
 }
예제 #5
0
 /**
  * Select orders to be pushed into Odoo (in case of "on event" push was failed).
  */
 public function getOrdersToReplicate()
 {
     $result = [];
     $orders = $this->_repoSaleOrder->getIdsToSaveToOdoo();
     foreach ($orders as $data) {
         $id = $data[Cfg::E_SALE_ORDER_A_ENTITY_ID];
         $order = $this->_repoMageSalesOrder->get($id);
         $result[$id] = $order;
     }
     return $result;
 }
예제 #6
0
 /**
  * Check is it possible to reorder
  *
  * @param int $orderId
  * @return bool
  */
 public function canReorder($orderId)
 {
     $order = $this->orderRepository->get($orderId);
     if (!$this->isAllowed($order->getStore())) {
         return false;
     }
     if ($this->customerSession->isLoggedIn()) {
         return $order->canReorder();
     } else {
         return true;
     }
 }
예제 #7
0
 /**
  * Process relations for CreditMemo
  *
  * @param \Magento\Framework\Model\AbstractModel $object
  * @throws \Exception
  * @return void
  */
 public function processRelation(\Magento\Framework\Model\AbstractModel $object)
 {
     /** @var \Magento\Sales\Model\Order\Creditmemo $object */
     if ($object->getState() == \Magento\Sales\Model\Order\Creditmemo::STATE_REFUNDED) {
         $this->prepareOrder($object);
         if ($object->getInvoice()) {
             $this->prepareInvoice($object);
             $this->invoiceRepository->save($object->getInvoice());
         }
         $this->preparePayment($object);
         $this->orderRepository->save($object->getOrder());
     }
 }
예제 #8
0
 public function testUnHold()
 {
     $this->orderRepositoryMock->expects($this->once())->method('get')->with(123)->willReturn($this->orderMock);
     $this->orderRepositoryMock->expects($this->once())->method('save')->with($this->orderMock)->willReturn($this->orderMock);
     $this->orderMock->expects($this->once())->method('unHold')->willReturn($this->orderMock);
     $this->assertTrue($this->orderService->unHold(123));
 }
예제 #9
0
 /**
  * Initialize shipment model instance
  *
  * @return bool|\Magento\Sales\Model\Order\Shipment
  * @throws \Magento\Framework\Exception\LocalizedException
  */
 public function load()
 {
     $shipment = false;
     $orderId = $this->getOrderId();
     $shipmentId = $this->getShipmentId();
     if ($shipmentId) {
         $shipment = $this->shipmentRepository->get($shipmentId);
     } elseif ($orderId) {
         $order = $this->orderRepository->get($orderId);
         /**
          * Check order existing
          */
         if (!$order->getId()) {
             $this->messageManager->addError(__('The order no longer exists.'));
             return false;
         }
         /**
          * Check shipment is available to create separate from invoice
          */
         if ($order->getForcedShipmentWithInvoice()) {
             $this->messageManager->addError(__('Cannot do shipment for the order separately from invoice.'));
             return false;
         }
         /**
          * Check shipment create availability
          */
         if (!$order->canShip()) {
             $this->messageManager->addError(__('Cannot do shipment for the order.'));
             return false;
         }
         $shipment = $this->shipmentFactory->create($order, $this->getItemQtys(), $this->getTracking());
     }
     $this->registry->register('current_shipment', $shipment);
     return $shipment;
 }
예제 #10
0
 /**
  * Retrieve the order the shipment for created for
  *
  * @return \Magento\Sales\Model\Order
  */
 public function getOrder()
 {
     if (!$this->_order instanceof \Magento\Sales\Model\Order) {
         $this->_order = $this->orderRepository->get($this->getOrderId());
     }
     return $this->_order->setHistoryEntityName($this->entityType);
 }
예제 #11
0
    public function testEmailNoOrderId()
    {
        $this->request->expects($this->once())
            ->method('getParam')
            ->with('order_id')
            ->will($this->returnValue(null));
        $this->orderRepositoryMock->expects($this->once())
            ->method('get')
            ->with(null)
            ->willThrowException(
                new \Magento\Framework\Exception\NoSuchEntityException(__('Requested entity doesn\'t exist'))
            );
        $this->messageManager->expects($this->once())
            ->method('addError')
            ->with('This order no longer exists.');

        $this->actionFlag->expects($this->once())
            ->method('set')
            ->with('', 'no-dispatch', true)
            ->will($this->returnValue(true));
        $this->resultRedirect->expects($this->once())
            ->method('setPath')
            ->with('sales/*/')
            ->willReturnSelf();

        $this->assertInstanceOf(
            'Magento\Backend\Model\View\Result\Redirect',
            $this->orderEmail->executeInternal()
        );
    }
예제 #12
0
 /**
  * Tests what happens if the customer is logged in and the order does or does not allow reorders.
  *
  * @param bool $orderCanReorder
  * @return void
  * @dataProvider getOrderCanReorder
  */
 public function testCanReorderCustomerLoggedInAndOrderCanReorder($orderCanReorder)
 {
     $this->setupOrderMock(true);
     $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->will($this->returnValue(true));
     $this->orderMock->expects($this->once())->method('canReorder')->will($this->returnValue($orderCanReorder));
     $this->repositoryMock->expects($this->once())->method('get')->with(1)->willReturn($this->orderMock);
     $this->assertEquals($orderCanReorder, $this->helper->canReorder(1));
 }
 public function testExecuteUpdateAction()
 {
     $orderId = 30;
     $action = 'update';
     $this->requestMock->expects($this->at(0))->method('getParam')->with('order_id')->willReturn($orderId);
     $this->requestMock->expects($this->at(1))->method('getParam')->with('action')->willReturn($action);
     $this->resultRedirectFactoryMock->expects($this->once())->method('create')->willReturn($this->resultRedirectMock);
     $this->orderRepositoryMock->expects($this->once())->method('get')->with($orderId)->willReturn($this->orderMock);
     $this->orderMock->expects($this->any())->method('getEntityId')->willReturn($orderId);
     $this->orderMock->expects($this->any())->method('getPayment')->willReturn($this->paymentMock);
     $this->orderRepositoryMock->expects($this->once())->method('save')->with($this->orderMock)->willReturnSelf();
     $this->paymentMock->expects($this->once())->method('update');
     $this->paymentMock->expects($this->any())->method('getIsTransactionApproved')->willReturn(true);
     $this->messageManagerMock->expects($this->once())->method('addSuccess');
     $this->resultRedirectMock->expects($this->once())->method('setPath')->with('sales/order/view')->willReturnSelf();
     $result = $this->reviewPayment->execute();
     $this->assertEquals($this->resultRedirectMock, $result);
 }
예제 #14
0
 /**
  * Update status in Magento2 Order
  *
  * @return bool
  */
 private function updateOrderStatus()
 {
     $this->_library->setEnvironment();
     $this->_library->setCharset();
     $this->_library->setLog();
     $transaction = $this->getTransaction();
     $order = $this->_order->get($this->_helperData->getReferenceDecryptOrderID($transaction->getReference()));
     $status = $this->_helperData->getStatusFromKey($transaction->getStatus());
     if (!$this->compareStatus($status, $order->getStatus())) {
         $history = array('status' => $this->_history->setStatus($status), 'comment' => $this->_history->setComment('PagSeguro Notification'));
         $transactionCode = $transaction->getCode();
         $orderId = $order->getId();
         $order->setStatus($status);
         $order->setStatusHistories($history);
         $order->save();
         $this->updateSalesOrderGridTransactionCode($orderId, $transactionCode);
         $this->updatePagSeguroOrdersTransactionCode($orderId, $transactionCode);
     }
     return true;
 }
 /**
  * @param \Magento\Framework\Event\Observer $observer
  * @throws \Exception
  */
 public function execute(\Magento\Framework\Event\Observer $observer)
 {
     $orderIds = $observer->getEvent()->getData('order_ids');
     if (isset($orderIds[0])) {
         $order = $this->orderRepository->get($orderIds[0]);
         if (!$order->getCustomerId()) {
             $isEmailAvailable = $this->accountManagement->isEmailAvailable($order->getCustomerEmail());
             //$this->logger->addInfo(print_r($isEmailAvailable,true));
             if ($isEmailAvailable) {
                 try {
                     $this->orderCustomerService->create($orderIds[0]);
                 } catch (\Exception $e) {
                     $this->messageManager->addException($e, $e->getMessage());
                     throw $e;
                 }
                 $this->coreRegistry->register('automatic_account', true);
             }
         }
     }
 }
예제 #16
0
 /**
  * Validate order addresses
  *
  * @return bool
  */
 protected function validateAddresses()
 {
     $order = $this->orderRepository->get($this->checkoutSession->getLastOrderId());
     $addresses = $order->getAddresses();
     foreach ($addresses as $address) {
         $result = $this->addressValidator->validateForCustomer($address);
         if (is_array($result) && !empty($result)) {
             return false;
         }
     }
     return true;
 }
예제 #17
0
 /**
  * @param \Magento\Sales\Api\Data\OrderInterface $order
  * @return \Magento\Sales\Api\Data\OrderInterface
  * @throws \Exception
  */
 public function place(\Magento\Sales\Api\Data\OrderInterface $order)
 {
     // transaction will be here
     //begin transaction
     try {
         $order->place();
         return $this->orderRepository->save($order);
         //commit
     } catch (\Exception $e) {
         throw $e;
         //rollback;
     }
 }
예제 #18
0
 /**
  * @param int $orderId
  * @param string $message
  */
 protected function addOrderComment($orderId, $message)
 {
     /* @var $order \Magento\Sales\Api\Data\OrderInterface */
     $order = $this->orderRepository->get($orderId);
     // create comment
     $orderStatusHistory = $this->orderStatusHistoryFactory->create();
     $orderStatusHistory->setParentId($orderId);
     $orderStatusHistory->setComment($message);
     $orderStatusHistory->setIsCustomerNotified(false);
     $orderStatusHistory->setIsVisibleOnFront(false);
     $orderStatusHistory->setEntityName(Queue::ENTITY_TYPE_CODE_ORDER);
     $orderStatusHistory->setStatus($order->getStatus());
     // add comment to order
     $this->orderManagement->addComment($orderId, $orderStatusHistory);
 }
예제 #19
0
 /**
  * Initialize order model instance
  *
  * @return \Magento\Sales\Api\Data\OrderInterface|false
  */
 protected function _initOrder()
 {
     $id = $this->getRequest()->getParam('order_id');
     try {
         $order = $this->orderRepository->get($id);
     } catch (NoSuchEntityException $e) {
         $this->messageManager->addError(__('This order no longer exists.'));
         $this->_actionFlag->set('', self::FLAG_NO_DISPATCH, true);
         return false;
     } catch (InputException $e) {
         $this->messageManager->addError(__('This order no longer exists.'));
         $this->_actionFlag->set('', self::FLAG_NO_DISPATCH, true);
         return false;
     }
     $this->_coreRegistry->register('sales_order', $order);
     $this->_coreRegistry->register('current_order', $order);
     return $order;
 }
예제 #20
0
 protected function setupPaymentObjectForCapture($paymentId)
 {
     $order = $this->getMockBuilder('Magento\\Sales\\Api\\Data\\OrderInterface')->getMockForAbstractClass();
     $order->expects(static::any())->method('getTotalDue')->willReturn(self::TOTAL_AMOUNT);
     $this->orderRepository->expects(static::any())->method('get')->willReturn($order);
     $currencyMock = $this->getPriceCurrencyMock();
     $paymentObject = $this->objectManagerHelper->getObject('Magento\\Sales\\Model\\Order\\Payment', ['priceCurrency' => $currencyMock, 'orderRepository' => $this->orderRepository, 'data' => ['id' => $paymentId, 'cc_trans_id' => self::AUTH_TRAN_ID]]);
     return $paymentObject;
 }
예제 #21
0
 /**
  * Checks whether the capture is final
  *
  * @param string $orderId
  * @param string $amount
  * @return bool
  */
 protected function isFinalCapture($orderId, $amount)
 {
     if (!empty($orderId)) {
         $order = $this->orderRepository->get($orderId);
         return (double) $order->getTotalDue() === (double) $amount;
     }
     return false;
 }
예제 #22
0
 /**
  * Creates and returns a populated getTaxRequest for a invoice
  *
  * @param \Magento\Sales\Api\Data\InvoiceInterface|\Magento\Sales\Api\Data\CreditmemoInterface $object
  * @return GetTaxRequest
  */
 public function getGetTaxRequestForSalesObject($object)
 {
     $order = $this->orderRepository->get($object->getOrderId());
     $lines = [];
     $items = $object->getItems();
     $this->taxClassHelper->populateCorrectTaxClasses($items, $object->getStoreId());
     /** @var \Magento\Tax\Api\Data\QuoteDetailsItemInterface $item */
     foreach ($items as $item) {
         $line = $this->interactionLine->getLine($item);
         if ($line) {
             $lines[] = $line;
         }
     }
     $objectIsCreditMemo = $object instanceof \Magento\Sales\Api\Data\CreditmemoInterface;
     $credit = $objectIsCreditMemo;
     $line = $this->interactionLine->getShippingLine($object, $credit);
     if ($line) {
         $lines[] = $line;
     }
     $line = $this->interactionLine->getGiftWrapItemsLine($object, $credit);
     if ($line) {
         $lines[] = $line;
     }
     $line = $this->interactionLine->getGiftWrapOrderLine($object, $credit);
     if ($line) {
         $lines[] = $line;
     }
     $line = $this->interactionLine->getGiftWrapCardLine($object, $credit);
     if ($line) {
         $lines[] = $line;
     }
     if ($objectIsCreditMemo) {
         $line = $this->interactionLine->getPositiveAdjustmentLine($object);
         if ($line) {
             $lines[] = $line;
         }
         $line = $this->interactionLine->getNegativeAdjustmentLine($object);
         if ($line) {
             $lines[] = $line;
         }
     }
     /** @var \Magento\Sales\Api\Data\OrderAddressInterface $address */
     if (!$order->getIsVirtual()) {
         $address = $order->getShippingAddress();
     } else {
         $address = $order->getBillingAddress();
     }
     $avaTaxAddress = $this->address->getAddress($address);
     $store = $this->storeRepository->getById($object->getStoreId());
     $currentDate = $this->getFormattedDate($store, $object->getCreatedAt());
     $taxOverride = null;
     if ($object instanceof \Magento\Sales\Api\Data\InvoiceInterface) {
         $docType = DocumentType::$SalesInvoice;
         if ($this->areTimesDifferentDays($order->getCreatedAt(), $object->getCreatedAt(), $object->getStoreId())) {
             $taxCalculationDate = $this->getFormattedDate($store, $order->getCreatedAt());
             // Set the tax date for calculation
             $taxOverride = $this->taxOverrideFactory->create();
             $taxOverride->setTaxDate($taxCalculationDate);
             $taxOverride->setTaxOverrideType(\AvaTax\TaxOverrideType::$TaxDate);
             $taxOverride->setTaxAmount(0.0);
             $taxOverride->setReason(self::AVATAX_INVOICE_OVERRIDE_REASON);
         }
     } else {
         $docType = DocumentType::$ReturnInvoice;
         $invoice = $this->getInvoice($object->getInvoiceId());
         // If a Creditmemo was generated for an invoice, use the created_at value from the invoice
         if ($invoice) {
             $taxCalculationDate = $this->getFormattedDate($store, $invoice->getCreatedAt());
         } else {
             $taxCalculationDate = $this->getFormattedDate($store, $order->getCreatedAt());
         }
         // Set the tax date for calculation
         $taxOverride = $this->taxOverrideFactory->create();
         $taxOverride->setTaxDate($taxCalculationDate);
         $taxOverride->setTaxOverrideType(\AvaTax\TaxOverrideType::$TaxDate);
         $taxOverride->setTaxAmount(0.0);
         $taxOverride->setReason(self::AVATAX_CREDITMEMO_OVERRIDE_REASON);
     }
     $customer = $this->getCustomerById($order->getCustomerId());
     $customerUsageType = $customer ? $this->taxClassHelper->getAvataxTaxCodeForCustomer($customer) : null;
     $data = ['StoreId' => $store->getId(), 'Commit' => $this->config->getCommitSubmittedTransactions($store), 'TaxOverride' => $taxOverride, 'CurrencyCode' => $order->getOrderCurrencyCode(), 'CustomerCode' => $this->getCustomerCode($order), 'CustomerUsageType' => $customerUsageType, 'DestinationAddress' => $avaTaxAddress, 'DocCode' => $object->getIncrementId() . '123-' . rand(10000000, 90000000000), 'DocDate' => $currentDate, 'DocType' => $docType, 'ExchangeRate' => $this->getExchangeRate($store, $order->getBaseCurrencyCode(), $order->getOrderCurrencyCode()), 'ExchangeRateEffDate' => $currentDate, 'Lines' => $lines, 'DetailLevel' => DetailLevel::$Document, 'PaymentDate' => $currentDate, 'PurchaseOrderNo' => $object->getIncrementId()];
     $data = array_merge($this->retrieveGetTaxRequestFields($store, $address, $object), $data);
     try {
         $data = $this->metaDataObject->validateData($data);
     } catch (ValidationException $e) {
         $this->avaTaxLogger->error('Error validating data: ' . $e->getMessage(), ['data' => var_export($data, true)]);
     }
     /** @var $getTaxRequest GetTaxRequest */
     $getTaxRequest = $this->getTaxRequestFactory->create();
     $this->populateGetTaxRequest($data, $getTaxRequest);
     return $getTaxRequest;
 }
예제 #23
0
 /**
  * Set order instance for transaction depends on transaction behavior
  * If $order equals to true, method isn't loading new order instance.
  *
  * @param \Magento\Sales\Model\Order|null|boolean $order
  * @return $this
  * @throws \Magento\Framework\Exception\LocalizedException
  */
 public function setOrder($order = null)
 {
     if (null === $order || $order === true) {
         if ($this->getOrderId()) {
             $this->_order = $this->orderRepository->get($this->getOrderId());
         } else {
             $this->_order = false;
         }
     } elseif (!$this->getId() || $this->getOrderId() == $order->getId()) {
         $this->_order = $order;
     } else {
         throw new \Magento\Framework\Exception\LocalizedException(__('Set order for existing transactions not allowed'));
     }
     return $this;
 }
예제 #24
0
    protected function initOrder()
    {
        $orderIdParam = 111;

        $this->requestMock->expects($this->atLeastOnce())
            ->method('getParam')
            ->with('order_id')
            ->willReturn($orderIdParam);
        $this->orderRepositoryMock->expects($this->once())
            ->method('get')
            ->with($orderIdParam)
            ->willReturn($this->orderMock);
    }
예제 #25
0
 /**
  * Retrieve order model object
  *
  * @codeCoverageIgnore
  * @return Order
  */
 public function getOrder()
 {
     if (!$this->_order && $this->getParentId()) {
         $this->_order = $this->orderRepository->get($this->getParentId());
     }
     return $this->_order;
 }
예제 #26
0
 public function testPartialCaptureCloneTransaction()
 {
     $amount = self::AUTH_AMOUNT;
     $paymentId = 1005;
     $authTransactionId = 1006;
     $braintreeTransactionId = '4fg7hj';
     $paymentObject = $this->setupPaymentObjectForCapture($paymentId);
     $this->setupSalesTransaction($paymentId, 1);
     //one existing capture transaction
     $authTransactionMock = $this->getMockBuilder('\\Magento\\Sales\\Model\\Order\\Payment\\Transaction')->disableOriginalConstructor()->getMock();
     $authTransactionMock->expects($this->any())->method('getId')->willReturn($authTransactionId);
     $authTransactionMock->expects($this->once())->method('getAdditionalInformation')->with('token')->willReturn(self::CC_TOKEN);
     $authTransactionMock->expects($this->once())->method('getTxnId')->willReturn($braintreeTransactionId);
     $this->setupAuthTransaction($paymentId, $authTransactionMock);
     $this->braintreeCreditCardMock->expects($this->once())->method('find')->with(self::CC_TOKEN)->willThrowException(new \Exception('not found'));
     $braintreeResultData = ['transaction' => \Braintree_Transaction::factory(['id' => self::AUTH_TRAN_ID, 'creditCard' => ['token' => null, 'last4' => self::AUTH_CC_LAST_4, 'expirationMonth' => '10', 'expirationYear' => '2020', 'bin' => 'bin'], 'avsErrorResponseCode' => null, 'avsPostalCodeResponseCode' => 'M', 'avsStreetAddressResponseCode' => 'M', 'cvvResponseCode' => 'M', 'gatewayRejectionReason' => null, 'processorAuthorizationCode' => 'S02T5Q', 'processorResponseCode' => '1000', 'processorResponseText' => 'Approved'])];
     $resultSuccess = $this->setupSuccessResponse($braintreeResultData);
     $this->braintreeTransactionMock->expects($this->once())->method('cloneTransaction')->with($braintreeTransactionId, ['amount' => $amount, 'options' => ['submitForSettlement' => true]])->willReturn($resultSuccess);
     $paymentObject->setParentId('1');
     $order = $this->getMockBuilder('Magento\\Sales\\Api\\Data\\OrderInterface')->getMockForAbstractClass();
     $order->expects($this->once())->method('getTotalDue')->willReturn(10.02);
     $this->orderRepository->expects($this->once())->method('get')->willReturn($order);
     $this->model->capture($paymentObject, $amount);
     $this->assertEquals(PaymentMethod::STATUS_APPROVED, $paymentObject->getStatus());
     $this->assertEquals($amount, $paymentObject->getAmount());
     $this->assertEquals(self::AUTH_TRAN_ID, $paymentObject->getCcTransId());
     $this->assertEquals(self::AUTH_CC_LAST_4, $paymentObject->getCcLast4());
 }