From 25a0967365e74ecba2157cb18ca26cec9043491d Mon Sep 17 00:00:00 2001 From: mrnhi Date: Wed, 1 Apr 2020 13:08:08 +0700 Subject: [PATCH 01/70] initialize giaohangnhanh extension --- Console/GeneratingRegionData.php | 113 ++++++++ Model/Api/RequestProvider.php | 11 + Model/Api/Rest/Service.php | 267 ++++++++++++++++++ Model/Attribute/Source/District.php | 72 +++++ Model/Carrier/GHN.php | 243 ++++++++++++++++ Model/Carrier/GHN/Express.php | 13 + Model/Carrier/GHN/Standard.php | 13 + Model/Config.php | 178 ++++++++++++ Model/Config/Source/District.php | 67 +++++ Model/Config/Source/NoteCode.php | 20 ++ Model/Config/Source/PaymentType.php | 16 ++ Model/ConfigProvider.php | 59 ++++ Observer/SalesOrderAfterPlaceObserver.php | 47 +++ Observer/SalesOrderAfterSaveObserver.php | 46 +++ .../Block/Checkout/LayoutProcessor.php | 36 +++ .../Model/ShippingInformationManagement.php | 82 ++++++ Setup/InstallData.php | 61 ++++ etc/adminhtml/system.xml | 147 ++++++++++ etc/config.xml | 39 +++ etc/db_schema.xml | 24 ++ etc/di.xml | 19 ++ etc/events.xml | 9 + etc/extension_attributes.xml | 7 + etc/frontend/di.xml | 15 + etc/module.xml | 12 + registration.php | 9 + view/frontend/layout/checkout_index_index.xml | 40 +++ .../frontend/layout/customer_address_form.xml | 10 + view/frontend/requirejs-config.js | 7 + view/frontend/templates/address/edit.phtml | 216 ++++++++++++++ .../model/shipping-save-processor/default.js | 73 +++++ .../web/js/view/checkout/shipping/district.js | 36 +++ 32 files changed, 2007 insertions(+) create mode 100644 Console/GeneratingRegionData.php create mode 100644 Model/Api/RequestProvider.php create mode 100644 Model/Api/Rest/Service.php create mode 100644 Model/Attribute/Source/District.php create mode 100644 Model/Carrier/GHN.php create mode 100644 Model/Carrier/GHN/Express.php create mode 100644 Model/Carrier/GHN/Standard.php create mode 100644 Model/Config.php create mode 100644 Model/Config/Source/District.php create mode 100644 Model/Config/Source/NoteCode.php create mode 100644 Model/Config/Source/PaymentType.php create mode 100644 Model/ConfigProvider.php create mode 100644 Observer/SalesOrderAfterPlaceObserver.php create mode 100644 Observer/SalesOrderAfterSaveObserver.php create mode 100644 Plugin/Checkout/Block/Checkout/LayoutProcessor.php create mode 100644 Plugin/Checkout/Model/ShippingInformationManagement.php create mode 100644 Setup/InstallData.php create mode 100644 etc/adminhtml/system.xml create mode 100644 etc/config.xml create mode 100644 etc/db_schema.xml create mode 100755 etc/di.xml create mode 100644 etc/events.xml create mode 100644 etc/extension_attributes.xml create mode 100644 etc/frontend/di.xml create mode 100644 etc/module.xml create mode 100644 registration.php create mode 100644 view/frontend/layout/checkout_index_index.xml create mode 100755 view/frontend/layout/customer_address_form.xml create mode 100644 view/frontend/requirejs-config.js create mode 100644 view/frontend/templates/address/edit.phtml create mode 100644 view/frontend/web/js/model/shipping-save-processor/default.js create mode 100644 view/frontend/web/js/view/checkout/shipping/district.js diff --git a/Console/GeneratingRegionData.php b/Console/GeneratingRegionData.php new file mode 100644 index 0000000..38c50da --- /dev/null +++ b/Console/GeneratingRegionData.php @@ -0,0 +1,113 @@ +service = $service; + $this->resourceConnection = $resourceConnection; + $this->regionFactory = $regionFactory; + parent::__construct($name); + } + + protected function configure() + { + $this->setDescription('Generate region data.'); + parent::configure(); + } + + /** + * @param InputInterface $input + * @param OutputInterface $output + * @return int|void|null + * @throws NoSuchEntityException + */ + protected function execute(InputInterface $input, OutputInterface $output) + { + $response = $this->service->getDistrictList(); + if (true === $this->service->checkResponse($response)) { + $output->writeln('Generating data. Please wait...'); + $responseObject = $response['response_object']; + $data = empty($responseObject->data) ? null : $responseObject->data; + + if ($data && is_array($data)) { + foreach ($data as $item) { + $provinceId = $item->ProvinceID; + $region = $this->regionFactory->create() + ->loadByCode($provinceId, 'VN'); + + $this->insertData( + 'boolfly_giaohangnhanh_district', + [ + 'district_id' => $item->DistrictID, + 'province_id' => $provinceId, + 'district_name' => $item->DistrictName + ] + ); + + if (!$region->getId()) { + $this->insertData( + 'directory_country_region', + [ + 'country_id' => 'VN', + 'code' => $provinceId, + 'default_name' => $item->ProvinceName + ] + ); + } + } + $output->writeln('Generate data successfully.'); + } else { + $output->writeln('Generating data was interrupted. Please try again!'); + } + } + } + + /** + * @param string $tableName + * @param array $data + */ + private function insertData($tableName, $data) + { + $this->resourceConnection->getConnection()->insert( + $this->resourceConnection->getTableName($tableName), + $data + ); + } +} diff --git a/Model/Api/RequestProvider.php b/Model/Api/RequestProvider.php new file mode 100644 index 0000000..05bb56d --- /dev/null +++ b/Model/Api/RequestProvider.php @@ -0,0 +1,11 @@ +log = $log; + $this->config = $config; + $this->storeInformation = $storeInformation; + $this->storeManager = $storeManager; + $this->client = new Client(); + } + + /** + * @return array|ResponseInterface + * @throws NoSuchEntityException + * @throws Exception + */ + public function getDistrictList() + { + $data = [ + 'headers' => [ + 'Content-Type' => 'application/json' + ], + 'json' => ['token' => $this->config->getApiToken()] + ]; + + return $this->makeRequest($this->config->getGettingDistrictsUrl(), $data); + } + + /** + * @param $request + * @return array|ResponseInterface + * @throws NoSuchEntityException + * @throws Exception + */ + public function estimateShippingCost($request) + { + $data = [ + 'headers' => [ + 'Content-Type' => 'application/json' + ], + 'json' => $request + ]; + + return $this->makeRequest($this->config->getCalculatingFeeUrl(), $data); + } + + public function getAvailableServices($request) + { + $data = [ + 'headers' => [ + 'Content-Type' => 'application/json' + ], + 'json' => $request + ]; + + return $this->makeRequest('https://dev-online-gateway.ghn.vn/apiv3-api/api/v1/apiv3/FindAvailableServices', $data); + } + + /** + * @param Order $order + * @return array|ResponseInterface + * @throws NoSuchEntityException + * @throws Exception + */ + public function syncOrder(Order $order) + { + $config = $this->config; + $weightRate = $config->getWeightUnit() == 'kgs' ? Config::KGS_G : Config::LBS_G; + $store = $this->storeManager->getStore(); + $storeInfo = $this->storeInformation->getStoreInformationObject($store); + $storeFormattedAddress = $this->storeInformation->getFormattedAddress($store); + $storeDistrict = (int)$config->getStoreDistrict(); + $data = [ + 'headers' => [ + 'Content-Type' => 'application/json' + ], + 'json' => [ + 'token' => $config->getApiToken(), + 'PaymentTypeID' => $config->getPaymentType(), + 'FromDistrictID' => $storeDistrict, + 'ToDistrictID' => (int)$order->getDistrict(), + 'ClientContactName' => $storeInfo->getName(), + 'ClientContactPhone' => $storeInfo->getPhone(), + 'ClientAddress' => $storeFormattedAddress, + 'CustomerName' => $order->getCustomerName(), + 'CustomerPhone' => $order->getShippingAddress()->getTelephone(), + 'ShippingAddress' => $order->getShippingAddress()->getStreetLine(1), + 'NoteCode' => $config->getNoteCode(), + 'ServiceID' => $order->getShippingServiceId(), + 'Weight' => $order->getWeight() * $weightRate, + 'Length' => 10, + 'Width' => 10, + 'Height' => 10, + 'CoDAmount' => 0, + 'ReturnContactName' => $storeInfo->getName(), + 'ReturnContactPhone' => $storeInfo->getPhone(), + 'ReturnAddress' => $storeFormattedAddress, + 'ReturnDistrictID' => $storeDistrict, + 'ExternalReturnCode' => $storeInfo->getName() + ] + ]; + + return $this->makeRequest($config->getSynchronizingOrderUrl(), $data); + } + + /** + * @param $url + * @param array $options + * @param string $method + * @return array|ResponseInterface + * @throws Exception + */ + private function makeRequest($url, $options = [], $method = self::POST) + { + $response = [ + 'is_successful' => false + ]; + try { + /** @var ResponseInterface $response */ + $response = $this->client->$method($url, $options); + $response = $this->processResponse($response); + $response['is_successful'] = true; + } catch (BadResponseException $e) { + $this->log->error('Bad Response: ' . $e->getMessage()); + $this->log->error((string)$e->getRequest()->getBody()); + $response['response_status_code'] = $e->getCode(); + $response['response_status_message'] = $e->getMessage(); + $response = $this->processResponse($response); + if ($e->hasResponse()) { + $errorResponse = $e->getResponse(); + $this->log->error($errorResponse->getStatusCode() . ' ' . $errorResponse->getReasonPhrase()); + try { + $body = $this->processResponse($errorResponse); + } catch (Exception $e) { + $this->log->error('Exception: ' . $e->getMessage()); + $response['exception_code'] = $e->getCode(); + } + $response = array_merge($response, $body); + } + $response['exception_code'] = $e->getCode(); + } catch (Exception $e) { + $this->log->error('Exception: ' . $e->getMessage()); + $response['exception_code'] = $e->getCode(); + } + + return $response; + } + + /** + * Process the response and return an array + * + * @param ResponseInterface|array $response + * @return array + * @throws Exception + */ + private function processResponse($response) + { + if (is_array($response)) { + return $response; + } + + try { + $body = Json::decode((string)$response->getBody()); + } catch (Exception $e) { + $body = $e->getMessage(); + } + + $data['response_object'] = $body; + $data['response_status_code'] = $response->getStatusCode(); + $data['response_status_message'] = $response->getReasonPhrase(); + + return $data; + } + + /** + * Was the response successful? + * + * @param $response + * @return bool + */ + public function checkResponse($response) + { + if (!empty($response['response_status_code'])) { + $code = $response['response_status_code']; + return (200 <= $code && 300 > $code); + } + + return false; + } +} diff --git a/Model/Attribute/Source/District.php b/Model/Attribute/Source/District.php new file mode 100644 index 0000000..e965899 --- /dev/null +++ b/Model/Attribute/Source/District.php @@ -0,0 +1,72 @@ +storeInformation = $storeInformation; + $this->storeManager = $storeManager; + $this->config = $config; + } + + /** + * @inheritDoc + */ + public function getAllOptions() + { + $store = $this->storeManager->getStore(); + $storeInfo = $this->storeInformation->getStoreInformationObject($store); + $districts = $this->config->getDistricts(); + $data = []; + foreach ($districts as $district) { + if ($district['region_id'] == $storeInfo->getRegionId()) { + $data[] = [ + 'districtName' => $district['district_name'], + 'districtID' => $district['district_id'] + ]; + } + } + + if (!$this->_options) { + $this->_options[] = ['label' => __('Please select a district.'), 'value' => '']; + + if ($data) { + foreach ($data as $districtItem) { + $this->_options[] = ['label' => $districtItem['districtName'], 'value' => $districtItem['districtID']]; + } + } + } + return $this->_options; + } +} diff --git a/Model/Carrier/GHN.php b/Model/Carrier/GHN.php new file mode 100644 index 0000000..3ff4652 --- /dev/null +++ b/Model/Carrier/GHN.php @@ -0,0 +1,243 @@ +rateResultFactory = $rateResultFactory; + $this->rateMethodFactory = $rateMethodFactory; + $this->storeInformation = $storeInformation; + $this->storeManager = $storeManager; + $this->restService = $restService; + $this->addressInformation = $addressInformation; + $this->session = $session; + $this->customerAddressFactory = $customerAddressFactory; + $this->weightUnit = $scopeConfig->getValue( + Data::XML_PATH_WEIGHT_UNIT, + ScopeInterface::SCOPE_STORE + ); + } + + /** + * @inheritDoc + */ + public function collectRates(RateRequest $request) + { + if (!$this->getConfigFlag(Config::IS_ACTIVE)) { + return false; + } + + if ($shippingCost = $this->estimateShippingCost($request)) { + /** @var Result $result */ + $result = $this->rateResultFactory->create(); + /** @var Method $method */ + $method = $this->rateMethodFactory->create(); + $method->setCarrier($this->_code); + $method->setCarrierTitle($this->getConfigData(Config::TITLE)); + $method->setMethod($this->_code); + $method->setMethodTitle($this->getConfigData(Config::NAME)); + $method->setPrice($shippingCost); + $method->setCost($shippingCost); + + $result->append($method); + + return $result; + } + + return false; + } + + /** + * @inheritDoc + */ + public function getAllowedMethods() + { + return [$this->_code => $this->getConfigData(Config::NAME)]; + } + + /** + * @param RateRequest $request + * @return float|null + * @throws NoSuchEntityException + * @throws LocalizedException + */ + private function estimateShippingCost(RateRequest $request) + { + $rate = $this->weightUnit == 'kgs' ? Config::KGS_G : Config::LBS_G; + $data = json_decode(file_get_contents('php://input'), true); + $quote = $this->session->getQuote(); + $districtId = ''; + + if (!empty($data['address'])) { + $customAttributes = $data['address']['custom_attributes']; + } elseif (!empty($data['addressInformation'])) { + $customAttributes = $data['addressInformation']['shipping_address']['customAttributes']; + } else { + $customAttributes = null; + } + + if (null !== $customAttributes) { + foreach ($customAttributes as $attribute) { + if ($attribute['attribute_code'] == 'district') { + $districtId = $attribute['value']; + break; + } + } + } + + if (!$districtId) { + $customerAddress = $this->customerAddressFactory->create(); + + if (!empty($data['addressId'])) { + $districtId = $customerAddress->load($data['addressId'])->getDistrict(); + } elseif ($customerAddressId = $quote->getShippingAddress()->getCustomerAddressId()) { + $districtId = $customerAddress->load($customerAddressId)->getDistrict(); + } else { + $districtId = $quote->getDistrict(); + } + } + + $request = [ + 'token' => 'TokenStaging', + 'Weight' => $request->getPackageWeight() * $rate, + 'FromDistrictID' => 1443, + 'ToDistrictID' => (int)$districtId + ]; + $serviceId = $this->getAvailableServices($request); + $request['ServiceID'] = $serviceId; + $this->session->getQuote()->setData('shipping_service_id', $serviceId); + $response = $this->restService->estimateShippingCost($request)['response_object']; + + return !empty($response->data->CalculatedFee) ? $response->data->CalculatedFee : null; + } + + /** + * @param $request + * @return string + */ + private function getAvailableServices($request) + { + $response = $this->restService->getAvailableServices($request)['response_object']->data; + + if (is_array($response)) { + foreach ($response as $serviceItem) { + if (!empty($serviceItem->Name)) { + $serviceType = $this->_code == 'giaohangnhanh_express' ? 'Nhanh' : 'Chuẩn'; + + if ($serviceItem->Name == $serviceType) { + return $serviceItem->ServiceID; + } + } + } + } + + return ''; + } +} diff --git a/Model/Carrier/GHN/Express.php b/Model/Carrier/GHN/Express.php new file mode 100644 index 0000000..3b0771a --- /dev/null +++ b/Model/Carrier/GHN/Express.php @@ -0,0 +1,13 @@ +storeManager = $storeManager; + $this->scopeConfig = $scopeConfig; + $this->resourceConnection = $resourceConnection; + } + + /** + * @return mixed + * @throws NoSuchEntityException + */ + public function getApiToken() + { + return $this->getConfig(self::API_TOKEN); + } + + /** + * @return mixed + * @throws NoSuchEntityException + */ + public function getCalculatingFeeUrl() + { + return $this->getConfig(self::CALCULATING_FEE_URL); + } + + /** + * @return mixed + * @throws NoSuchEntityException + */ + public function getSynchronizingOrderUrl() + { + return $this->getConfig(self::SYNCHRONIZING_ORDER_URL); + } + + /** + * @return mixed + * @throws NoSuchEntityException + */ + public function getGettingDistrictsUrl() + { + return $this->getConfig(self::GETTING_DISTRICTS_URL); + } + + /** + * @return mixed + * @throws NoSuchEntityException + */ + public function getPaymentType() + { + return $this->getConfig(self::PAYMENT_TYPE); + } + + /** + * @return mixed + * @throws NoSuchEntityException + */ + public function getNoteCode() + { + return $this->getConfig(self::NOTE_CODE); + } + + /** + * @return mixed + * @throws NoSuchEntityException + */ + public function getStoreDistrict() + { + return $this->getConfig(self::DISTRICT); + } + + /** + * @return mixed + * @throws NoSuchEntityException + */ + public function getWeightUnit() + { + return $this->getConfig(Data::XML_PATH_WEIGHT_UNIT); + } + + /** + * @return array + */ + public function getDistricts() + { + $connection = $this->resourceConnection->getConnection(); + $sql = $connection->select()->from( + ['districtTable' => $this->resourceConnection->getTableName('boolfly_giaohangnhanh_district')] + )->joinLeft( + ['regionTable' => $this->resourceConnection->getTableName('directory_country_region')], + 'regionTable.code = districtTable.province_id', + 'regionTable.region_id as region_id' + ); + + return $connection->fetchAll($sql); + } + + /** + * @param $path + * @return mixed + * @throws NoSuchEntityException + */ + private function getConfig($path) + { + return $this->scopeConfig->getValue( + $path, + ScopeInterface::SCOPE_STORE, + $this->getStoreId() + ); + } + + /** + * @return int + * @throws NoSuchEntityException + */ + private function getStoreId() + { + if (!$this->storeId) { + $this->storeId = $this->storeManager->getStore()->getStoreId(); + } + return $this->storeId; + } +} diff --git a/Model/Config/Source/District.php b/Model/Config/Source/District.php new file mode 100644 index 0000000..1893cca --- /dev/null +++ b/Model/Config/Source/District.php @@ -0,0 +1,67 @@ +storeInformation = $storeInformation; + $this->storeManager = $storeManager; + $this->config = $config; + } + + /** + * @inheritDoc + */ + public function toOptionArray() + { + $store = $this->storeManager->getStore(); + $storeInfo = $this->storeInformation->getStoreInformationObject($store); + $districts = $this->config->getDistricts(); + $data = []; + foreach ($districts as $district) { + if ($district['region_id'] == $storeInfo->getRegionId()) { + $data[] = [ + 'label' => $district['district_name'], + 'value' => $district['district_id'] + ]; + } + } + + if ($data) { + return $data; + } + + return [['value' => '', 'label' => __('No district to select.')],]; + } +} diff --git a/Model/Config/Source/NoteCode.php b/Model/Config/Source/NoteCode.php new file mode 100644 index 0000000..f64eb9b --- /dev/null +++ b/Model/Config/Source/NoteCode.php @@ -0,0 +1,20 @@ + 'CHOTHUHANG', 'label' => __('Allow trying item')], + ['value' => 'CHOXEMHANGKHONGTHU', 'label' => __('Allow checking item, but not trying')], + ['value' => 'KHONGCHOXEMHANG', 'label' => __('Don\'t allow checking item')] + ]; + } +} diff --git a/Model/Config/Source/PaymentType.php b/Model/Config/Source/PaymentType.php new file mode 100644 index 0000000..5feb2e3 --- /dev/null +++ b/Model/Config/Source/PaymentType.php @@ -0,0 +1,16 @@ + 1, 'label' => __('Shop/Seller')], ['value' => 2, 'label' => __('Buyer/Consignee')]]; + } +} diff --git a/Model/ConfigProvider.php b/Model/ConfigProvider.php new file mode 100644 index 0000000..864f039 --- /dev/null +++ b/Model/ConfigProvider.php @@ -0,0 +1,59 @@ +resourceConnection = $resourceConnection; + } + + /** + * @inheritDoc + */ + public function getConfig() + { + $districts = $this->getDistricts(); + $data = []; + foreach ($districts as $district) { + $data[$district['region_id']][] = [ + 'districtName' => $district['district_name'], + 'districtID' => $district['district_id'], + 'provinceID' => $district['province_id'] + ]; + } + return [ + 'districts' => $data + ]; + } + + /** + * @return array + */ + private function getDistricts() + { + $connection = $this->resourceConnection->getConnection(); + $sql = $connection->select()->from( + ['districtTable' => $this->resourceConnection->getTableName('boolfly_giaohangnhanh_district')] + )->joinLeft( + ['regionTable' => $this->resourceConnection->getTableName('directory_country_region')], + 'regionTable.code = districtTable.province_id', + 'regionTable.region_id as region_id' + ); + + return $connection->fetchAll($sql); + } +} diff --git a/Observer/SalesOrderAfterPlaceObserver.php b/Observer/SalesOrderAfterPlaceObserver.php new file mode 100644 index 0000000..c8887b8 --- /dev/null +++ b/Observer/SalesOrderAfterPlaceObserver.php @@ -0,0 +1,47 @@ +service = $service; + $this->quoteRepository = $quoteRepository; + } + + /** + * @inheritDoc + */ + public function execute(Observer $observer) + { + /** @var \Magento\Sales\Model\Order $order */ + $order = $observer->getEvent()->getOrder(); + $quote = $this->quoteRepository->getActive($order->getQuoteId()); + $order->setDistrict($quote->getDistrict()); + $order->setShippingServiceId($quote->getShippingServiceId()); + $this->service->syncOrder($order); + } +} diff --git a/Observer/SalesOrderAfterSaveObserver.php b/Observer/SalesOrderAfterSaveObserver.php new file mode 100644 index 0000000..74e11f8 --- /dev/null +++ b/Observer/SalesOrderAfterSaveObserver.php @@ -0,0 +1,46 @@ +quoteRepository = $quoteRepository; + $this->customerAddressFactory = $customerAddressFactory; + } + + /** + * @inheritDoc + */ + public function execute(Observer $observer) + { + /** @var \Magento\Sales\Model\Order $order */ + $order = $observer->getEvent()->getOrder(); + $quote = $this->quoteRepository->getActive($order->getQuoteId()); + $address = $this->customerAddressFactory->create()->load($quote->getShippingAddress()->getCustomerAddressId()); + $address->setData('district', $quote->getDistrict())->save(); + } +} diff --git a/Plugin/Checkout/Block/Checkout/LayoutProcessor.php b/Plugin/Checkout/Block/Checkout/LayoutProcessor.php new file mode 100644 index 0000000..9ec7ad5 --- /dev/null +++ b/Plugin/Checkout/Block/Checkout/LayoutProcessor.php @@ -0,0 +1,36 @@ + 'Magento_Ui/js/form/element/select', + 'config' => [ + 'customScope' => 'shippingAddress.custom_attributes', + 'template' => 'ui/form/field', + 'elementTmpl' => 'ui/form/element/select', + 'id' => 'district', + ], + 'dataScope' => 'shippingAddress.custom_attributes.district', + 'label' => __('District'), + 'provider' => 'checkoutProvider', + 'visible' => true, + 'validation' => ['required-entry' => true], + 'sortOrder' => 255, + 'id' => 'district', + 'options' => [ + [ + 'value' => '', + 'label' => __('Please select a district.'), + ] + ] + ]; + + return $result; + } +} diff --git a/Plugin/Checkout/Model/ShippingInformationManagement.php b/Plugin/Checkout/Model/ShippingInformationManagement.php new file mode 100644 index 0000000..bb0202b --- /dev/null +++ b/Plugin/Checkout/Model/ShippingInformationManagement.php @@ -0,0 +1,82 @@ +quoteRepository = $quoteRepository; + $this->addressRepository = $addressRepository; + $this->customerAddressFactory = $customerAddressFactory; + } + + /** + * @param MageShippingInformationManagement $subject + * @param $result + * @param $cartId + * @param ShippingInformationInterface $addressInformation + * @return mixed + * @throws NoSuchEntityException + */ + public function afterSaveAddressInformation( + MageShippingInformationManagement $subject, + $result, + $cartId, + ShippingInformationInterface $addressInformation + ) { + /** @var \Magento\Quote\Model\Quote $quote */ + $quote = $this->quoteRepository->getActive($cartId); + $district = ''; + + if ($extensionAttributes = $addressInformation->getExtensionAttributes()) { + if ($extensionAttributes->getDistrict()) { + $district = $extensionAttributes->getDistrict(); + } + } + + if (!$district) { + $customerAddressId = $addressInformation->getShippingAddress()->getCustomerAddressId(); + $customerAddress = $this->customerAddressFactory->create()->load($customerAddressId); + if ($customerAddress->getId()) { + $district = $customerAddress->getDistrict(); + } + } + + $quote->setData('district', $district); + $this->quoteRepository->save($quote); + + return $result; + } +} diff --git a/Setup/InstallData.php b/Setup/InstallData.php new file mode 100644 index 0000000..b8ae24c --- /dev/null +++ b/Setup/InstallData.php @@ -0,0 +1,61 @@ +eavSetupFactory = $eavSetupFactory; + } + + /** + * {@inheritdoc} + * @SuppressWarnings(PHPMD.CyclomaticComplexity) + * @SuppressWarnings(PHPMD.ExcessiveMethodLength) + * @SuppressWarnings(PHPMD.NPathComplexity) + */ + public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context) + { + $eavSetup = $this->eavSetupFactory->create(); + $eavSetup->addAttribute( + 'customer_address', + 'district', + [ + 'group' => 'General', + 'type' => 'varchar', + 'label' => 'District', + 'input' => 'select', + 'source' => 'Boolfly\GiaoHangNhanh\Model\Attribute\Source\District', + 'required' => false, + 'sort_order' => 110, + 'global' => ScopedAttributeInterface::SCOPE_GLOBAL, + 'is_used_in_grid' => true, + 'is_visible_in_grid' => true, + 'is_filterable_in_grid' => false, + 'visible' => true, + 'is_html_allowed_on_front' => true, + 'visible_on_front' => true + ] + ); + } +} diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml new file mode 100644 index 0000000..8203bfb --- /dev/null +++ b/etc/adminhtml/system.xml @@ -0,0 +1,147 @@ + + + +
+ + + + + Magento\Config\Model\Config\Source\Yesno + + + + + + + validate-number validate-zero-or-greater + + + + Magento\Shipping\Model\Source\HandlingType + + + + validate-number validate-zero-or-greater + + + + + + + + + + shipping-applicable-country + Magento\Shipping\Model\Config\Source\Allspecificcountries + + + + Magento\Directory\Model\Config\Source\Country + 1 + + + + Magento\Config\Model\Config\Source\Yesno + shipping-skip-hide + + + + + + + + + + + + + + + + + + + Boolfly\GiaoHangNhanh\Model\Config\Source\PaymentType + + + + Boolfly\GiaoHangNhanh\Model\Config\Source\NoteCode + + + + Boolfly\GiaoHangNhanh\Model\Config\Source\District + + + + + + + Magento\Config\Model\Config\Source\Yesno + + + + + + + validate-number validate-zero-or-greater + + + + Magento\Shipping\Model\Source\HandlingType + + + + validate-number validate-zero-or-greater + + + + + + + + + + shipping-applicable-country + Magento\Shipping\Model\Config\Source\Allspecificcountries + + + + Magento\Directory\Model\Config\Source\Country + 1 + + + + Magento\Config\Model\Config\Source\Yesno + shipping-skip-hide + + + + + + + + + + + + + + + + + + + Boolfly\GiaoHangNhanh\Model\Config\Source\PaymentType + + + + Boolfly\GiaoHangNhanh\Model\Config\Source\NoteCode + + + + Boolfly\GiaoHangNhanh\Model\Config\Source\District + + +
+
+
\ No newline at end of file diff --git a/etc/config.xml b/etc/config.xml new file mode 100644 index 0000000..122dc1f --- /dev/null +++ b/etc/config.xml @@ -0,0 +1,39 @@ + + + + + + 1 + 0 + Boolfly\GiaoHangNhanh\Model\Carrier\GHN\Express + Giao Hang Nhanh(Express) + 10.00 + Giao Hang Nhanh + This shipping method is not available. To use this shipping method, please contact us. + F + TokenStaging + https://dev-online-gateway.ghn.vn/apiv3-api/api/v1/apiv3/CalculateFee + https://dev-online-gateway.ghn.vn/apiv3-api/api/v1/apiv3/CreateOrder + https://dev-online-gateway.ghn.vn/apiv3-api/api/v1/apiv3/GetDistricts + 2 + CHOXEMHANGKHONGTHU + + + 1 + 0 + Boolfly\GiaoHangNhanh\Model\Carrier\GHN\Standard + Giao Hang Nhanh(Standard) + 10.00 + Giao Hang Nhanh + This shipping method is not available. To use this shipping method, please contact us. + F + TokenStaging + https://dev-online-gateway.ghn.vn/apiv3-api/api/v1/apiv3/CalculateFee + https://dev-online-gateway.ghn.vn/apiv3-api/api/v1/apiv3/CreateOrder + https://dev-online-gateway.ghn.vn/apiv3-api/api/v1/apiv3/GetDistricts + 2 + CHOXEMHANGKHONGTHU + + + + \ No newline at end of file diff --git a/etc/db_schema.xml b/etc/db_schema.xml new file mode 100644 index 0000000..70abde8 --- /dev/null +++ b/etc/db_schema.xml @@ -0,0 +1,24 @@ + + + + + + + + + + +
+ + +
+ + + +
+ + +
+
\ No newline at end of file diff --git a/etc/di.xml b/etc/di.xml new file mode 100755 index 0000000..5a53e27 --- /dev/null +++ b/etc/di.xml @@ -0,0 +1,19 @@ + + + + + + region:generate + + + + + + Boolfly\GiaoHangNhanh\Console\GeneratingRegionData + + + + + + + diff --git a/etc/events.xml b/etc/events.xml new file mode 100644 index 0000000..4ffc598 --- /dev/null +++ b/etc/events.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/etc/extension_attributes.xml b/etc/extension_attributes.xml new file mode 100644 index 0000000..c143e8e --- /dev/null +++ b/etc/extension_attributes.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/etc/frontend/di.xml b/etc/frontend/di.xml new file mode 100644 index 0000000..760f73f --- /dev/null +++ b/etc/frontend/di.xml @@ -0,0 +1,15 @@ + + + + + + + Boolfly\GiaoHangNhanh\Model\ConfigProvider + + + + + + + + diff --git a/etc/module.xml b/etc/module.xml new file mode 100644 index 0000000..7d05a6b --- /dev/null +++ b/etc/module.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/registration.php b/registration.php new file mode 100644 index 0000000..56d94d7 --- /dev/null +++ b/registration.php @@ -0,0 +1,9 @@ + + + + + + + + + + + + + + + + + uiComponent + shippingAdditional + + + + Boolfly_GiaoHangNhanh/js/view/checkout/shipping/district + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/view/frontend/layout/customer_address_form.xml b/view/frontend/layout/customer_address_form.xml new file mode 100755 index 0000000..58b0778 --- /dev/null +++ b/view/frontend/layout/customer_address_form.xml @@ -0,0 +1,10 @@ + + + + + + Boolfly_GiaoHangNhanh::address/edit.phtml + + + + diff --git a/view/frontend/requirejs-config.js b/view/frontend/requirejs-config.js new file mode 100644 index 0000000..f6a0185 --- /dev/null +++ b/view/frontend/requirejs-config.js @@ -0,0 +1,7 @@ +var config = { + "map": { + "*": { + 'Magento_Checkout/js/model/shipping-save-processor/default': 'Boolfly_GiaoHangNhanh/js/model/shipping-save-processor/default' + } + } +}; diff --git a/view/frontend/templates/address/edit.phtml b/view/frontend/templates/address/edit.phtml new file mode 100644 index 0000000..8a78957 --- /dev/null +++ b/view/frontend/templates/address/edit.phtml @@ -0,0 +1,216 @@ + +getLayout()->createBlock('Magento\Customer\Block\Widget\Company') ?> +getLayout()->createBlock('Magento\Customer\Block\Widget\Telephone') ?> +getLayout()->createBlock('Magento\Customer\Block\Widget\Fax') ?> +
+
+ escapeHtml(__('Contact Information')) ?>
+ getBlockHtml('formkey') ?> + + + getNameBlockHtml() ?> + + isEnabled()): ?> + setCompany($block->getAddress()->getCompany())->toHtml() ?> + + + isEnabled()): ?> + setTelephone($block->getAddress()->getTelephone())->toHtml() ?> + + + isEnabled()): ?> + setFax($block->getAddress()->getFax())->toHtml() ?> + + +
+
+ escapeHtml(__('Address')) ?>
+ helper('Magento\Customer\Helper\Address')->getAttributeValidationClass('street'); ?> +
+ +
+ +
+ + helper('Magento\Customer\Helper\Address')->getStreetLines(); $_i < $_n; $_i++): ?> +
+ +
+ +
+
+ +
+
+
+ + helper('Magento\Customer\Helper\Address')->isVatAttributeVisible()) : ?> +
+ +
+ +
+
+ +
+ +
+ +
+
+
+ +
+ + getConfig('general/region/display_all') ? ' disabled="disabled"' : '' ?>/> +
+
+ +
+ +
+ +
+
+ +
+ +
+ + +
+
+
+ +
+ getCountryHtmlSelect() ?> +
+
+ + isDefaultBilling()): ?> +
+ escapeHtml(__("It's a default billing address.")) ?> +
+ canSetAsDefaultBilling()): ?> +
+ + +
+ + + + + isDefaultShipping()): ?> +
+ escapeHtml(__("It's a default shipping address.")) ?> +
+ canSetAsDefaultShipping()): ?> +
+ + +
+ + + +
+
+
+ +
+ +
+
+ diff --git a/view/frontend/web/js/model/shipping-save-processor/default.js b/view/frontend/web/js/model/shipping-save-processor/default.js new file mode 100644 index 0000000..23ae7eb --- /dev/null +++ b/view/frontend/web/js/model/shipping-save-processor/default.js @@ -0,0 +1,73 @@ +define( + [ + 'jquery', + 'ko', + 'Magento_Checkout/js/model/quote', + 'Magento_Checkout/js/model/resource-url-manager', + 'mage/storage', + 'Magento_Checkout/js/model/payment-service', + 'Magento_Checkout/js/model/payment/method-converter', + 'Magento_Checkout/js/model/error-processor', + 'Magento_Checkout/js/model/full-screen-loader', + 'Magento_Checkout/js/action/select-billing-address' + ], + function ( + $, + ko, + quote, + resourceUrlManager, + storage, + paymentService, + methodConverter, + errorProcessor, + fullScreenLoader, + selectBillingAddressAction + ) { + 'use strict'; + + return { + saveShippingInformation: function () { + var payload; + + if (!quote.billingAddress()) { + selectBillingAddressAction(quote.shippingAddress()); + } + + var district = $('[name="custom_attributes[district]"]').val(); + + payload = { + addressInformation: { + shipping_address: quote.shippingAddress(), + billing_address: quote.billingAddress(), + shipping_method_code: quote.shippingMethod().method_code, + shipping_carrier_code: quote.shippingMethod().carrier_code, + extension_attributes:{ + district: district + + } + } + }; + + fullScreenLoader.startLoader(); + + return storage.post( + resourceUrlManager.getUrlForSetShippingInformation(quote), + JSON.stringify(payload) + ).done( + function (response) { + quote.setTotals(response.totals); + paymentService.setPaymentMethods(methodConverter(response.payment_methods)); + fullScreenLoader.stopLoader(); + } + ).fail( + function (response) { + errorProcessor.process(response); + fullScreenLoader.stopLoader(); + } + ); + } + }; + } +); + + diff --git a/view/frontend/web/js/view/checkout/shipping/district.js b/view/frontend/web/js/view/checkout/shipping/district.js new file mode 100644 index 0000000..a6f388e --- /dev/null +++ b/view/frontend/web/js/view/checkout/shipping/district.js @@ -0,0 +1,36 @@ +define([ + 'jquery', + 'Magento_Ui/js/form/element/select', + 'Magento_Checkout/js/model/quote', + 'Magento_Checkout/js/model/shipping-rate-registry' +], function ($, Component, quote, rateRegistry) { + 'use strict'; + + let checkoutConfigDistricts = window.checkoutConfig.districts; + return Component.extend({ + defaults: { + imports: { + update: 'checkout.steps.shipping-step.shippingAddress.shipping-address-fieldset.region_id:value' + } + }, + + initialize: function () { + this._super(); + let district = $('[name="custom_attributes[district]"]'); + district.on('change', function() { + alert('kkk'); + }); + + }, + + update: function (value) { + let district = $('[name="custom_attributes[district]"]'); + let districtList = checkoutConfigDistricts[parseInt(value)]; + district.children('option:not(:first)').remove(); + + $.each(districtList, function (k, v) { + district.append(new Option(v.districtName, v.districtID)); + }); + } + }); +}); \ No newline at end of file From 5a74c713cc94e1de375648eb455b62c36f0e2d76 Mon Sep 17 00:00:00 2001 From: mrnhi Date: Wed, 1 Apr 2020 17:25:59 +0700 Subject: [PATCH 02/70] remove unrelated methods --- Model/Api/Rest/Service.php | 127 +------------------------------------ 1 file changed, 2 insertions(+), 125 deletions(-) diff --git a/Model/Api/Rest/Service.php b/Model/Api/Rest/Service.php index 8a0acf0..5650cbc 100644 --- a/Model/Api/Rest/Service.php +++ b/Model/Api/Rest/Service.php @@ -2,14 +2,9 @@ namespace Boolfly\GiaoHangNhanh\Model\Api\Rest; -use Boolfly\GiaoHangNhanh\Model\Config; use Exception; use GuzzleHttp\Client; use GuzzleHttp\Exception\BadResponseException; -use Magento\Framework\Exception\NoSuchEntityException; -use Magento\Sales\Model\Order; -use Magento\Store\Model\Information; -use Magento\Store\Model\StoreManagerInterface; use Psr\Http\Message\ResponseInterface; use Psr\Log\LoggerInterface; use Zend\Json\Json; @@ -51,135 +46,17 @@ class Service */ private $log; - /** - * @var Config - */ - private $config; - - /** - * @var Information - */ - private $storeInformation; - - /** - * @var StoreManagerInterface - */ - private $storeManager; - /** * Service constructor. * @param LoggerInterface $log - * @param Config $config - * @param Information $storeInformation - * @param StoreManagerInterface $storeManager */ public function __construct( - LoggerInterface $log, - Config $config, - Information $storeInformation, - StoreManagerInterface $storeManager + LoggerInterface $log ) { $this->log = $log; - $this->config = $config; - $this->storeInformation = $storeInformation; - $this->storeManager = $storeManager; $this->client = new Client(); } - /** - * @return array|ResponseInterface - * @throws NoSuchEntityException - * @throws Exception - */ - public function getDistrictList() - { - $data = [ - 'headers' => [ - 'Content-Type' => 'application/json' - ], - 'json' => ['token' => $this->config->getApiToken()] - ]; - - return $this->makeRequest($this->config->getGettingDistrictsUrl(), $data); - } - - /** - * @param $request - * @return array|ResponseInterface - * @throws NoSuchEntityException - * @throws Exception - */ - public function estimateShippingCost($request) - { - $data = [ - 'headers' => [ - 'Content-Type' => 'application/json' - ], - 'json' => $request - ]; - - return $this->makeRequest($this->config->getCalculatingFeeUrl(), $data); - } - - public function getAvailableServices($request) - { - $data = [ - 'headers' => [ - 'Content-Type' => 'application/json' - ], - 'json' => $request - ]; - - return $this->makeRequest('https://dev-online-gateway.ghn.vn/apiv3-api/api/v1/apiv3/FindAvailableServices', $data); - } - - /** - * @param Order $order - * @return array|ResponseInterface - * @throws NoSuchEntityException - * @throws Exception - */ - public function syncOrder(Order $order) - { - $config = $this->config; - $weightRate = $config->getWeightUnit() == 'kgs' ? Config::KGS_G : Config::LBS_G; - $store = $this->storeManager->getStore(); - $storeInfo = $this->storeInformation->getStoreInformationObject($store); - $storeFormattedAddress = $this->storeInformation->getFormattedAddress($store); - $storeDistrict = (int)$config->getStoreDistrict(); - $data = [ - 'headers' => [ - 'Content-Type' => 'application/json' - ], - 'json' => [ - 'token' => $config->getApiToken(), - 'PaymentTypeID' => $config->getPaymentType(), - 'FromDistrictID' => $storeDistrict, - 'ToDistrictID' => (int)$order->getDistrict(), - 'ClientContactName' => $storeInfo->getName(), - 'ClientContactPhone' => $storeInfo->getPhone(), - 'ClientAddress' => $storeFormattedAddress, - 'CustomerName' => $order->getCustomerName(), - 'CustomerPhone' => $order->getShippingAddress()->getTelephone(), - 'ShippingAddress' => $order->getShippingAddress()->getStreetLine(1), - 'NoteCode' => $config->getNoteCode(), - 'ServiceID' => $order->getShippingServiceId(), - 'Weight' => $order->getWeight() * $weightRate, - 'Length' => 10, - 'Width' => 10, - 'Height' => 10, - 'CoDAmount' => 0, - 'ReturnContactName' => $storeInfo->getName(), - 'ReturnContactPhone' => $storeInfo->getPhone(), - 'ReturnAddress' => $storeFormattedAddress, - 'ReturnDistrictID' => $storeDistrict, - 'ExternalReturnCode' => $storeInfo->getName() - ] - ]; - - return $this->makeRequest($config->getSynchronizingOrderUrl(), $data); - } - /** * @param $url * @param array $options @@ -187,7 +64,7 @@ public function syncOrder(Order $order) * @return array|ResponseInterface * @throws Exception */ - private function makeRequest($url, $options = [], $method = self::POST) + public function makeRequest($url, $options = [], $method = self::POST) { $response = [ 'is_successful' => false From 54ac3ca500a988dfcf2d3be076a897e3e800916e Mon Sep 17 00:00:00 2001 From: mrnhi Date: Wed, 1 Apr 2020 17:32:39 +0700 Subject: [PATCH 03/70] add 3 classes which contact directly to giaohangnhanh apis --- Model/DistrictProvider.php | 51 +++++++++++++++++++ Model/Order/Processor.php | 101 +++++++++++++++++++++++++++++++++++++ Model/ServiceProvider.php | 50 ++++++++++++++++++ 3 files changed, 202 insertions(+) create mode 100644 Model/DistrictProvider.php create mode 100644 Model/Order/Processor.php create mode 100644 Model/ServiceProvider.php diff --git a/Model/DistrictProvider.php b/Model/DistrictProvider.php new file mode 100644 index 0000000..9539e92 --- /dev/null +++ b/Model/DistrictProvider.php @@ -0,0 +1,51 @@ +apiService = $apiService; + $this->config = $config; + } + + /** + * @return array|ResponseInterface + * @throws NoSuchEntityException + * @throws Exception + */ + public function getDistrictList() + { + $data = [ + 'headers' => [ + 'Content-Type' => 'application/json' + ], + 'json' => ['token' => $this->config->getApiToken()] + ]; + + return $this->apiService->makeRequest($this->config->getGettingDistrictsUrl(), $data); + } +} diff --git a/Model/Order/Processor.php b/Model/Order/Processor.php new file mode 100644 index 0000000..eaa2ac6 --- /dev/null +++ b/Model/Order/Processor.php @@ -0,0 +1,101 @@ +config = $config; + $this->apiService = $apiService; + $this->storeManager = $storeManager; + $this->storeInformation = $storeInformation; + } + + /** + * @param Order $order + * @return array|ResponseInterface + * @throws NoSuchEntityException + * @throws Exception + */ + public function syncOrder(Order $order) + { + $config = $this->config; + $weightRate = $config->getWeightUnit() == 'kgs' ? Config::KGS_G : Config::LBS_G; + $store = $this->storeManager->getStore(); + $storeInfo = $this->storeInformation->getStoreInformationObject($store); + $storeFormattedAddress = $this->storeInformation->getFormattedAddress($store); + $storeDistrict = (int)$config->getStoreDistrict(); + $data = [ + 'headers' => [ + 'Content-Type' => 'application/json' + ], + 'json' => [ + 'token' => $config->getApiToken(), + 'PaymentTypeID' => $config->getPaymentType(), + 'FromDistrictID' => $storeDistrict, + 'ToDistrictID' => (int)$order->getDistrict(), + 'ClientContactName' => $storeInfo->getName(), + 'ClientContactPhone' => $storeInfo->getPhone(), + 'ClientAddress' => $storeFormattedAddress, + 'CustomerName' => $order->getCustomerName(), + 'CustomerPhone' => $order->getShippingAddress()->getTelephone(), + 'ShippingAddress' => $order->getShippingAddress()->getStreetLine(1), + 'NoteCode' => $config->getNoteCode(), + 'ServiceID' => $order->getShippingServiceId(), + 'Weight' => $order->getWeight() * $weightRate, + 'Length' => 10, + 'Width' => 10, + 'Height' => 10, + 'CoDAmount' => 0, + 'ReturnContactName' => $storeInfo->getName(), + 'ReturnContactPhone' => $storeInfo->getPhone(), + 'ReturnAddress' => $storeFormattedAddress, + 'ReturnDistrictID' => $storeDistrict, + 'ExternalReturnCode' => $storeInfo->getName() + ] + ]; + + return $this->apiService->makeRequest($config->getSynchronizingOrderUrl(), $data); + } +} diff --git a/Model/ServiceProvider.php b/Model/ServiceProvider.php new file mode 100644 index 0000000..7d76b0e --- /dev/null +++ b/Model/ServiceProvider.php @@ -0,0 +1,50 @@ +apiService = $apiService; + $this->config = $config; + } + + /** + * @param $request + * @return array|ResponseInterface + * @throws Exception + */ + public function getAvailableServices($request) + { + $data = [ + 'headers' => [ + 'Content-Type' => 'application/json' + ], + 'json' => $request + ]; + + return $this->apiService->makeRequest($this->config->getGettingServicesUrl(), $data); + } +} From 689c873f774be8c755d99d77bd1fb404ef98b4fa Mon Sep 17 00:00:00 2001 From: mrnhi Date: Wed, 1 Apr 2020 17:41:05 +0700 Subject: [PATCH 04/70] update code of classes which were affected by refactoring Service class --- Console/GeneratingRegionData.php | 11 +++++++- Model/Carrier/GHN.php | 32 ++++++++++++++++++++-- Model/Config.php | 10 +++++++ Model/ConfigProvider.php | 33 ++++++----------------- Observer/SalesOrderAfterPlaceObserver.php | 11 +++++++- Observer/SalesOrderAfterSaveObserver.php | 23 +++++++++++++--- etc/adminhtml/system.xml | 3 +++ etc/config.xml | 1 + 8 files changed, 92 insertions(+), 32 deletions(-) diff --git a/Console/GeneratingRegionData.php b/Console/GeneratingRegionData.php index 38c50da..f62cb0e 100644 --- a/Console/GeneratingRegionData.php +++ b/Console/GeneratingRegionData.php @@ -3,6 +3,7 @@ namespace Boolfly\GiaoHangNhanh\Console; use Boolfly\GiaoHangNhanh\Model\Api\Rest\Service; +use Boolfly\GiaoHangNhanh\Model\DistrictProvider; use Magento\Directory\Model\RegionFactory; use Magento\Framework\App\ResourceConnection; use Magento\Framework\Exception\NoSuchEntityException; @@ -27,22 +28,30 @@ class GeneratingRegionData extends Command */ private $regionFactory; + /** + * @var DistrictProvider + */ + private $districtProvider; + /** * GeneratingRegionData constructor. * @param Service $service * @param ResourceConnection $resourceConnection * @param RegionFactory $regionFactory + * @param DistrictProvider $districtProvider * @param string|null $name */ public function __construct( Service $service, ResourceConnection $resourceConnection, RegionFactory $regionFactory, + DistrictProvider $districtProvider, $name = null ) { $this->service = $service; $this->resourceConnection = $resourceConnection; $this->regionFactory = $regionFactory; + $this->districtProvider = $districtProvider; parent::__construct($name); } @@ -60,7 +69,7 @@ protected function configure() */ protected function execute(InputInterface $input, OutputInterface $output) { - $response = $this->service->getDistrictList(); + $response = $this->districtProvider->getDistrictList(); if (true === $this->service->checkResponse($response)) { $output->writeln('Generating data. Please wait...'); $responseObject = $response['response_object']; diff --git a/Model/Carrier/GHN.php b/Model/Carrier/GHN.php index 3ff4652..799c6e5 100644 --- a/Model/Carrier/GHN.php +++ b/Model/Carrier/GHN.php @@ -3,6 +3,8 @@ namespace Boolfly\GiaoHangNhanh\Model\Carrier; use Boolfly\GiaoHangNhanh\Model\Api\Rest\Service; +use Boolfly\GiaoHangNhanh\Model\ServiceProvider; +use Exception; use Magento\Checkout\Api\Data\ShippingInformationInterface; use Magento\Checkout\Model\Session; use Magento\Customer\Model\AddressFactory; @@ -81,6 +83,16 @@ class GHN extends AbstractCarrier implements CarrierInterface */ private $customerAddressFactory; + /** + * @var ServiceProvider + */ + private $serviceProvider; + + /** + * @var Config + */ + private $config; + /** * GHN constructor. * @param ScopeConfigInterface $scopeConfig @@ -94,6 +106,8 @@ class GHN extends AbstractCarrier implements CarrierInterface * @param ShippingInformationInterface $addressInformation * @param Session $session * @param AddressFactory $customerAddressFactory + * @param ServiceProvider $serviceProvider + * @param Config $config * @param array $data */ public function __construct( @@ -108,6 +122,8 @@ public function __construct( ShippingInformationInterface $addressInformation, Session $session, AddressFactory $customerAddressFactory, + ServiceProvider $serviceProvider, + Config $config, array $data = [] ) { parent::__construct($scopeConfig, $rateErrorFactory, $logger, $data); @@ -119,6 +135,8 @@ public function __construct( $this->addressInformation = $addressInformation; $this->session = $session; $this->customerAddressFactory = $customerAddressFactory; + $this->serviceProvider = $serviceProvider; + $this->config = $config; $this->weightUnit = $scopeConfig->getValue( Data::XML_PATH_WEIGHT_UNIT, ScopeInterface::SCOPE_STORE @@ -213,7 +231,16 @@ private function estimateShippingCost(RateRequest $request) $serviceId = $this->getAvailableServices($request); $request['ServiceID'] = $serviceId; $this->session->getQuote()->setData('shipping_service_id', $serviceId); - $response = $this->restService->estimateShippingCost($request)['response_object']; + + $response = $this->restService->makeRequest( + $this->config->getCalculatingFeeUrl(), + [ + 'headers' => [ + 'Content-Type' => 'application/json' + ], + 'json' => $request + ] + )['response_object']; return !empty($response->data->CalculatedFee) ? $response->data->CalculatedFee : null; } @@ -221,10 +248,11 @@ private function estimateShippingCost(RateRequest $request) /** * @param $request * @return string + * @throws Exception */ private function getAvailableServices($request) { - $response = $this->restService->getAvailableServices($request)['response_object']->data; + $response = $this->serviceProvider->getAvailableServices($request)['response_object']->data; if (is_array($response)) { foreach ($response as $serviceItem) { diff --git a/Model/Config.php b/Model/Config.php index 1e0edc0..2e4e084 100644 --- a/Model/Config.php +++ b/Model/Config.php @@ -24,6 +24,7 @@ class Config const GETTING_DISTRICTS_URL = 'carriers/giaohangnhanh_standard/get_districts_url'; const NOTE_CODE = 'carriers/giaohangnhanh_standard/note_code'; const DISTRICT = 'carriers/giaohangnhanh_standard/district'; + const GETTING_SERVICES_URL = 'carriers/giaohangnhanh_standard/get_services_url'; /** * @var int @@ -97,6 +98,15 @@ public function getGettingDistrictsUrl() return $this->getConfig(self::GETTING_DISTRICTS_URL); } + /** + * @return mixed + * @throws NoSuchEntityException + */ + public function getGettingServicesUrl() + { + return $this->getConfig(self::GETTING_SERVICES_URL); + } + /** * @return mixed * @throws NoSuchEntityException diff --git a/Model/ConfigProvider.php b/Model/ConfigProvider.php index 864f039..0db4bb7 100644 --- a/Model/ConfigProvider.php +++ b/Model/ConfigProvider.php @@ -3,22 +3,22 @@ namespace Boolfly\GiaoHangNhanh\Model; use Magento\Checkout\Model\ConfigProviderInterface; -use Magento\Framework\App\ResourceConnection; class ConfigProvider implements ConfigProviderInterface { /** - * @var ResourceConnection + * @var Config */ - private $resourceConnection; + private $config; /** * ConfigProvider constructor. - * @param ResourceConnection $resourceConnection + * @param Config $config */ - public function __construct(ResourceConnection $resourceConnection) - { - $this->resourceConnection = $resourceConnection; + public function __construct( + Config $config + ) { + $this->config = $config; } /** @@ -26,7 +26,7 @@ public function __construct(ResourceConnection $resourceConnection) */ public function getConfig() { - $districts = $this->getDistricts(); + $districts = $this->config->getDistricts(); $data = []; foreach ($districts as $district) { $data[$district['region_id']][] = [ @@ -39,21 +39,4 @@ public function getConfig() 'districts' => $data ]; } - - /** - * @return array - */ - private function getDistricts() - { - $connection = $this->resourceConnection->getConnection(); - $sql = $connection->select()->from( - ['districtTable' => $this->resourceConnection->getTableName('boolfly_giaohangnhanh_district')] - )->joinLeft( - ['regionTable' => $this->resourceConnection->getTableName('directory_country_region')], - 'regionTable.code = districtTable.province_id', - 'regionTable.region_id as region_id' - ); - - return $connection->fetchAll($sql); - } } diff --git a/Observer/SalesOrderAfterPlaceObserver.php b/Observer/SalesOrderAfterPlaceObserver.php index c8887b8..4c775ac 100644 --- a/Observer/SalesOrderAfterPlaceObserver.php +++ b/Observer/SalesOrderAfterPlaceObserver.php @@ -3,6 +3,7 @@ namespace Boolfly\GiaoHangNhanh\Observer; use Boolfly\GiaoHangNhanh\Model\Api\Rest\Service; +use Boolfly\GiaoHangNhanh\Model\Order\Processor; use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; use Magento\Quote\Model\QuoteRepository; @@ -19,16 +20,24 @@ class SalesOrderAfterPlaceObserver implements ObserverInterface */ private $quoteRepository; + /** + * @var Processor + */ + private $orderProcessor; + /** * SalesOrderAfterPlaceObserver constructor. * @param Service $service + * @param Processor $orderProcessor * @param QuoteRepository $quoteRepository */ public function __construct( Service $service, + Processor $orderProcessor, QuoteRepository $quoteRepository ) { $this->service = $service; + $this->orderProcessor = $orderProcessor; $this->quoteRepository = $quoteRepository; } @@ -42,6 +51,6 @@ public function execute(Observer $observer) $quote = $this->quoteRepository->getActive($order->getQuoteId()); $order->setDistrict($quote->getDistrict()); $order->setShippingServiceId($quote->getShippingServiceId()); - $this->service->syncOrder($order); + $this->orderProcessor->syncOrder($order); } } diff --git a/Observer/SalesOrderAfterSaveObserver.php b/Observer/SalesOrderAfterSaveObserver.php index 74e11f8..b27fe76 100644 --- a/Observer/SalesOrderAfterSaveObserver.php +++ b/Observer/SalesOrderAfterSaveObserver.php @@ -2,10 +2,12 @@ namespace Boolfly\GiaoHangNhanh\Observer; +use Exception; use Magento\Customer\Model\AddressFactory; use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; use Magento\Quote\Model\QuoteRepository; +use Psr\Log\LoggerInterface; class SalesOrderAfterSaveObserver implements ObserverInterface { @@ -19,15 +21,23 @@ class SalesOrderAfterSaveObserver implements ObserverInterface */ protected $customerAddressFactory; + /** + * @var LoggerInterface + */ + protected $logger; + /** * SalesOrderAfterSaveObserver constructor. * @param QuoteRepository $quoteRepository * @param AddressFactory $customerAddressFactory + * @param LoggerInterface $logger */ public function __construct( QuoteRepository $quoteRepository, - AddressFactory $customerAddressFactory + AddressFactory $customerAddressFactory, + LoggerInterface $logger ) { + $this->logger = $logger; $this->quoteRepository = $quoteRepository; $this->customerAddressFactory = $customerAddressFactory; } @@ -40,7 +50,14 @@ public function execute(Observer $observer) /** @var \Magento\Sales\Model\Order $order */ $order = $observer->getEvent()->getOrder(); $quote = $this->quoteRepository->getActive($order->getQuoteId()); - $address = $this->customerAddressFactory->create()->load($quote->getShippingAddress()->getCustomerAddressId()); - $address->setData('district', $quote->getDistrict())->save(); + $address = $this->customerAddressFactory->create() + ->load($quote->getShippingAddress()->getCustomerAddressId()); + + try { + $address->setData('district', $quote->getDistrict()); + $address->save(); + } catch (Exception $e) { + $this->logger->error(__('Can\'t set district for customer address.')); + } } } diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index 8203bfb..06adae8 100644 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -129,6 +129,9 @@ + + + Boolfly\GiaoHangNhanh\Model\Config\Source\PaymentType diff --git a/etc/config.xml b/etc/config.xml index 122dc1f..71aff89 100644 --- a/etc/config.xml +++ b/etc/config.xml @@ -31,6 +31,7 @@ https://dev-online-gateway.ghn.vn/apiv3-api/api/v1/apiv3/CalculateFee https://dev-online-gateway.ghn.vn/apiv3-api/api/v1/apiv3/CreateOrder https://dev-online-gateway.ghn.vn/apiv3-api/api/v1/apiv3/GetDistricts + https://dev-online-gateway.ghn.vn/apiv3-api/api/v1/apiv3/FindAvailableServices 2 CHOXEMHANGKHONGTHU From 8484a140255b9f1a2b3d486abaf5a1a48332a56e Mon Sep 17 00:00:00 2001 From: mrnhi Date: Fri, 3 Apr 2020 08:02:21 +0700 Subject: [PATCH 05/70] update GHN class --- Model/Carrier/GHN.php | 114 +++++++++++++++++++++++++----------------- 1 file changed, 67 insertions(+), 47 deletions(-) diff --git a/Model/Carrier/GHN.php b/Model/Carrier/GHN.php index 799c6e5..f246096 100644 --- a/Model/Carrier/GHN.php +++ b/Model/Carrier/GHN.php @@ -10,12 +10,12 @@ use Magento\Customer\Model\AddressFactory; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\Serialize\SerializerInterface; +use Magento\Quote\Model\Quote; use Magento\Shipping\Model\Carrier\AbstractCarrier; use Magento\Store\Model\Information; -use Magento\Store\Model\ScopeInterface; use Magento\Store\Model\StoreManagerInterface; use Psr\Log\LoggerInterface; -use Magento\Directory\Helper\Data; use Boolfly\GiaoHangNhanh\Model\Config; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Quote\Model\Quote\Address\RateRequest; @@ -58,11 +58,6 @@ class GHN extends AbstractCarrier implements CarrierInterface */ private $storeManager; - /** - * @var string - */ - private $weightUnit; - /** * @var Service */ @@ -93,6 +88,11 @@ class GHN extends AbstractCarrier implements CarrierInterface */ private $config; + /** + * @var SerializerInterface + */ + private $serializer; + /** * GHN constructor. * @param ScopeConfigInterface $scopeConfig @@ -108,6 +108,7 @@ class GHN extends AbstractCarrier implements CarrierInterface * @param AddressFactory $customerAddressFactory * @param ServiceProvider $serviceProvider * @param Config $config + * @param SerializerInterface $serializer * @param array $data */ public function __construct( @@ -124,6 +125,7 @@ public function __construct( AddressFactory $customerAddressFactory, ServiceProvider $serviceProvider, Config $config, + SerializerInterface $serializer, array $data = [] ) { parent::__construct($scopeConfig, $rateErrorFactory, $logger, $data); @@ -137,10 +139,7 @@ public function __construct( $this->customerAddressFactory = $customerAddressFactory; $this->serviceProvider = $serviceProvider; $this->config = $config; - $this->weightUnit = $scopeConfig->getValue( - Data::XML_PATH_WEIGHT_UNIT, - ScopeInterface::SCOPE_STORE - ); + $this->serializer = $serializer; } /** @@ -185,52 +184,27 @@ public function getAllowedMethods() * @return float|null * @throws NoSuchEntityException * @throws LocalizedException + * @throws Exception */ private function estimateShippingCost(RateRequest $request) { - $rate = $this->weightUnit == 'kgs' ? Config::KGS_G : Config::LBS_G; - $data = json_decode(file_get_contents('php://input'), true); $quote = $this->session->getQuote(); - $districtId = ''; - - if (!empty($data['address'])) { - $customAttributes = $data['address']['custom_attributes']; - } elseif (!empty($data['addressInformation'])) { - $customAttributes = $data['addressInformation']['shipping_address']['customAttributes']; - } else { - $customAttributes = null; - } - - if (null !== $customAttributes) { - foreach ($customAttributes as $attribute) { - if ($attribute['attribute_code'] == 'district') { - $districtId = $attribute['value']; - break; - } - } - } - - if (!$districtId) { - $customerAddress = $this->customerAddressFactory->create(); - - if (!empty($data['addressId'])) { - $districtId = $customerAddress->load($data['addressId'])->getDistrict(); - } elseif ($customerAddressId = $quote->getShippingAddress()->getCustomerAddressId()) { - $districtId = $customerAddress->load($customerAddressId)->getDistrict(); - } else { - $districtId = $quote->getDistrict(); - } - } - + $rate = $this->config->getWeightUnit() == 'kgs' ? Config::KGS_G : Config::LBS_G; $request = [ 'token' => 'TokenStaging', 'Weight' => $request->getPackageWeight() * $rate, - 'FromDistrictID' => 1443, - 'ToDistrictID' => (int)$districtId + 'FromDistrictID' => (int)$this->config->getStoreDistrict(), + 'ToDistrictID' => (int)$this->getDistrictId($quote) ]; $serviceId = $this->getAvailableServices($request); $request['ServiceID'] = $serviceId; - $this->session->getQuote()->setData('shipping_service_id', $serviceId); + $quote->setData('shipping_service_id', $serviceId); + + try { + $quote->save(); + } catch (Exception $e) { + $this->_logger->error(__('Can\'t save quote.')); + } $response = $this->restService->makeRequest( $this->config->getCalculatingFeeUrl(), @@ -268,4 +242,50 @@ private function getAvailableServices($request) return ''; } + + /** + * @param Quote $quote + * @return mixed|string + * @throws Exception + */ + private function getDistrictId(Quote $quote) + { + $data = $this->serializer->unserialize(file_get_contents('php://input')); + $districtId = ''; + + //After selecting shipping method and go to payment step + if (!empty($quote->getDistrict())) { + $districtId = $quote->getDistrict(); + } else { + //If the shipping address is new + if (!empty($data['address'])) { + $customAttributes = $data['address']['custom_attributes']; + + if (null !== $customAttributes) { + foreach ($customAttributes as $attribute) { + if ($attribute['attribute_code'] == 'district') { + $districtId = $attribute['value']; + break; + } + } + } + } + + //If existing shipping address has been selected + if (!empty($data['addressId'])) { + $customerAddress = $this->customerAddressFactory->create()->load($data['addressId']); + + if ($customerAddress->getId()) { + $districtId = $customerAddress->getDistrict(); + } + } + + //Set districtId to quote, this value will be used in payment step + if (!$quote->getDistrict()) { + $quote->setDistrict($districtId); + } + } + + return $districtId; + } } From aca218a6d3675897d617ad5bd96ee725f390a435 Mon Sep 17 00:00:00 2001 From: mrnhi Date: Fri, 3 Apr 2020 08:03:37 +0700 Subject: [PATCH 06/70] delete Observer/SalesOrderAfterPlaceObserver.php --- Observer/SalesOrderAfterPlaceObserver.php | 56 ----------------------- 1 file changed, 56 deletions(-) delete mode 100644 Observer/SalesOrderAfterPlaceObserver.php diff --git a/Observer/SalesOrderAfterPlaceObserver.php b/Observer/SalesOrderAfterPlaceObserver.php deleted file mode 100644 index 4c775ac..0000000 --- a/Observer/SalesOrderAfterPlaceObserver.php +++ /dev/null @@ -1,56 +0,0 @@ -service = $service; - $this->orderProcessor = $orderProcessor; - $this->quoteRepository = $quoteRepository; - } - - /** - * @inheritDoc - */ - public function execute(Observer $observer) - { - /** @var \Magento\Sales\Model\Order $order */ - $order = $observer->getEvent()->getOrder(); - $quote = $this->quoteRepository->getActive($order->getQuoteId()); - $order->setDistrict($quote->getDistrict()); - $order->setShippingServiceId($quote->getShippingServiceId()); - $this->orderProcessor->syncOrder($order); - } -} From 069305a39d0ac58ee33167b5543680ee7e4d552e Mon Sep 17 00:00:00 2001 From: mrnhi Date: Fri, 3 Apr 2020 08:13:17 +0700 Subject: [PATCH 07/70] remove sales_place_order_after event --- etc/events.xml | 3 --- 1 file changed, 3 deletions(-) diff --git a/etc/events.xml b/etc/events.xml index 4ffc598..c0012b5 100644 --- a/etc/events.xml +++ b/etc/events.xml @@ -1,8 +1,5 @@ - - - From b6e0f295147a3ef46fbabeb5712e09f00499c446 Mon Sep 17 00:00:00 2001 From: mrnhi Date: Fri, 3 Apr 2020 08:17:02 +0700 Subject: [PATCH 08/70] update Observer/SalesOrderAfterSaveObserver.php --- Observer/SalesOrderAfterSaveObserver.php | 45 +++++++++++++++++++----- 1 file changed, 36 insertions(+), 9 deletions(-) diff --git a/Observer/SalesOrderAfterSaveObserver.php b/Observer/SalesOrderAfterSaveObserver.php index b27fe76..3af6229 100644 --- a/Observer/SalesOrderAfterSaveObserver.php +++ b/Observer/SalesOrderAfterSaveObserver.php @@ -2,6 +2,7 @@ namespace Boolfly\GiaoHangNhanh\Observer; +use Boolfly\GiaoHangNhanh\Model\Order\Processor; use Exception; use Magento\Customer\Model\AddressFactory; use Magento\Framework\Event\Observer; @@ -14,31 +15,39 @@ class SalesOrderAfterSaveObserver implements ObserverInterface /** * @var QuoteRepository */ - protected $quoteRepository; + private $quoteRepository; /** * @var AddressFactory */ - protected $customerAddressFactory; + private $customerAddressFactory; /** * @var LoggerInterface */ - protected $logger; + private $logger; + + /** + * @var Processor + */ + private $orderProcessor; /** * SalesOrderAfterSaveObserver constructor. * @param QuoteRepository $quoteRepository * @param AddressFactory $customerAddressFactory * @param LoggerInterface $logger + * @param Processor $orderProcessor */ public function __construct( QuoteRepository $quoteRepository, AddressFactory $customerAddressFactory, - LoggerInterface $logger + LoggerInterface $logger, + Processor $orderProcessor ) { $this->logger = $logger; $this->quoteRepository = $quoteRepository; + $this->orderProcessor = $orderProcessor; $this->customerAddressFactory = $customerAddressFactory; } @@ -50,14 +59,32 @@ public function execute(Observer $observer) /** @var \Magento\Sales\Model\Order $order */ $order = $observer->getEvent()->getOrder(); $quote = $this->quoteRepository->getActive($order->getQuoteId()); - $address = $this->customerAddressFactory->create() - ->load($quote->getShippingAddress()->getCustomerAddressId()); + $order->setDistrict($quote->getDistrict()); + $order->setShippingServiceId($quote->getShippingServiceId()); try { - $address->setData('district', $quote->getDistrict()); - $address->save(); + $order->save(); + $this->orderProcessor->syncOrder($order); } catch (Exception $e) { - $this->logger->error(__('Can\'t set district for customer address.')); + $this->logger->error(__( + 'Can\'t send order with increment ID %1 to giaohangnhanh.', + $order->getIncrementId() + )); + } + + $customerAddressId = $quote->getShippingAddress()->getCustomerAddressId(); + $address = $this->customerAddressFactory->create()->load($customerAddressId); + + if ($address->getId()) { + try { + $address->setData('district', $quote->getDistrict()); + $address->save(); + } catch (Exception $e) { + $this->logger->error(__( + 'Can\'t set district for customer address with ID %1.', + $customerAddressId + )); + } } } } From ce339f93ba9916f3475c6f486a2a9eabc25bd617 Mon Sep 17 00:00:00 2001 From: mrnhi Date: Fri, 3 Apr 2020 08:29:11 +0700 Subject: [PATCH 09/70] delete Plugin/Checkout/Model/ShippingInformationManagement.php --- .../Model/ShippingInformationManagement.php | 82 ------------------- 1 file changed, 82 deletions(-) delete mode 100644 Plugin/Checkout/Model/ShippingInformationManagement.php diff --git a/Plugin/Checkout/Model/ShippingInformationManagement.php b/Plugin/Checkout/Model/ShippingInformationManagement.php deleted file mode 100644 index bb0202b..0000000 --- a/Plugin/Checkout/Model/ShippingInformationManagement.php +++ /dev/null @@ -1,82 +0,0 @@ -quoteRepository = $quoteRepository; - $this->addressRepository = $addressRepository; - $this->customerAddressFactory = $customerAddressFactory; - } - - /** - * @param MageShippingInformationManagement $subject - * @param $result - * @param $cartId - * @param ShippingInformationInterface $addressInformation - * @return mixed - * @throws NoSuchEntityException - */ - public function afterSaveAddressInformation( - MageShippingInformationManagement $subject, - $result, - $cartId, - ShippingInformationInterface $addressInformation - ) { - /** @var \Magento\Quote\Model\Quote $quote */ - $quote = $this->quoteRepository->getActive($cartId); - $district = ''; - - if ($extensionAttributes = $addressInformation->getExtensionAttributes()) { - if ($extensionAttributes->getDistrict()) { - $district = $extensionAttributes->getDistrict(); - } - } - - if (!$district) { - $customerAddressId = $addressInformation->getShippingAddress()->getCustomerAddressId(); - $customerAddress = $this->customerAddressFactory->create()->load($customerAddressId); - if ($customerAddress->getId()) { - $district = $customerAddress->getDistrict(); - } - } - - $quote->setData('district', $district); - $this->quoteRepository->save($quote); - - return $result; - } -} From ab01e9b3d74aecac413c5641181b8a89fbc614bb Mon Sep 17 00:00:00 2001 From: mrnhi Date: Fri, 3 Apr 2020 08:30:41 +0700 Subject: [PATCH 10/70] update di.xml --- etc/di.xml | 3 --- 1 file changed, 3 deletions(-) diff --git a/etc/di.xml b/etc/di.xml index 5a53e27..f46908f 100755 --- a/etc/di.xml +++ b/etc/di.xml @@ -13,7 +13,4 @@ - - - From 3e5d0d06f7b996c5de8c4bbcf540e9824959576d Mon Sep 17 00:00:00 2001 From: mrnhi Date: Fri, 3 Apr 2020 08:32:06 +0700 Subject: [PATCH 11/70] update Model/Attribute/Source/District.php --- Model/Attribute/Source/District.php | 54 +---------------------------- 1 file changed, 1 insertion(+), 53 deletions(-) diff --git a/Model/Attribute/Source/District.php b/Model/Attribute/Source/District.php index e965899..9e52f28 100644 --- a/Model/Attribute/Source/District.php +++ b/Model/Attribute/Source/District.php @@ -2,71 +2,19 @@ namespace Boolfly\GiaoHangNhanh\Model\Attribute\Source; -use Boolfly\GiaoHangNhanh\Model\Config; use Magento\Eav\Model\Entity\Attribute\Source\AbstractSource; -use Magento\Store\Model\Information; -use Magento\Store\Model\StoreManagerInterface; class District extends AbstractSource { - /** - * @var Information - */ - private $storeInformation; - - /** - * @var StoreManagerInterface - */ - private $storeManager; - - /** - * @var Config - */ - private $config; - - /** - * District constructor. - * @param Config $config - * @param Information $storeInformation - * @param StoreManagerInterface $storeManager - */ - public function __construct( - Config $config, - Information $storeInformation, - StoreManagerInterface $storeManager - ) { - $this->storeInformation = $storeInformation; - $this->storeManager = $storeManager; - $this->config = $config; - } - /** * @inheritDoc */ public function getAllOptions() { - $store = $this->storeManager->getStore(); - $storeInfo = $this->storeInformation->getStoreInformationObject($store); - $districts = $this->config->getDistricts(); - $data = []; - foreach ($districts as $district) { - if ($district['region_id'] == $storeInfo->getRegionId()) { - $data[] = [ - 'districtName' => $district['district_name'], - 'districtID' => $district['district_id'] - ]; - } - } - if (!$this->_options) { $this->_options[] = ['label' => __('Please select a district.'), 'value' => '']; - - if ($data) { - foreach ($data as $districtItem) { - $this->_options[] = ['label' => $districtItem['districtName'], 'value' => $districtItem['districtID']]; - } - } } + return $this->_options; } } From 0bc9cd5c74c499ba32dea7676c2f817fff9d3f3a Mon Sep 17 00:00:00 2001 From: mrnhi Date: Tue, 7 Apr 2020 19:09:14 +0700 Subject: [PATCH 12/70] update some code in carrier classes --- Model/Carrier/GHN.php | 208 +++++++++++++-------------------- Model/Carrier/GHN/Express.php | 2 + Model/Carrier/GHN/Standard.php | 2 + 3 files changed, 82 insertions(+), 130 deletions(-) diff --git a/Model/Carrier/GHN.php b/Model/Carrier/GHN.php index f246096..94ed802 100644 --- a/Model/Carrier/GHN.php +++ b/Model/Carrier/GHN.php @@ -3,18 +3,14 @@ namespace Boolfly\GiaoHangNhanh\Model\Carrier; use Boolfly\GiaoHangNhanh\Model\Api\Rest\Service; +use Boolfly\GiaoHangNhanh\Model\Carrier\GHN\Express; +use Boolfly\GiaoHangNhanh\Model\Carrier\GHN\Standard; use Boolfly\GiaoHangNhanh\Model\ServiceProvider; use Exception; -use Magento\Checkout\Api\Data\ShippingInformationInterface; -use Magento\Checkout\Model\Session; -use Magento\Customer\Model\AddressFactory; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\NoSuchEntityException; -use Magento\Framework\Serialize\SerializerInterface; -use Magento\Quote\Model\Quote; +use Magento\Quote\Model\QuoteRepository; use Magento\Shipping\Model\Carrier\AbstractCarrier; -use Magento\Store\Model\Information; -use Magento\Store\Model\StoreManagerInterface; use Psr\Log\LoggerInterface; use Boolfly\GiaoHangNhanh\Model\Config; use Magento\Framework\App\Config\ScopeConfigInterface; @@ -26,7 +22,7 @@ use Magento\Shipping\Model\Rate\Result; use Magento\Shipping\Model\Rate\ResultFactory; -class GHN extends AbstractCarrier implements CarrierInterface +abstract class GHN extends AbstractCarrier implements CarrierInterface { /** * @var string @@ -48,36 +44,11 @@ class GHN extends AbstractCarrier implements CarrierInterface */ private $rateMethodFactory; - /** - * @var Information - */ - private $storeInformation; - - /** - * @var StoreManagerInterface - */ - private $storeManager; - /** * @var Service */ private $restService; - /** - * @var ShippingInformationInterface - */ - private $addressInformation; - - /** - * @var Session - */ - private $session; - - /** - * @var AddressFactory - */ - private $customerAddressFactory; - /** * @var ServiceProvider */ @@ -89,9 +60,14 @@ class GHN extends AbstractCarrier implements CarrierInterface private $config; /** - * @var SerializerInterface + * @var QuoteRepository + */ + private $quoteRepository; + + /** + * @var array */ - private $serializer; + private $availableServices = []; /** * GHN constructor. @@ -100,15 +76,10 @@ class GHN extends AbstractCarrier implements CarrierInterface * @param LoggerInterface $logger * @param ResultFactory $rateResultFactory * @param MethodFactory $rateMethodFactory - * @param Information $storeInformation - * @param StoreManagerInterface $storeManager * @param Service $restService - * @param ShippingInformationInterface $addressInformation - * @param Session $session - * @param AddressFactory $customerAddressFactory * @param ServiceProvider $serviceProvider * @param Config $config - * @param SerializerInterface $serializer + * @param QuoteRepository $quoteRepository * @param array $data */ public function __construct( @@ -117,29 +88,19 @@ public function __construct( LoggerInterface $logger, ResultFactory $rateResultFactory, MethodFactory $rateMethodFactory, - Information $storeInformation, - StoreManagerInterface $storeManager, Service $restService, - ShippingInformationInterface $addressInformation, - Session $session, - AddressFactory $customerAddressFactory, ServiceProvider $serviceProvider, Config $config, - SerializerInterface $serializer, + QuoteRepository $quoteRepository, array $data = [] ) { parent::__construct($scopeConfig, $rateErrorFactory, $logger, $data); $this->rateResultFactory = $rateResultFactory; $this->rateMethodFactory = $rateMethodFactory; - $this->storeInformation = $storeInformation; - $this->storeManager = $storeManager; $this->restService = $restService; - $this->addressInformation = $addressInformation; - $this->session = $session; - $this->customerAddressFactory = $customerAddressFactory; $this->serviceProvider = $serviceProvider; $this->config = $config; - $this->serializer = $serializer; + $this->quoteRepository = $quoteRepository; } /** @@ -188,35 +149,51 @@ public function getAllowedMethods() */ private function estimateShippingCost(RateRequest $request) { - $quote = $this->session->getQuote(); - $rate = $this->config->getWeightUnit() == 'kgs' ? Config::KGS_G : Config::LBS_G; - $request = [ - 'token' => 'TokenStaging', - 'Weight' => $request->getPackageWeight() * $rate, - 'FromDistrictID' => (int)$this->config->getStoreDistrict(), - 'ToDistrictID' => (int)$this->getDistrictId($quote) - ]; - $serviceId = $this->getAvailableServices($request); - $request['ServiceID'] = $serviceId; - $quote->setData('shipping_service_id', $serviceId); - - try { - $quote->save(); - } catch (Exception $e) { - $this->_logger->error(__('Can\'t save quote.')); + $quote = $this->quoteRepository->getActive( + $request->getAllItems()[0]->getQuoteId() + ); + $shippingAddress = $quote->getShippingAddress(); + $districtId = $shippingAddress->getDistrict(); + + if ($districtId) { + $rate = $this->config->getWeightUnit() == 'kgs' ? Config::KGS_G : Config::LBS_G; + $requestBody = [ + 'token' => $this->config->getApiToken(), + 'Weight' => $request->getPackageWeight() * $rate, + 'FromDistrictID' => (int)$this->config->getStoreDistrict(), + 'ToDistrictID' => (int)$districtId + ]; + + if ($serviceId = $this->getAvailableService($requestBody)) { + $requestBody['ServiceID'] = $serviceId; + + if ($request->getLimitCarrier()) { + $shippingAddress->setData('shipping_service_id', $serviceId); + + try { + $shippingAddress->save(); + } catch (Exception $e) { + $this->_logger->error(__('Can\'t save shipping address.')); + } + } + + $response = $this->restService->makeRequest( + $this->config->getCalculatingFeeUrl(), + [ + 'headers' => [ + 'Content-Type' => 'application/json' + ], + 'json' => $requestBody + ] + ); + + if ($this->restService->checkResponse($response)) { + return $response['response_object']->data->CalculatedFee; + } + } } - $response = $this->restService->makeRequest( - $this->config->getCalculatingFeeUrl(), - [ - 'headers' => [ - 'Content-Type' => 'application/json' - ], - 'json' => $request - ] - )['response_object']; - - return !empty($response->data->CalculatedFee) ? $response->data->CalculatedFee : null; + return null; } /** @@ -224,68 +201,39 @@ private function estimateShippingCost(RateRequest $request) * @return string * @throws Exception */ - private function getAvailableServices($request) + private function getAvailableService($request) { - $response = $this->serviceProvider->getAvailableServices($request)['response_object']->data; + if (empty($this->availableServices)) { + $response = $this->serviceProvider->getAvailableServices($request); - if (is_array($response)) { - foreach ($response as $serviceItem) { - if (!empty($serviceItem->Name)) { - $serviceType = $this->_code == 'giaohangnhanh_express' ? 'Nhanh' : 'Chuẩn'; - - if ($serviceItem->Name == $serviceType) { - return $serviceItem->ServiceID; - } - } + if ($this->restService->checkResponse($response)) { + $data = $response['response_object']->data; + $this->availableServices = is_array($data) ? $data : []; } } - return ''; - } + if (count($this->availableServices)) { + foreach ($this->availableServices as $serviceItem) { + if (!empty($serviceItem->Name)) { - /** - * @param Quote $quote - * @return mixed|string - * @throws Exception - */ - private function getDistrictId(Quote $quote) - { - $data = $this->serializer->unserialize(file_get_contents('php://input')); - $districtId = ''; - - //After selecting shipping method and go to payment step - if (!empty($quote->getDistrict())) { - $districtId = $quote->getDistrict(); - } else { - //If the shipping address is new - if (!empty($data['address'])) { - $customAttributes = $data['address']['custom_attributes']; - - if (null !== $customAttributes) { - foreach ($customAttributes as $attribute) { - if ($attribute['attribute_code'] == 'district') { - $districtId = $attribute['value']; + switch ($this->_code) { + case Express::CODE: + $serviceType = 'Nhanh'; + break; + case Standard::CODE: + $serviceType = 'Chuẩn'; break; - } + default: + $serviceType = 'Chuẩn'; } - } - } - - //If existing shipping address has been selected - if (!empty($data['addressId'])) { - $customerAddress = $this->customerAddressFactory->create()->load($data['addressId']); - if ($customerAddress->getId()) { - $districtId = $customerAddress->getDistrict(); + if ($serviceItem->Name == $serviceType) { + return $serviceItem->ServiceID; + } } } - - //Set districtId to quote, this value will be used in payment step - if (!$quote->getDistrict()) { - $quote->setDistrict($districtId); - } } - return $districtId; + return ''; } } diff --git a/Model/Carrier/GHN/Express.php b/Model/Carrier/GHN/Express.php index 3b0771a..d16f89d 100644 --- a/Model/Carrier/GHN/Express.php +++ b/Model/Carrier/GHN/Express.php @@ -6,6 +6,8 @@ class Express extends GHN { + const CODE = 'giaohangnhanh_express'; + /** * @var string */ diff --git a/Model/Carrier/GHN/Standard.php b/Model/Carrier/GHN/Standard.php index b15fc38..67771af 100644 --- a/Model/Carrier/GHN/Standard.php +++ b/Model/Carrier/GHN/Standard.php @@ -6,6 +6,8 @@ class Standard extends GHN { + const CODE = 'giaohangnhanh_standard'; + /** * @var string */ From c1cde0efdc52907442865b10b3c47bbe6b02f6d9 Mon Sep 17 00:00:00 2001 From: mrnhi Date: Tue, 7 Apr 2020 19:15:55 +0700 Subject: [PATCH 13/70] add plugin classes --- .../Model/ShippingInformationManagement.php | 71 +++++++++++++++++++ .../Quote/Model/EstimateByAddressIdBefore.php | 56 +++++++++++++++ .../Model/EstimateByExtendedAddressBefore.php | 56 +++++++++++++++ etc/di.xml | 20 +++++- 4 files changed, 201 insertions(+), 2 deletions(-) create mode 100644 Plugin/Checkout/Model/ShippingInformationManagement.php create mode 100644 Plugin/Quote/Model/EstimateByAddressIdBefore.php create mode 100644 Plugin/Quote/Model/EstimateByExtendedAddressBefore.php diff --git a/Plugin/Checkout/Model/ShippingInformationManagement.php b/Plugin/Checkout/Model/ShippingInformationManagement.php new file mode 100644 index 0000000..5472452 --- /dev/null +++ b/Plugin/Checkout/Model/ShippingInformationManagement.php @@ -0,0 +1,71 @@ +quoteRepository = $quoteRepository; + $this->districtProvider = $districtProvider; + } + + /** + * @param MageShippingInformationManagement $subject + * @param $cartId + * @param ShippingInformationInterface $addressInformation + * @throws NoSuchEntityException + */ + public function beforeSaveAddressInformation( + MageShippingInformationManagement $subject, + $cartId, + ShippingInformationInterface $addressInformation + ) { + if (false !== strpos($addressInformation->getShippingMethodCode(), Config::GHN_CODE)) { + $quote = $this->quoteRepository->getActive($cartId); + $extensionAttributes = $addressInformation->getExtensionAttributes(); + $shippingAddress = $quote->getShippingAddress(); + $district = ''; + + if ($shippingAddress->getDistrict()) { + return; + } + + if (!$extensionAttributes->getDistrict()) { + if ($customerAddressId = $shippingAddress->getCustomerAddressId()) { + $district = $this->districtProvider->getDistrictByCustomerAddressId($customerAddressId); + } + } else { + $district = $extensionAttributes->getDistrict(); + } + + if ($district) { + $shippingAddress->setDistrict($district); + } + } + } +} diff --git a/Plugin/Quote/Model/EstimateByAddressIdBefore.php b/Plugin/Quote/Model/EstimateByAddressIdBefore.php new file mode 100644 index 0000000..05b9cbb --- /dev/null +++ b/Plugin/Quote/Model/EstimateByAddressIdBefore.php @@ -0,0 +1,56 @@ +quoteRepository = $quoteRepository; + $this->districtProvider = $districtProvider; + } + + /** + * @param MageShippingMethodManagement $subject + * @param $cartId + * @param $addressId + * @throws NoSuchEntityException + */ + public function beforeEstimateByAddressId( + MageShippingMethodManagement $subject, + $cartId, + $addressId + ) { + /** @var \Magento\Quote\Model\Quote $quote */ + $quote = $this->quoteRepository->getActive($cartId); + $district = $this->districtProvider->getDistrictByCustomerAddressId($addressId); + + if (!$district) { + return; + } + + $quote->getShippingAddress()->setDistrict($district); + } +} diff --git a/Plugin/Quote/Model/EstimateByExtendedAddressBefore.php b/Plugin/Quote/Model/EstimateByExtendedAddressBefore.php new file mode 100644 index 0000000..504785d --- /dev/null +++ b/Plugin/Quote/Model/EstimateByExtendedAddressBefore.php @@ -0,0 +1,56 @@ +quoteRepository = $quoteRepository; + } + + + /** + * @param MageShippingMethodManagement $subject + * @param $cartId + * @param AddressInterface $address + * @throws NoSuchEntityException + */ + public function beforeEstimateByExtendedAddress( + MageShippingMethodManagement $subject, + $cartId, + AddressInterface $address + ) { + /** @var \Magento\Quote\Model\Quote $quote */ + $quote = $this->quoteRepository->getActive($cartId); + $checkoutFields = $address->getExtensionAttributes()->getCheckoutFields(); + $district = ''; + + foreach ($checkoutFields as $field) { + if ($field->getAttributeCode() == 'district') { + $district = $field->getValue(); + break; + } + } + + if (!$district) { + return; + } + + $quote->getShippingAddress()->setDistrict($district); + } +} diff --git a/etc/di.xml b/etc/di.xml index f46908f..55636ca 100755 --- a/etc/di.xml +++ b/etc/di.xml @@ -1,6 +1,6 @@ - + region:generate @@ -9,8 +9,24 @@ - Boolfly\GiaoHangNhanh\Console\GeneratingRegionData + + Boolfly\GiaoHangNhanh\Console\GenerateRegionCommand + + + + + sales_order.ghn_status + + + + + + + + + + From 14da0f12b01621b23fbea927a2edd4d9fb535ac6 Mon Sep 17 00:00:00 2001 From: mrnhi Date: Tue, 7 Apr 2020 19:21:02 +0700 Subject: [PATCH 14/70] refactor code --- ...gionData.php => GenerateRegionCommand.php} | 2 +- Model/Config.php | 1 + Model/DistrictProvider.php | 26 ++++++++++++++++++- Model/Order/Processor.php | 21 +++++++++++---- .../Block/Checkout/LayoutProcessor.php | 1 + 5 files changed, 44 insertions(+), 7 deletions(-) rename Console/{GeneratingRegionData.php => GenerateRegionCommand.php} (98%) diff --git a/Console/GeneratingRegionData.php b/Console/GenerateRegionCommand.php similarity index 98% rename from Console/GeneratingRegionData.php rename to Console/GenerateRegionCommand.php index f62cb0e..8bf1886 100644 --- a/Console/GeneratingRegionData.php +++ b/Console/GenerateRegionCommand.php @@ -11,7 +11,7 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -class GeneratingRegionData extends Command +class GenerateRegionCommand extends Command { /** * @var Service diff --git a/Model/Config.php b/Model/Config.php index 2e4e084..3d1aa57 100644 --- a/Model/Config.php +++ b/Model/Config.php @@ -11,6 +11,7 @@ class Config { + const GHN_CODE = 'giaohangnhanh'; const LBS_G = 453.59237; const KGS_G = 1000; const IS_ACTIVE = 'active'; diff --git a/Model/DistrictProvider.php b/Model/DistrictProvider.php index 9539e92..ed54d65 100644 --- a/Model/DistrictProvider.php +++ b/Model/DistrictProvider.php @@ -4,6 +4,7 @@ use Boolfly\GiaoHangNhanh\Model\Api\Rest\Service; use Exception; +use Magento\Customer\Model\AddressFactory; use Magento\Framework\Exception\NoSuchEntityException; use Psr\Http\Message\ResponseInterface; @@ -19,17 +20,25 @@ class DistrictProvider */ private $config; + /** + * @var AddressFactory + */ + private $customerAddressFactory; + /** * DistrictProvider constructor. * @param Service $apiService * @param Config $config + * @param AddressFactory $customerAddressFactory */ public function __construct( Service $apiService, - Config $config + Config $config, + AddressFactory $customerAddressFactory ) { $this->apiService = $apiService; $this->config = $config; + $this->customerAddressFactory = $customerAddressFactory; } /** @@ -48,4 +57,19 @@ public function getDistrictList() return $this->apiService->makeRequest($this->config->getGettingDistrictsUrl(), $data); } + + /** + * @param int $customerAddressId + * @return string + */ + public function getDistrictByCustomerAddressId($customerAddressId) + { + $address = $this->customerAddressFactory->create()->load($customerAddressId); + + if (!$address->getId()) { + return ''; + } + + return $address->getDistrict() ?: ''; + } } diff --git a/Model/Order/Processor.php b/Model/Order/Processor.php index eaa2ac6..c766ecc 100644 --- a/Model/Order/Processor.php +++ b/Model/Order/Processor.php @@ -6,6 +6,7 @@ use Boolfly\GiaoHangNhanh\Model\Config; use Exception; use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Quote\Model\Quote\AddressFactory; use Magento\Sales\Model\Order; use Magento\Store\Model\Information; use Magento\Store\Model\StoreManagerInterface; @@ -33,32 +34,40 @@ class Processor */ private $apiService; + /** + * @var AddressFactory + */ + private $addressFactory; + /** * Processor constructor. * @param Config $config * @param Service $apiService * @param StoreManagerInterface $storeManager * @param Information $storeInformation + * @param AddressFactory $addressFactory */ public function __construct( Config $config, Service $apiService, StoreManagerInterface $storeManager, - Information $storeInformation + Information $storeInformation, + AddressFactory $addressFactory ) { $this->config = $config; $this->apiService = $apiService; $this->storeManager = $storeManager; $this->storeInformation = $storeInformation; + $this->addressFactory = $addressFactory; } /** * @param Order $order + * @param array $additionalData * @return array|ResponseInterface * @throws NoSuchEntityException - * @throws Exception */ - public function syncOrder(Order $order) + public function syncOrder(Order $order, $additionalData) { $config = $this->config; $weightRate = $config->getWeightUnit() == 'kgs' ? Config::KGS_G : Config::LBS_G; @@ -66,6 +75,8 @@ public function syncOrder(Order $order) $storeInfo = $this->storeInformation->getStoreInformationObject($store); $storeFormattedAddress = $this->storeInformation->getFormattedAddress($store); $storeDistrict = (int)$config->getStoreDistrict(); + $address = $this->addressFactory->create()->load($order->getQuoteAddressId()); + $data = [ 'headers' => [ 'Content-Type' => 'application/json' @@ -74,7 +85,7 @@ public function syncOrder(Order $order) 'token' => $config->getApiToken(), 'PaymentTypeID' => $config->getPaymentType(), 'FromDistrictID' => $storeDistrict, - 'ToDistrictID' => (int)$order->getDistrict(), + 'ToDistrictID' => (int)$additionalData['district'], 'ClientContactName' => $storeInfo->getName(), 'ClientContactPhone' => $storeInfo->getPhone(), 'ClientAddress' => $storeFormattedAddress, @@ -82,7 +93,7 @@ public function syncOrder(Order $order) 'CustomerPhone' => $order->getShippingAddress()->getTelephone(), 'ShippingAddress' => $order->getShippingAddress()->getStreetLine(1), 'NoteCode' => $config->getNoteCode(), - 'ServiceID' => $order->getShippingServiceId(), + 'ServiceID' => $additionalData['shipping_service_id'], 'Weight' => $order->getWeight() * $weightRate, 'Length' => 10, 'Width' => 10, diff --git a/Plugin/Checkout/Block/Checkout/LayoutProcessor.php b/Plugin/Checkout/Block/Checkout/LayoutProcessor.php index 9ec7ad5..1d97444 100644 --- a/Plugin/Checkout/Block/Checkout/LayoutProcessor.php +++ b/Plugin/Checkout/Block/Checkout/LayoutProcessor.php @@ -1,6 +1,7 @@ Date: Tue, 7 Apr 2020 19:23:06 +0700 Subject: [PATCH 15/70] add ghn_status column to sales_order and sales_order_grid tables --- etc/db_schema.xml | 10 ++++++---- etc/db_schema_whitelist.json | 29 +++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 4 deletions(-) create mode 100644 etc/db_schema_whitelist.json diff --git a/etc/db_schema.xml b/etc/db_schema.xml index 70abde8..852a327 100644 --- a/etc/db_schema.xml +++ b/etc/db_schema.xml @@ -12,13 +12,15 @@ - +
- - +
+
- +
\ No newline at end of file diff --git a/etc/db_schema_whitelist.json b/etc/db_schema_whitelist.json new file mode 100644 index 0000000..47183c1 --- /dev/null +++ b/etc/db_schema_whitelist.json @@ -0,0 +1,29 @@ +{ + "boolfly_giaohangnhanh_district": { + "column": { + "entity_id": true, + "district_id": true, + "province_id": true, + "district_name": true + }, + "constraint": { + "PRIMARY": true + } + }, + "sales_order": { + "column": { + "ghn_status": true + } + }, + "quote_address": { + "column": { + "district": true, + "shipping_service_id": true + } + }, + "sales_order_grid": { + "column": { + "ghn_status": true + } + } +} \ No newline at end of file From f8d361adffba85253d9ab2a8c7599a9d1e783158 Mon Sep 17 00:00:00 2001 From: mrnhi Date: Tue, 7 Apr 2020 19:26:20 +0700 Subject: [PATCH 16/70] update Observer/SalesOrderAfterSaveObserver.php --- Observer/SalesOrderAfterSaveObserver.php | 66 +++++++++++++++++------- 1 file changed, 46 insertions(+), 20 deletions(-) diff --git a/Observer/SalesOrderAfterSaveObserver.php b/Observer/SalesOrderAfterSaveObserver.php index 3af6229..2fbdd5a 100644 --- a/Observer/SalesOrderAfterSaveObserver.php +++ b/Observer/SalesOrderAfterSaveObserver.php @@ -2,6 +2,8 @@ namespace Boolfly\GiaoHangNhanh\Observer; +use Boolfly\GiaoHangNhanh\Model\Api\Rest\Service; +use Boolfly\GiaoHangNhanh\Model\Config; use Boolfly\GiaoHangNhanh\Model\Order\Processor; use Exception; use Magento\Customer\Model\AddressFactory; @@ -12,6 +14,9 @@ class SalesOrderAfterSaveObserver implements ObserverInterface { + const GHN_STATUS_FAIL = 0; + const GHN_STATUS_SUCCESS = 1; + /** * @var QuoteRepository */ @@ -32,20 +37,28 @@ class SalesOrderAfterSaveObserver implements ObserverInterface */ private $orderProcessor; + /** + * @var Service + */ + private $apiService; + /** * SalesOrderAfterSaveObserver constructor. * @param QuoteRepository $quoteRepository * @param AddressFactory $customerAddressFactory * @param LoggerInterface $logger * @param Processor $orderProcessor + * @param Service $apiService */ public function __construct( QuoteRepository $quoteRepository, AddressFactory $customerAddressFactory, LoggerInterface $logger, - Processor $orderProcessor + Processor $orderProcessor, + Service $apiService ) { $this->logger = $logger; + $this->apiService = $apiService; $this->quoteRepository = $quoteRepository; $this->orderProcessor = $orderProcessor; $this->customerAddressFactory = $customerAddressFactory; @@ -58,33 +71,46 @@ public function execute(Observer $observer) { /** @var \Magento\Sales\Model\Order $order */ $order = $observer->getEvent()->getOrder(); - $quote = $this->quoteRepository->getActive($order->getQuoteId()); - $order->setDistrict($quote->getDistrict()); - $order->setShippingServiceId($quote->getShippingServiceId()); - try { - $order->save(); - $this->orderProcessor->syncOrder($order); - } catch (Exception $e) { - $this->logger->error(__( - 'Can\'t send order with increment ID %1 to giaohangnhanh.', - $order->getIncrementId() - )); - } + if (false !== strpos($order->getShippingMethod(), Config::GHN_CODE)) { + $quote = $this->quoteRepository->getActive($order->getQuoteId()); + $shippingAddress = $quote->getShippingAddress(); + $additionalData = [ + 'district' => $shippingAddress->getDistrict(), + 'shipping_service_id' => $shippingAddress->getShippingServiceId() + ]; + $response = $this->orderProcessor->syncOrder($order, $additionalData); - $customerAddressId = $quote->getShippingAddress()->getCustomerAddressId(); - $address = $this->customerAddressFactory->create()->load($customerAddressId); + if (true === $this->apiService->checkResponse($response)) { + $order->setData('ghn_status', self::GHN_STATUS_SUCCESS); + } else { + $order->setData('ghn_status', self::GHN_STATUS_FAIL); + } - if ($address->getId()) { try { - $address->setData('district', $quote->getDistrict()); - $address->save(); + $order->save(); } catch (Exception $e) { $this->logger->error(__( - 'Can\'t set district for customer address with ID %1.', - $customerAddressId + 'Can\'t send order with increment ID %1 to giaohangnhanh.', + $order->getIncrementId() )); } + + if ($customerAddressId = $shippingAddress->getCustomerAddressId()) { + $customerAddress = $this->customerAddressFactory->create()->load($customerAddressId); + + if ($customerAddress->getId()) { + try { + $customerAddress->setData('district', $shippingAddress->getDistrict()); + $customerAddress->save(); + } catch (Exception $e) { + $this->logger->error(__( + 'Can\'t set district for customer address with ID %1.', + $customerAddressId + )); + } + } + } } } } From cfd28d83e91c6ce27f490594c9c6f76c16da9395 Mon Sep 17 00:00:00 2001 From: mrnhi Date: Tue, 7 Apr 2020 19:32:37 +0700 Subject: [PATCH 17/70] replace Magento_Checkout/js/model/shipping-rate-processor/new-address file to add district to extension_attribute. --- view/frontend/requirejs-config.js | 3 +- .../shipping-rate-processor/new-address.js | 69 +++++++++++++++++++ 2 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 view/frontend/web/js/model/shipping-rate-processor/new-address.js diff --git a/view/frontend/requirejs-config.js b/view/frontend/requirejs-config.js index f6a0185..d05a2b9 100644 --- a/view/frontend/requirejs-config.js +++ b/view/frontend/requirejs-config.js @@ -1,7 +1,8 @@ var config = { "map": { "*": { - 'Magento_Checkout/js/model/shipping-save-processor/default': 'Boolfly_GiaoHangNhanh/js/model/shipping-save-processor/default' + 'Magento_Checkout/js/model/shipping-save-processor/default': 'Boolfly_GiaoHangNhanh/js/model/shipping-save-processor/default', + 'Magento_Checkout/js/model/shipping-rate-processor/new-address': 'Boolfly_GiaoHangNhanh/js/model/shipping-rate-processor/new-address' } } }; diff --git a/view/frontend/web/js/model/shipping-rate-processor/new-address.js b/view/frontend/web/js/model/shipping-rate-processor/new-address.js new file mode 100644 index 0000000..e9f86c5 --- /dev/null +++ b/view/frontend/web/js/model/shipping-rate-processor/new-address.js @@ -0,0 +1,69 @@ +define([ + 'Magento_Checkout/js/model/resource-url-manager', + 'Magento_Checkout/js/model/quote', + 'mage/storage', + 'Magento_Checkout/js/model/shipping-service', + 'Magento_Checkout/js/model/shipping-rate-registry', + 'Magento_Checkout/js/model/error-processor' +], function (resourceUrlManager, quote, storage, shippingService, rateRegistry, errorProcessor) { + 'use strict'; + + return { + /** + * Get shipping rates for specified address. + * @param {Object} address + */ + getRates: function (address) { + var cache, serviceUrl, payload; + + shippingService.isLoading(true); + cache = rateRegistry.get(address.getCacheKey()); + serviceUrl = resourceUrlManager.getUrlForEstimationShippingMethodsForNewAddress(quote); + payload = JSON.stringify({ + address: { + 'street': address.street, + 'city': address.city, + 'region_id': address.regionId, + 'region': address.region, + 'country_id': address.countryId, + 'postcode': address.postcode, + 'email': address.email, + 'customer_id': address.customerId, + 'firstname': address.firstname, + 'lastname': address.lastname, + 'middlename': address.middlename, + 'prefix': address.prefix, + 'suffix': address.suffix, + 'vat_id': address.vatId, + 'company': address.company, + 'telephone': address.telephone, + 'fax': address.fax, + 'custom_attributes': address.customAttributes, + 'extension_attributes': { + 'checkout_fields': address.customAttributes + + }, + 'save_in_address_book': address.saveInAddressBook + } + } + ); + + if (cache) { + shippingService.setShippingRates(cache); + shippingService.isLoading(false); + } else { + storage.post( + serviceUrl, payload, false + ).done(function (result) { + rateRegistry.set(address.getCacheKey(), result); + shippingService.setShippingRates(result); + }).fail(function (response) { + shippingService.setShippingRates([]); + errorProcessor.process(response); + }).always(function () { + shippingService.isLoading(false); + }); + } + } + }; +}); From 1a3b646b2d056e222f950c64a65ae9d4d3b6fc70 Mon Sep 17 00:00:00 2001 From: mrnhi Date: Wed, 8 Apr 2020 14:18:46 +0700 Subject: [PATCH 18/70] refactor code --- Model/Carrier/GHN.php | 42 ++++++++++------------------------ Model/Carrier/GHN/Express.php | 2 +- Model/Carrier/GHN/Standard.php | 2 +- 3 files changed, 14 insertions(+), 32 deletions(-) diff --git a/Model/Carrier/GHN.php b/Model/Carrier/GHN.php index 94ed802..6edfdae 100644 --- a/Model/Carrier/GHN.php +++ b/Model/Carrier/GHN.php @@ -24,6 +24,8 @@ abstract class GHN extends AbstractCarrier implements CarrierInterface { + const SERVICE_NAME = 'GHN'; + /** * @var string */ @@ -47,27 +49,27 @@ abstract class GHN extends AbstractCarrier implements CarrierInterface /** * @var Service */ - private $restService; + protected $restService; /** * @var ServiceProvider */ - private $serviceProvider; + protected $serviceProvider; /** * @var Config */ - private $config; + protected $config; /** * @var QuoteRepository */ - private $quoteRepository; + protected $quoteRepository; /** * @var array */ - private $availableServices = []; + protected $availableServices = []; /** * GHN constructor. @@ -164,7 +166,9 @@ private function estimateShippingCost(RateRequest $request) 'ToDistrictID' => (int)$districtId ]; - if ($serviceId = $this->getAvailableService($requestBody)) { + $this->availableServices = $this->serviceProvider->getAvailableServices($requestBody); + + if ($serviceId = $this->getAvailableService()) { $requestBody['ServiceID'] = $serviceId; if ($request->getLimitCarrier()) { @@ -197,37 +201,15 @@ private function estimateShippingCost(RateRequest $request) } /** - * @param $request * @return string - * @throws Exception */ - private function getAvailableService($request) + protected function getAvailableService() { - if (empty($this->availableServices)) { - $response = $this->serviceProvider->getAvailableServices($request); - - if ($this->restService->checkResponse($response)) { - $data = $response['response_object']->data; - $this->availableServices = is_array($data) ? $data : []; - } - } - if (count($this->availableServices)) { foreach ($this->availableServices as $serviceItem) { if (!empty($serviceItem->Name)) { - switch ($this->_code) { - case Express::CODE: - $serviceType = 'Nhanh'; - break; - case Standard::CODE: - $serviceType = 'Chuẩn'; - break; - default: - $serviceType = 'Chuẩn'; - } - - if ($serviceItem->Name == $serviceType) { + if ($serviceItem->Name == static::SERVICE_NAME) { return $serviceItem->ServiceID; } } diff --git a/Model/Carrier/GHN/Express.php b/Model/Carrier/GHN/Express.php index d16f89d..045f212 100644 --- a/Model/Carrier/GHN/Express.php +++ b/Model/Carrier/GHN/Express.php @@ -6,7 +6,7 @@ class Express extends GHN { - const CODE = 'giaohangnhanh_express'; + const SERVICE_NAME = 'Nhanh'; /** * @var string diff --git a/Model/Carrier/GHN/Standard.php b/Model/Carrier/GHN/Standard.php index 67771af..f1323c8 100644 --- a/Model/Carrier/GHN/Standard.php +++ b/Model/Carrier/GHN/Standard.php @@ -6,7 +6,7 @@ class Standard extends GHN { - const CODE = 'giaohangnhanh_standard'; + const SERVICE_NAME = 'Chuẩn'; /** * @var string From aaf5db6bbd36e95eb8cd3587aaf0f725ddfa3d6f Mon Sep 17 00:00:00 2001 From: mrnhi Date: Wed, 8 Apr 2020 19:28:51 +0700 Subject: [PATCH 19/70] refactor Model/Api/Rest/Service.php class --- Model/Api/Rest/Service.php | 110 +++++++++++++------------------------ 1 file changed, 38 insertions(+), 72 deletions(-) diff --git a/Model/Api/Rest/Service.php b/Model/Api/Rest/Service.php index 5650cbc..6a27987 100644 --- a/Model/Api/Rest/Service.php +++ b/Model/Api/Rest/Service.php @@ -3,109 +3,75 @@ namespace Boolfly\GiaoHangNhanh\Model\Api\Rest; use Exception; -use GuzzleHttp\Client; -use GuzzleHttp\Exception\BadResponseException; -use Psr\Http\Message\ResponseInterface; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\HTTP\ZendClientFactory; +use Magento\Framework\Serialize\SerializerInterface; use Psr\Log\LoggerInterface; -use Zend\Json\Json; +use Zend_Http_Client; +use Zend_Http_Client_Exception; +use Zend_Http_Response; class Service { /** - * post - */ - const POST = 'post'; - - /** - * get - */ - const GET = 'get'; - - /** - * put - */ - const PUT = 'put'; - - /** - * patch - */ - const PATCH = 'patch'; - - /** - * delete + * @var LoggerInterface $log */ - const DELETE = 'delete'; + private $log; /** - * @var Client + * @var SerializerInterface */ - private $client; + protected $serializer; /** - * @var LoggerInterface $log + * @var ZendClientFactory */ - private $log; + protected $httpClientFactory; /** * Service constructor. * @param LoggerInterface $log + * @param SerializerInterface $serializer + * @param ZendClientFactory $httpClientFactory */ public function __construct( - LoggerInterface $log + LoggerInterface $log, + SerializerInterface $serializer, + ZendClientFactory $httpClientFactory ) { $this->log = $log; - $this->client = new Client(); + $this->serializer = $serializer; + $this->httpClientFactory = $httpClientFactory; } /** * @param $url - * @param array $options + * @param array $rawData * @param string $method - * @return array|ResponseInterface - * @throws Exception + * @return mixed|Zend_Http_Response + * @throws LocalizedException + * @throws Zend_Http_Client_Exception */ - public function makeRequest($url, $options = [], $method = self::POST) + public function makeRequest($url, $rawData = [], $method = Zend_Http_Client::POST) { - $response = [ - 'is_successful' => false - ]; + $client = $this->httpClientFactory->create(); + $client->setUri($url); + $client->setConfig(['maxredirects' => 0, 'timeout' => 60]); + $client->setRawData($this->serializer->serialize($rawData)); + $client->setMethod($method); + try { - /** @var ResponseInterface $response */ - $response = $this->client->$method($url, $options); - $response = $this->processResponse($response); - $response['is_successful'] = true; - } catch (BadResponseException $e) { - $this->log->error('Bad Response: ' . $e->getMessage()); - $this->log->error((string)$e->getRequest()->getBody()); - $response['response_status_code'] = $e->getCode(); - $response['response_status_message'] = $e->getMessage(); + $response = $client->request(); $response = $this->processResponse($response); - if ($e->hasResponse()) { - $errorResponse = $e->getResponse(); - $this->log->error($errorResponse->getStatusCode() . ' ' . $errorResponse->getReasonPhrase()); - try { - $body = $this->processResponse($errorResponse); - } catch (Exception $e) { - $this->log->error('Exception: ' . $e->getMessage()); - $response['exception_code'] = $e->getCode(); - } - $response = array_merge($response, $body); - } - $response['exception_code'] = $e->getCode(); + return $response; } catch (Exception $e) { - $this->log->error('Exception: ' . $e->getMessage()); - $response['exception_code'] = $e->getCode(); + throw new LocalizedException(__('The transaction details are unavailable. Please try again later.')); } - - return $response; } /** - * Process the response and return an array - * - * @param ResponseInterface|array $response - * @return array - * @throws Exception + * @param Zend_Http_Response $response + * @return mixed */ private function processResponse($response) { @@ -114,14 +80,14 @@ private function processResponse($response) } try { - $body = Json::decode((string)$response->getBody()); + $body = $this->serializer->unserialize((string)$response->getBody()); } catch (Exception $e) { $body = $e->getMessage(); } $data['response_object'] = $body; - $data['response_status_code'] = $response->getStatusCode(); - $data['response_status_message'] = $response->getReasonPhrase(); + $data['response_status_code'] = $response->getStatus(); + $data['response_status_message'] = $response->getMessage(); return $data; } From 83c37ab8c96ea47c44f4a350d64cc45e3c323bf1 Mon Sep 17 00:00:00 2001 From: mrnhi Date: Wed, 8 Apr 2020 19:33:45 +0700 Subject: [PATCH 20/70] refactor classes which are affected by changing code in Service class --- Console/GenerateRegionCommand.php | 10 +++--- Model/Carrier/GHN.php | 15 +++------ Model/DistrictProvider.php | 12 +++---- Model/Order/Processor.php | 54 +++++++++++++++---------------- Model/ServiceProvider.php | 29 +++++++++++------ 5 files changed, 59 insertions(+), 61 deletions(-) diff --git a/Console/GenerateRegionCommand.php b/Console/GenerateRegionCommand.php index 8bf1886..6e081a0 100644 --- a/Console/GenerateRegionCommand.php +++ b/Console/GenerateRegionCommand.php @@ -73,20 +73,20 @@ protected function execute(InputInterface $input, OutputInterface $output) if (true === $this->service->checkResponse($response)) { $output->writeln('Generating data. Please wait...'); $responseObject = $response['response_object']; - $data = empty($responseObject->data) ? null : $responseObject->data; + $data = empty($responseObject['data']) ? null : $responseObject['data']; if ($data && is_array($data)) { foreach ($data as $item) { - $provinceId = $item->ProvinceID; + $provinceId = $item['ProvinceID']; $region = $this->regionFactory->create() ->loadByCode($provinceId, 'VN'); $this->insertData( 'boolfly_giaohangnhanh_district', [ - 'district_id' => $item->DistrictID, + 'district_id' => $item['DistrictID'], 'province_id' => $provinceId, - 'district_name' => $item->DistrictName + 'district_name' => $item['DistrictName'] ] ); @@ -96,7 +96,7 @@ protected function execute(InputInterface $input, OutputInterface $output) [ 'country_id' => 'VN', 'code' => $provinceId, - 'default_name' => $item->ProvinceName + 'default_name' => $item['ProvinceName'] ] ); } diff --git a/Model/Carrier/GHN.php b/Model/Carrier/GHN.php index 6edfdae..db5fd52 100644 --- a/Model/Carrier/GHN.php +++ b/Model/Carrier/GHN.php @@ -183,16 +183,11 @@ private function estimateShippingCost(RateRequest $request) $response = $this->restService->makeRequest( $this->config->getCalculatingFeeUrl(), - [ - 'headers' => [ - 'Content-Type' => 'application/json' - ], - 'json' => $requestBody - ] + $requestBody ); if ($this->restService->checkResponse($response)) { - return $response['response_object']->data->CalculatedFee; + return $response['response_object']['data']['CalculatedFee']; } } } @@ -207,10 +202,10 @@ protected function getAvailableService() { if (count($this->availableServices)) { foreach ($this->availableServices as $serviceItem) { - if (!empty($serviceItem->Name)) { + if (!empty($serviceItem['Name'])) { - if ($serviceItem->Name == static::SERVICE_NAME) { - return $serviceItem->ServiceID; + if ($serviceItem['Name'] == static::SERVICE_NAME) { + return $serviceItem['ServiceID']; } } } diff --git a/Model/DistrictProvider.php b/Model/DistrictProvider.php index ed54d65..37d3f68 100644 --- a/Model/DistrictProvider.php +++ b/Model/DistrictProvider.php @@ -48,14 +48,10 @@ public function __construct( */ public function getDistrictList() { - $data = [ - 'headers' => [ - 'Content-Type' => 'application/json' - ], - 'json' => ['token' => $this->config->getApiToken()] - ]; - - return $this->apiService->makeRequest($this->config->getGettingDistrictsUrl(), $data); + return $this->apiService->makeRequest( + $this->config->getGettingDistrictsUrl(), + ['token' => $this->config->getApiToken()] + ); } /** diff --git a/Model/Order/Processor.php b/Model/Order/Processor.php index c766ecc..5a030fd 100644 --- a/Model/Order/Processor.php +++ b/Model/Order/Processor.php @@ -5,12 +5,14 @@ use Boolfly\GiaoHangNhanh\Model\Api\Rest\Service; use Boolfly\GiaoHangNhanh\Model\Config; use Exception; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\NoSuchEntityException; use Magento\Quote\Model\Quote\AddressFactory; use Magento\Sales\Model\Order; use Magento\Store\Model\Information; use Magento\Store\Model\StoreManagerInterface; use Psr\Http\Message\ResponseInterface; +use Zend_Http_Client_Exception; class Processor { @@ -66,6 +68,8 @@ public function __construct( * @param array $additionalData * @return array|ResponseInterface * @throws NoSuchEntityException + * @throws LocalizedException + * @throws Zend_Http_Client_Exception */ public function syncOrder(Order $order, $additionalData) { @@ -75,36 +79,30 @@ public function syncOrder(Order $order, $additionalData) $storeInfo = $this->storeInformation->getStoreInformationObject($store); $storeFormattedAddress = $this->storeInformation->getFormattedAddress($store); $storeDistrict = (int)$config->getStoreDistrict(); - $address = $this->addressFactory->create()->load($order->getQuoteAddressId()); $data = [ - 'headers' => [ - 'Content-Type' => 'application/json' - ], - 'json' => [ - 'token' => $config->getApiToken(), - 'PaymentTypeID' => $config->getPaymentType(), - 'FromDistrictID' => $storeDistrict, - 'ToDistrictID' => (int)$additionalData['district'], - 'ClientContactName' => $storeInfo->getName(), - 'ClientContactPhone' => $storeInfo->getPhone(), - 'ClientAddress' => $storeFormattedAddress, - 'CustomerName' => $order->getCustomerName(), - 'CustomerPhone' => $order->getShippingAddress()->getTelephone(), - 'ShippingAddress' => $order->getShippingAddress()->getStreetLine(1), - 'NoteCode' => $config->getNoteCode(), - 'ServiceID' => $additionalData['shipping_service_id'], - 'Weight' => $order->getWeight() * $weightRate, - 'Length' => 10, - 'Width' => 10, - 'Height' => 10, - 'CoDAmount' => 0, - 'ReturnContactName' => $storeInfo->getName(), - 'ReturnContactPhone' => $storeInfo->getPhone(), - 'ReturnAddress' => $storeFormattedAddress, - 'ReturnDistrictID' => $storeDistrict, - 'ExternalReturnCode' => $storeInfo->getName() - ] + 'token' => $config->getApiToken(), + 'PaymentTypeID' => (int)$config->getPaymentType(), + 'FromDistrictID' => $storeDistrict, + 'ToDistrictID' => (int)$additionalData['district'], + 'ClientContactName' => $storeInfo->getName(), + 'ClientContactPhone' => $storeInfo->getPhone(), + 'ClientAddress' => $storeFormattedAddress, + 'CustomerName' => $order->getCustomerName(), + 'CustomerPhone' => $order->getShippingAddress()->getTelephone(), + 'ShippingAddress' => $order->getShippingAddress()->getStreetLine(1), + 'NoteCode' => $config->getNoteCode(), + 'ServiceID' => $additionalData['shipping_service_id'], + 'Weight' => $order->getWeight() * $weightRate, + 'Length' => 10, + 'Width' => 10, + 'Height' => 10, + 'CoDAmount' => 0, + 'ReturnContactName' => $storeInfo->getName(), + 'ReturnContactPhone' => $storeInfo->getPhone(), + 'ReturnAddress' => $storeFormattedAddress, + 'ReturnDistrictID' => $storeDistrict, + 'ExternalReturnCode' => $storeInfo->getName() ]; return $this->apiService->makeRequest($config->getSynchronizingOrderUrl(), $data); diff --git a/Model/ServiceProvider.php b/Model/ServiceProvider.php index 7d76b0e..3a94d9d 100644 --- a/Model/ServiceProvider.php +++ b/Model/ServiceProvider.php @@ -4,7 +4,10 @@ use Boolfly\GiaoHangNhanh\Model\Api\Rest\Service; use Exception; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Exception\NoSuchEntityException; use Psr\Http\Message\ResponseInterface; +use Zend_Http_Client_Exception; class ServiceProvider { @@ -33,18 +36,24 @@ public function __construct( /** * @param $request - * @return array|ResponseInterface - * @throws Exception + * @return array + * @throws NoSuchEntityException + * @throws Zend_Http_Client_Exception + * @throws LocalizedException */ public function getAvailableServices($request) { - $data = [ - 'headers' => [ - 'Content-Type' => 'application/json' - ], - 'json' => $request - ]; - - return $this->apiService->makeRequest($this->config->getGettingServicesUrl(), $data); + $response = $this->apiService->makeRequest($this->config->getGettingServicesUrl(), $request); + $availableServices = []; + + if ($this->apiService->checkResponse($response)) { + $data = $response['response_object']['data']; + + if (is_array($data)) { + $availableServices = $data; + } + } + + return $availableServices; } } From 2dfd7eb73d38d3b3d7af07b3762ff5d71203535e Mon Sep 17 00:00:00 2001 From: mrnhi Date: Wed, 8 Apr 2020 19:37:00 +0700 Subject: [PATCH 21/70] replace event sales_order_save_after by sales_order_place_after --- ...Observer.php => SalesOrderPlaceAfterSObserver.php} | 11 +---------- etc/events.xml | 4 ++-- 2 files changed, 3 insertions(+), 12 deletions(-) rename Observer/{SalesOrderAfterSaveObserver.php => SalesOrderPlaceAfterSObserver.php} (90%) diff --git a/Observer/SalesOrderAfterSaveObserver.php b/Observer/SalesOrderPlaceAfterSObserver.php similarity index 90% rename from Observer/SalesOrderAfterSaveObserver.php rename to Observer/SalesOrderPlaceAfterSObserver.php index 2fbdd5a..4e02efa 100644 --- a/Observer/SalesOrderAfterSaveObserver.php +++ b/Observer/SalesOrderPlaceAfterSObserver.php @@ -12,7 +12,7 @@ use Magento\Quote\Model\QuoteRepository; use Psr\Log\LoggerInterface; -class SalesOrderAfterSaveObserver implements ObserverInterface +class SalesOrderPlaceAfterSObserver implements ObserverInterface { const GHN_STATUS_FAIL = 0; const GHN_STATUS_SUCCESS = 1; @@ -87,15 +87,6 @@ public function execute(Observer $observer) $order->setData('ghn_status', self::GHN_STATUS_FAIL); } - try { - $order->save(); - } catch (Exception $e) { - $this->logger->error(__( - 'Can\'t send order with increment ID %1 to giaohangnhanh.', - $order->getIncrementId() - )); - } - if ($customerAddressId = $shippingAddress->getCustomerAddressId()) { $customerAddress = $this->customerAddressFactory->create()->load($customerAddressId); diff --git a/etc/events.xml b/etc/events.xml index c0012b5..3c493ec 100644 --- a/etc/events.xml +++ b/etc/events.xml @@ -1,6 +1,6 @@ - - + + \ No newline at end of file From 5f0ef6ad2fa1f271d7a4dc680eb9623b8d0c2f76 Mon Sep 17 00:00:00 2001 From: mrnhi Date: Wed, 8 Apr 2020 19:41:19 +0700 Subject: [PATCH 22/70] Add custom shipping carrier validations --- view/frontend/layout/checkout_index_index.xml | 14 ++++++++ view/frontend/requirejs-config.js | 11 +++++-- .../web/js/form/element/region-mixin.js | 26 +++++++++++++++ .../model/shipping-rates-validation-rules.js | 22 +++++++++++++ .../web/js/model/shipping-rates-validator.js | 33 +++++++++++++++++++ .../web/js/view/shipping-rates-validation.js | 22 +++++++++++++ 6 files changed, 126 insertions(+), 2 deletions(-) create mode 100644 view/frontend/web/js/form/element/region-mixin.js create mode 100644 view/frontend/web/js/model/shipping-rates-validation-rules.js create mode 100755 view/frontend/web/js/model/shipping-rates-validator.js create mode 100755 view/frontend/web/js/view/shipping-rates-validation.js diff --git a/view/frontend/layout/checkout_index_index.xml b/view/frontend/layout/checkout_index_index.xml index f64728b..4c69623 100644 --- a/view/frontend/layout/checkout_index_index.xml +++ b/view/frontend/layout/checkout_index_index.xml @@ -26,6 +26,20 @@ + + + + + + Boolfly_GiaoHangNhanh/js/view/shipping-rates-validation + + + Boolfly_GiaoHangNhanh/js/view/shipping-rates-validation + + + + + diff --git a/view/frontend/requirejs-config.js b/view/frontend/requirejs-config.js index d05a2b9..cfa767e 100644 --- a/view/frontend/requirejs-config.js +++ b/view/frontend/requirejs-config.js @@ -1,8 +1,15 @@ var config = { - "map": { + map: { "*": { 'Magento_Checkout/js/model/shipping-save-processor/default': 'Boolfly_GiaoHangNhanh/js/model/shipping-save-processor/default', 'Magento_Checkout/js/model/shipping-rate-processor/new-address': 'Boolfly_GiaoHangNhanh/js/model/shipping-rate-processor/new-address' } + }, + config: { + mixins: { + 'Magento_Ui/js/form/element/region': { + 'Boolfly_GiaoHangNhanh/js/form/element/region-mixin': true + } + } } -}; +}; \ No newline at end of file diff --git a/view/frontend/web/js/form/element/region-mixin.js b/view/frontend/web/js/form/element/region-mixin.js new file mode 100644 index 0000000..d14daff --- /dev/null +++ b/view/frontend/web/js/form/element/region-mixin.js @@ -0,0 +1,26 @@ +define(['jquery'], function ($) { + 'use strict'; + + var mixin = { + + /** + * @param {String} value + */ + update: function (value) { + this._super(); + let districtField = $('[name="custom_attributes[district]"]'); + + if (value !== 'VN') { + districtField.hide(); + } else { + if (districtField.is(":hidden")) { + districtField.show(); + } + } + } + }; + + return function (target) { + return target.extend(mixin); + }; +}); \ No newline at end of file diff --git a/view/frontend/web/js/model/shipping-rates-validation-rules.js b/view/frontend/web/js/model/shipping-rates-validation-rules.js new file mode 100644 index 0000000..fc1b88d --- /dev/null +++ b/view/frontend/web/js/model/shipping-rates-validation-rules.js @@ -0,0 +1,22 @@ +define([], function () { + 'use strict'; + + return { + /** + * @return {Object} + */ + getRules: function () { + return { + 'country_id': { + 'required': true + }, + 'region_id': { + 'required': true + }, + 'district': { + 'required': true + } + }; + } + }; +}); diff --git a/view/frontend/web/js/model/shipping-rates-validator.js b/view/frontend/web/js/model/shipping-rates-validator.js new file mode 100755 index 0000000..71d60af --- /dev/null +++ b/view/frontend/web/js/model/shipping-rates-validator.js @@ -0,0 +1,33 @@ +define([ + 'jquery', + 'mageUtils', + 'Boolfly_GiaoHangNhanh/js/model/shipping-rates-validation-rules', + 'mage/translate' +], function ($, utils, validationRules, $t) { + 'use strict'; + + return { + validationErrors: [], + + /** + * @param {Object} address + * @return {Boolean} + */ + validate: function (address) { + var self = this; + + this.validationErrors = []; + $.each(validationRules.getRules(), function (field, rule) { + var message; + + if (rule.required && utils.isEmpty(address[field])) { + message = $t('Field ') + field + $t(' is required.'); + + self.validationErrors.push(message); + } + }); + + return !this.validationErrors.length; + } + }; +}); diff --git a/view/frontend/web/js/view/shipping-rates-validation.js b/view/frontend/web/js/view/shipping-rates-validation.js new file mode 100755 index 0000000..9488e80 --- /dev/null +++ b/view/frontend/web/js/view/shipping-rates-validation.js @@ -0,0 +1,22 @@ +define([ + 'uiComponent', + 'Magento_Checkout/js/model/shipping-rates-validator', + 'Magento_Checkout/js/model/shipping-rates-validation-rules', + 'Boolfly_GiaoHangNhanh/js/model/shipping-rates-validator', + 'Boolfly_GiaoHangNhanh/js/model/shipping-rates-validation-rules' +], function ( + Component, + defaultShippingRatesValidator, + defaultShippingRatesValidationRules, + ghnShippingRatesValidator, + ghnShippingRatesValidationRules +) { + 'use strict'; + + defaultShippingRatesValidator.registerValidator('giaohangnhanh_express', ghnShippingRatesValidator); + defaultShippingRatesValidationRules.registerRules('giaohangnhanh_express', ghnShippingRatesValidationRules); + defaultShippingRatesValidator.registerValidator('giaohangnhanh_standard', ghnShippingRatesValidator); + defaultShippingRatesValidationRules.registerRules('giaohangnhanh_standard', ghnShippingRatesValidationRules); + + return Component; +}); From 50b20bb056c15abbcf5a3655c42ea2a473a6c44b Mon Sep 17 00:00:00 2001 From: mrnhi Date: Wed, 8 Apr 2020 19:43:07 +0700 Subject: [PATCH 23/70] refactor code --- Model/Config.php | 2 +- Plugin/Checkout/Block/Checkout/LayoutProcessor.php | 2 +- Plugin/Quote/Model/EstimateByExtendedAddressBefore.php | 10 ++++++---- .../frontend/web/js/view/checkout/shipping/district.js | 9 --------- 4 files changed, 8 insertions(+), 15 deletions(-) diff --git a/Model/Config.php b/Model/Config.php index 3d1aa57..a6863ca 100644 --- a/Model/Config.php +++ b/Model/Config.php @@ -19,7 +19,7 @@ class Config const NAME = 'name'; const SALLOWSPECIFIC = 'sallowspecific'; const API_TOKEN = 'carriers/giaohangnhanh_standard/api_token'; - const PAYMENT_TYPE = 'payment_type'; + const PAYMENT_TYPE = 'carriers/giaohangnhanh_standard/payment_type'; const CALCULATING_FEE_URL = 'carriers/giaohangnhanh_standard/calculate_fee_url'; const SYNCHRONIZING_ORDER_URL = 'carriers/giaohangnhanh_standard/sync_order_url'; const GETTING_DISTRICTS_URL = 'carriers/giaohangnhanh_standard/get_districts_url'; diff --git a/Plugin/Checkout/Block/Checkout/LayoutProcessor.php b/Plugin/Checkout/Block/Checkout/LayoutProcessor.php index 1d97444..5f5adc9 100644 --- a/Plugin/Checkout/Block/Checkout/LayoutProcessor.php +++ b/Plugin/Checkout/Block/Checkout/LayoutProcessor.php @@ -21,7 +21,7 @@ public function afterProcess(MageLayoutProcessor $subject, $result) 'label' => __('District'), 'provider' => 'checkoutProvider', 'visible' => true, - 'validation' => ['required-entry' => true], + 'validation' => ['required-entry' => false], 'sortOrder' => 255, 'id' => 'district', 'options' => [ diff --git a/Plugin/Quote/Model/EstimateByExtendedAddressBefore.php b/Plugin/Quote/Model/EstimateByExtendedAddressBefore.php index 504785d..58a1db8 100644 --- a/Plugin/Quote/Model/EstimateByExtendedAddressBefore.php +++ b/Plugin/Quote/Model/EstimateByExtendedAddressBefore.php @@ -40,10 +40,12 @@ public function beforeEstimateByExtendedAddress( $checkoutFields = $address->getExtensionAttributes()->getCheckoutFields(); $district = ''; - foreach ($checkoutFields as $field) { - if ($field->getAttributeCode() == 'district') { - $district = $field->getValue(); - break; + if ($checkoutFields) { + foreach ($checkoutFields as $field) { + if ($field->getAttributeCode() == 'district') { + $district = $field->getValue(); + break; + } } } diff --git a/view/frontend/web/js/view/checkout/shipping/district.js b/view/frontend/web/js/view/checkout/shipping/district.js index a6f388e..8104881 100644 --- a/view/frontend/web/js/view/checkout/shipping/district.js +++ b/view/frontend/web/js/view/checkout/shipping/district.js @@ -14,15 +14,6 @@ define([ } }, - initialize: function () { - this._super(); - let district = $('[name="custom_attributes[district]"]'); - district.on('change', function() { - alert('kkk'); - }); - - }, - update: function (value) { let district = $('[name="custom_attributes[district]"]'); let districtList = checkoutConfigDistricts[parseInt(value)]; From e182153ff5353694def65b66349006a330ed0268 Mon Sep 17 00:00:00 2001 From: mrnhi Date: Tue, 14 Apr 2020 11:52:11 +0700 Subject: [PATCH 24/70] refactor code --- Console/GenerateRegionCommand.php | 63 ++++++++----------- Model/Carrier/GHN.php | 28 +++++---- Model/DistrictProvider.php | 40 +++++------- Model/Order/Processor.php | 9 +-- Model/ServiceProvider.php | 59 ----------------- Observer/SalesOrderPlaceAfterSObserver.php | 15 +---- .../Model/ShippingInformationManagement.php | 18 +++--- .../Quote/Model/EstimateByAddressIdBefore.php | 19 +++--- Setup/InstallData.php | 25 +++++++- 9 files changed, 112 insertions(+), 164 deletions(-) delete mode 100644 Model/ServiceProvider.php diff --git a/Console/GenerateRegionCommand.php b/Console/GenerateRegionCommand.php index 6e081a0..d97f3b4 100644 --- a/Console/GenerateRegionCommand.php +++ b/Console/GenerateRegionCommand.php @@ -2,22 +2,18 @@ namespace Boolfly\GiaoHangNhanh\Console; -use Boolfly\GiaoHangNhanh\Model\Api\Rest\Service; use Boolfly\GiaoHangNhanh\Model\DistrictProvider; use Magento\Directory\Model\RegionFactory; use Magento\Framework\App\ResourceConnection; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\NoSuchEntityException; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; +use Zend_Http_Client_Exception; class GenerateRegionCommand extends Command { - /** - * @var Service - */ - private $service; - /** * @var ResourceConnection */ @@ -35,20 +31,17 @@ class GenerateRegionCommand extends Command /** * GeneratingRegionData constructor. - * @param Service $service * @param ResourceConnection $resourceConnection * @param RegionFactory $regionFactory * @param DistrictProvider $districtProvider * @param string|null $name */ public function __construct( - Service $service, ResourceConnection $resourceConnection, RegionFactory $regionFactory, DistrictProvider $districtProvider, $name = null ) { - $this->service = $service; $this->resourceConnection = $resourceConnection; $this->regionFactory = $regionFactory; $this->districtProvider = $districtProvider; @@ -66,45 +59,43 @@ protected function configure() * @param OutputInterface $output * @return int|void|null * @throws NoSuchEntityException + * @throws LocalizedException + * @throws Zend_Http_Client_Exception */ protected function execute(InputInterface $input, OutputInterface $output) { - $response = $this->districtProvider->getDistrictList(); - if (true === $this->service->checkResponse($response)) { + $data = $this->districtProvider->getDistrictList(); + + if ($data) { $output->writeln('Generating data. Please wait...'); - $responseObject = $response['response_object']; - $data = empty($responseObject['data']) ? null : $responseObject['data']; + foreach ($data as $item) { + $provinceId = $item['ProvinceID']; + $region = $this->regionFactory->create() + ->loadByCode($provinceId, 'VN'); - if ($data && is_array($data)) { - foreach ($data as $item) { - $provinceId = $item['ProvinceID']; - $region = $this->regionFactory->create() - ->loadByCode($provinceId, 'VN'); + $this->insertData( + 'boolfly_giaohangnhanh_district', + [ + 'district_id' => $item['DistrictID'], + 'province_id' => $provinceId, + 'district_name' => $item['DistrictName'] + ] + ); + if (!$region->getId()) { $this->insertData( - 'boolfly_giaohangnhanh_district', + 'directory_country_region', [ - 'district_id' => $item['DistrictID'], - 'province_id' => $provinceId, - 'district_name' => $item['DistrictName'] + 'country_id' => 'VN', + 'code' => $provinceId, + 'default_name' => $item['ProvinceName'] ] ); - - if (!$region->getId()) { - $this->insertData( - 'directory_country_region', - [ - 'country_id' => 'VN', - 'code' => $provinceId, - 'default_name' => $item['ProvinceName'] - ] - ); - } } - $output->writeln('Generate data successfully.'); - } else { - $output->writeln('Generating data was interrupted. Please try again!'); } + $output->writeln('Generate data successfully.'); + } else { + $output->writeln('Generating data was interrupted. Please try again!'); } } diff --git a/Model/Carrier/GHN.php b/Model/Carrier/GHN.php index db5fd52..85b3039 100644 --- a/Model/Carrier/GHN.php +++ b/Model/Carrier/GHN.php @@ -3,9 +3,6 @@ namespace Boolfly\GiaoHangNhanh\Model\Carrier; use Boolfly\GiaoHangNhanh\Model\Api\Rest\Service; -use Boolfly\GiaoHangNhanh\Model\Carrier\GHN\Express; -use Boolfly\GiaoHangNhanh\Model\Carrier\GHN\Standard; -use Boolfly\GiaoHangNhanh\Model\ServiceProvider; use Exception; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\NoSuchEntityException; @@ -51,11 +48,6 @@ abstract class GHN extends AbstractCarrier implements CarrierInterface */ protected $restService; - /** - * @var ServiceProvider - */ - protected $serviceProvider; - /** * @var Config */ @@ -79,7 +71,6 @@ abstract class GHN extends AbstractCarrier implements CarrierInterface * @param ResultFactory $rateResultFactory * @param MethodFactory $rateMethodFactory * @param Service $restService - * @param ServiceProvider $serviceProvider * @param Config $config * @param QuoteRepository $quoteRepository * @param array $data @@ -91,7 +82,6 @@ public function __construct( ResultFactory $rateResultFactory, MethodFactory $rateMethodFactory, Service $restService, - ServiceProvider $serviceProvider, Config $config, QuoteRepository $quoteRepository, array $data = [] @@ -100,7 +90,6 @@ public function __construct( $this->rateResultFactory = $rateResultFactory; $this->rateMethodFactory = $rateMethodFactory; $this->restService = $restService; - $this->serviceProvider = $serviceProvider; $this->config = $config; $this->quoteRepository = $quoteRepository; } @@ -149,7 +138,7 @@ public function getAllowedMethods() * @throws LocalizedException * @throws Exception */ - private function estimateShippingCost(RateRequest $request) + protected function estimateShippingCost(RateRequest $request) { $quote = $this->quoteRepository->getActive( $request->getAllItems()[0]->getQuoteId() @@ -166,7 +155,7 @@ private function estimateShippingCost(RateRequest $request) 'ToDistrictID' => (int)$districtId ]; - $this->availableServices = $this->serviceProvider->getAvailableServices($requestBody); + $this->prepareServices($requestBody); if ($serviceId = $this->getAvailableService()) { $requestBody['ServiceID'] = $serviceId; @@ -195,6 +184,19 @@ private function estimateShippingCost(RateRequest $request) return null; } + protected function prepareServices($request) + { + $response = $this->restService->makeRequest($this->config->getGettingServicesUrl(), $request); + + if ($this->restService->checkResponse($response)) { + $data = $response['response_object']['data']; + + if (is_array($data)) { + $this->availableServices = $data; + } + } + } + /** * @return string */ diff --git a/Model/DistrictProvider.php b/Model/DistrictProvider.php index 37d3f68..c989c71 100644 --- a/Model/DistrictProvider.php +++ b/Model/DistrictProvider.php @@ -4,9 +4,10 @@ use Boolfly\GiaoHangNhanh\Model\Api\Rest\Service; use Exception; -use Magento\Customer\Model\AddressFactory; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\NoSuchEntityException; use Psr\Http\Message\ResponseInterface; +use Zend_Http_Client_Exception; class DistrictProvider { @@ -20,52 +21,43 @@ class DistrictProvider */ private $config; - /** - * @var AddressFactory - */ - private $customerAddressFactory; - /** * DistrictProvider constructor. * @param Service $apiService * @param Config $config - * @param AddressFactory $customerAddressFactory */ public function __construct( Service $apiService, - Config $config, - AddressFactory $customerAddressFactory + Config $config ) { $this->apiService = $apiService; $this->config = $config; - $this->customerAddressFactory = $customerAddressFactory; } /** - * @return array|ResponseInterface + * @return array * @throws NoSuchEntityException - * @throws Exception + * @throws LocalizedException + * @throws Zend_Http_Client_Exception */ public function getDistrictList() { - return $this->apiService->makeRequest( + $data = []; + $response = $this->apiService->makeRequest( $this->config->getGettingDistrictsUrl(), ['token' => $this->config->getApiToken()] ); - } - /** - * @param int $customerAddressId - * @return string - */ - public function getDistrictByCustomerAddressId($customerAddressId) - { - $address = $this->customerAddressFactory->create()->load($customerAddressId); + if ($this->apiService->checkResponse($response)) { + $responseObject = $response['response_object']; - if (!$address->getId()) { - return ''; + if (!empty($responseObject['data'])) { + if (is_array($responseObject['data'])) { + $data = $responseObject['data']; + } + } } - return $address->getDistrict() ?: ''; + return $data; } } diff --git a/Model/Order/Processor.php b/Model/Order/Processor.php index 5a030fd..ff4663d 100644 --- a/Model/Order/Processor.php +++ b/Model/Order/Processor.php @@ -4,7 +4,6 @@ use Boolfly\GiaoHangNhanh\Model\Api\Rest\Service; use Boolfly\GiaoHangNhanh\Model\Config; -use Exception; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\NoSuchEntityException; use Magento\Quote\Model\Quote\AddressFactory; @@ -66,9 +65,9 @@ public function __construct( /** * @param Order $order * @param array $additionalData - * @return array|ResponseInterface - * @throws NoSuchEntityException + * @return bool * @throws LocalizedException + * @throws NoSuchEntityException * @throws Zend_Http_Client_Exception */ public function syncOrder(Order $order, $additionalData) @@ -105,6 +104,8 @@ public function syncOrder(Order $order, $additionalData) 'ExternalReturnCode' => $storeInfo->getName() ]; - return $this->apiService->makeRequest($config->getSynchronizingOrderUrl(), $data); + $response = $this->apiService->makeRequest($config->getSynchronizingOrderUrl(), $data); + + return $this->apiService->checkResponse($response); } } diff --git a/Model/ServiceProvider.php b/Model/ServiceProvider.php deleted file mode 100644 index 3a94d9d..0000000 --- a/Model/ServiceProvider.php +++ /dev/null @@ -1,59 +0,0 @@ -apiService = $apiService; - $this->config = $config; - } - - /** - * @param $request - * @return array - * @throws NoSuchEntityException - * @throws Zend_Http_Client_Exception - * @throws LocalizedException - */ - public function getAvailableServices($request) - { - $response = $this->apiService->makeRequest($this->config->getGettingServicesUrl(), $request); - $availableServices = []; - - if ($this->apiService->checkResponse($response)) { - $data = $response['response_object']['data']; - - if (is_array($data)) { - $availableServices = $data; - } - } - - return $availableServices; - } -} diff --git a/Observer/SalesOrderPlaceAfterSObserver.php b/Observer/SalesOrderPlaceAfterSObserver.php index 4e02efa..bde700b 100644 --- a/Observer/SalesOrderPlaceAfterSObserver.php +++ b/Observer/SalesOrderPlaceAfterSObserver.php @@ -2,7 +2,6 @@ namespace Boolfly\GiaoHangNhanh\Observer; -use Boolfly\GiaoHangNhanh\Model\Api\Rest\Service; use Boolfly\GiaoHangNhanh\Model\Config; use Boolfly\GiaoHangNhanh\Model\Order\Processor; use Exception; @@ -37,28 +36,20 @@ class SalesOrderPlaceAfterSObserver implements ObserverInterface */ private $orderProcessor; - /** - * @var Service - */ - private $apiService; - /** * SalesOrderAfterSaveObserver constructor. * @param QuoteRepository $quoteRepository * @param AddressFactory $customerAddressFactory * @param LoggerInterface $logger * @param Processor $orderProcessor - * @param Service $apiService */ public function __construct( QuoteRepository $quoteRepository, AddressFactory $customerAddressFactory, LoggerInterface $logger, - Processor $orderProcessor, - Service $apiService + Processor $orderProcessor ) { $this->logger = $logger; - $this->apiService = $apiService; $this->quoteRepository = $quoteRepository; $this->orderProcessor = $orderProcessor; $this->customerAddressFactory = $customerAddressFactory; @@ -79,9 +70,9 @@ public function execute(Observer $observer) 'district' => $shippingAddress->getDistrict(), 'shipping_service_id' => $shippingAddress->getShippingServiceId() ]; - $response = $this->orderProcessor->syncOrder($order, $additionalData); + $result = $this->orderProcessor->syncOrder($order, $additionalData); - if (true === $this->apiService->checkResponse($response)) { + if (true === $result) { $order->setData('ghn_status', self::GHN_STATUS_SUCCESS); } else { $order->setData('ghn_status', self::GHN_STATUS_FAIL); diff --git a/Plugin/Checkout/Model/ShippingInformationManagement.php b/Plugin/Checkout/Model/ShippingInformationManagement.php index 5472452..3330390 100644 --- a/Plugin/Checkout/Model/ShippingInformationManagement.php +++ b/Plugin/Checkout/Model/ShippingInformationManagement.php @@ -3,8 +3,8 @@ namespace Boolfly\GiaoHangNhanh\Plugin\Checkout\Model; use Boolfly\GiaoHangNhanh\Model\Config; -use Boolfly\GiaoHangNhanh\Model\DistrictProvider; use Magento\Checkout\Api\Data\ShippingInformationInterface; +use Magento\Customer\Model\AddressFactory; use Magento\Framework\Exception\NoSuchEntityException; use Magento\Quote\Model\QuoteRepository; use Magento\Checkout\Model\ShippingInformationManagement as MageShippingInformationManagement; @@ -17,21 +17,21 @@ class ShippingInformationManagement private $quoteRepository; /** - * @var DistrictProvider + * @var AddressFactory */ - private $districtProvider; + private $customerAddressFactory; /** * ShippingInformationManagement constructor. * @param QuoteRepository $quoteRepository - * @param DistrictProvider $districtProvider + * @param AddressFactory $customerAddressFactory */ public function __construct( QuoteRepository $quoteRepository, - DistrictProvider $districtProvider + AddressFactory $customerAddressFactory ) { $this->quoteRepository = $quoteRepository; - $this->districtProvider = $districtProvider; + $this->customerAddressFactory = $customerAddressFactory; } /** @@ -57,7 +57,11 @@ public function beforeSaveAddressInformation( if (!$extensionAttributes->getDistrict()) { if ($customerAddressId = $shippingAddress->getCustomerAddressId()) { - $district = $this->districtProvider->getDistrictByCustomerAddressId($customerAddressId); + $address = $this->customerAddressFactory->create()->load($customerAddressId); + + if ($address->getId()) { + $district = $address->getDistrict(); + } } } else { $district = $extensionAttributes->getDistrict(); diff --git a/Plugin/Quote/Model/EstimateByAddressIdBefore.php b/Plugin/Quote/Model/EstimateByAddressIdBefore.php index 05b9cbb..09f4112 100644 --- a/Plugin/Quote/Model/EstimateByAddressIdBefore.php +++ b/Plugin/Quote/Model/EstimateByAddressIdBefore.php @@ -2,7 +2,7 @@ namespace Boolfly\GiaoHangNhanh\Plugin\Quote\Model; -use Boolfly\GiaoHangNhanh\Model\DistrictProvider; +use Magento\Customer\Model\AddressFactory; use Magento\Quote\Model\ShippingMethodManagement as MageShippingMethodManagement; use Magento\Framework\Exception\NoSuchEntityException; use Magento\Quote\Model\QuoteRepository; @@ -15,21 +15,21 @@ class EstimateByAddressIdBefore private $quoteRepository; /** - * @var DistrictProvider + * @var AddressFactory */ - private $districtProvider; + private $customerAddressFactory; /** * ShippingInformationManagement constructor. * @param QuoteRepository $quoteRepository - * @param DistrictProvider $districtProvider + * @param AddressFactory $customerAddressFactory */ public function __construct( QuoteRepository $quoteRepository, - DistrictProvider $districtProvider + AddressFactory $customerAddressFactory ) { $this->quoteRepository = $quoteRepository; - $this->districtProvider = $districtProvider; + $this->customerAddressFactory = $customerAddressFactory; } /** @@ -45,7 +45,12 @@ public function beforeEstimateByAddressId( ) { /** @var \Magento\Quote\Model\Quote $quote */ $quote = $this->quoteRepository->getActive($cartId); - $district = $this->districtProvider->getDistrictByCustomerAddressId($addressId); + $address = $this->customerAddressFactory->create()->load($addressId); + $district = ''; + + if ($address->getId()) { + $district = $address->getDistrict(); + } if (!$district) { return; diff --git a/Setup/InstallData.php b/Setup/InstallData.php index b8ae24c..d9834da 100644 --- a/Setup/InstallData.php +++ b/Setup/InstallData.php @@ -4,6 +4,7 @@ use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface; use Magento\Eav\Setup\EavSetupFactory; +use Magento\Eav\Model\Config; use Magento\Framework\Setup\InstallDataInterface; use Magento\Framework\Setup\ModuleContextInterface; use Magento\Framework\Setup\ModuleDataSetupInterface; @@ -19,13 +20,22 @@ class InstallData implements InstallDataInterface */ private $eavSetupFactory; + /** + * @var Config + */ + private $eavConfig; + /** * Init * @param EavSetupFactory $eavSetupFactory + * @param Config $eavConfig */ - public function __construct(EavSetupFactory $eavSetupFactory) - { + public function __construct( + EavSetupFactory $eavSetupFactory, + Config $eavConfig + ) { $this->eavSetupFactory = $eavSetupFactory; + $this->eavConfig = $eavConfig; } /** @@ -36,6 +46,7 @@ public function __construct(EavSetupFactory $eavSetupFactory) */ public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context) { + $setup->startSetup(); $eavSetup = $this->eavSetupFactory->create(); $eavSetup->addAttribute( 'customer_address', @@ -57,5 +68,15 @@ public function install(ModuleDataSetupInterface $setup, ModuleContextInterface 'visible_on_front' => true ] ); + + $customAttribute = $this->eavConfig->getAttribute('customer_address', 'district'); + + $customAttribute->setData( + 'used_in_forms', + ['adminhtml_customer_address','customer_address_edit','customer_register_address'] + ); + $customAttribute->save(); + + $setup->endSetup(); } } From c59bd807eabd33a94b45130f7efd61bebb27a507 Mon Sep 17 00:00:00 2001 From: mrnhi Date: Tue, 14 Apr 2020 11:55:02 +0700 Subject: [PATCH 25/70] add configuration group giaohangnhanh_setting --- Model/Config.php | 17 ++++++----- etc/adminhtml/system.xml | 63 +++++++++++++++++----------------------- etc/config.xml | 24 +++++++-------- 3 files changed, 46 insertions(+), 58 deletions(-) diff --git a/Model/Config.php b/Model/Config.php index a6863ca..83610d9 100644 --- a/Model/Config.php +++ b/Model/Config.php @@ -18,14 +18,15 @@ class Config const TITLE = 'title'; const NAME = 'name'; const SALLOWSPECIFIC = 'sallowspecific'; - const API_TOKEN = 'carriers/giaohangnhanh_standard/api_token'; - const PAYMENT_TYPE = 'carriers/giaohangnhanh_standard/payment_type'; - const CALCULATING_FEE_URL = 'carriers/giaohangnhanh_standard/calculate_fee_url'; - const SYNCHRONIZING_ORDER_URL = 'carriers/giaohangnhanh_standard/sync_order_url'; - const GETTING_DISTRICTS_URL = 'carriers/giaohangnhanh_standard/get_districts_url'; - const NOTE_CODE = 'carriers/giaohangnhanh_standard/note_code'; - const DISTRICT = 'carriers/giaohangnhanh_standard/district'; - const GETTING_SERVICES_URL = 'carriers/giaohangnhanh_standard/get_services_url'; + const SPECIFICCOUNTRY = 'specificcountry'; + const API_TOKEN = 'giaohangnhanh_setting/general/api_token'; + const PAYMENT_TYPE = 'giaohangnhanh_setting/general/payment_type'; + const CALCULATING_FEE_URL = 'giaohangnhanh_setting/general/calculate_fee_url'; + const SYNCHRONIZING_ORDER_URL = 'giaohangnhanh_setting/general/sync_order_url'; + const GETTING_DISTRICTS_URL = 'giaohangnhanh_setting/general/get_districts_url'; + const NOTE_CODE = 'giaohangnhanh_setting/general/note_code'; + const DISTRICT = 'giaohangnhanh_setting/general/district'; + const GETTING_SERVICES_URL = 'giaohangnhanh_setting/general/get_services_url'; /** * @var int diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index 06adae8..156de17 100644 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -47,30 +47,6 @@ - - - - - - - - - - - - - - - Boolfly\GiaoHangNhanh\Model\Config\Source\PaymentType - - - - Boolfly\GiaoHangNhanh\Model\Config\Source\NoteCode - - - - Boolfly\GiaoHangNhanh\Model\Config\Source\District - @@ -117,33 +93,46 @@ - + + + + + +
+ separator-top + + boolfly + Boolfly_GiaoHangNhanh::config_giaohangnhanh + + + + Set token to access giaohangnhanh api. + + + + Boolfly\GiaoHangNhanh\Model\Config\Source\PaymentType - + - + - + - - - - - - Boolfly\GiaoHangNhanh\Model\Config\Source\PaymentType - - + Boolfly\GiaoHangNhanh\Model\Config\Source\NoteCode - + Boolfly\GiaoHangNhanh\Model\Config\Source\District + + +
diff --git a/etc/config.xml b/etc/config.xml index 71aff89..cff19ec 100644 --- a/etc/config.xml +++ b/etc/config.xml @@ -1,6 +1,17 @@ + + + TokenStaging + 2 + https://dev-online-gateway.ghn.vn/apiv3-api/api/v1/apiv3/CalculateFee + https://dev-online-gateway.ghn.vn/apiv3-api/api/v1/apiv3/CreateOrder + https://dev-online-gateway.ghn.vn/apiv3-api/api/v1/apiv3/GetDistricts + CHOXEMHANGKHONGTHU + https://dev-online-gateway.ghn.vn/apiv3-api/api/v1/apiv3/FindAvailableServices + + 1 @@ -11,12 +22,6 @@ Giao Hang Nhanh This shipping method is not available. To use this shipping method, please contact us. F - TokenStaging - https://dev-online-gateway.ghn.vn/apiv3-api/api/v1/apiv3/CalculateFee - https://dev-online-gateway.ghn.vn/apiv3-api/api/v1/apiv3/CreateOrder - https://dev-online-gateway.ghn.vn/apiv3-api/api/v1/apiv3/GetDistricts - 2 - CHOXEMHANGKHONGTHU 1 @@ -27,13 +32,6 @@ Giao Hang Nhanh This shipping method is not available. To use this shipping method, please contact us. F - TokenStaging - https://dev-online-gateway.ghn.vn/apiv3-api/api/v1/apiv3/CalculateFee - https://dev-online-gateway.ghn.vn/apiv3-api/api/v1/apiv3/CreateOrder - https://dev-online-gateway.ghn.vn/apiv3-api/api/v1/apiv3/GetDistricts - https://dev-online-gateway.ghn.vn/apiv3-api/api/v1/apiv3/FindAvailableServices - 2 - CHOXEMHANGKHONGTHU From 16a979b94f9fea5422c1f8d1890d498e83511ab2 Mon Sep 17 00:00:00 2001 From: mrnhi Date: Tue, 21 Apr 2020 01:00:07 +0700 Subject: [PATCH 26/70] add api service classes --- .../Service/DistrictProviderInterface.php | 14 ++++++ .../Service/Order/SynchronizerInterface.php | 18 ++++++++ Api/Rest/Service/Order/TrackerInterface.php | 18 ++++++++ .../Shipping/Fee/CalculatorInterface.php | 16 +++++++ .../Shipping/Services/ProviderInterface.php | 16 +++++++ Model/Api/Rest/Service.php | 30 ++++++++----- .../Rest/Service}/DistrictProvider.php | 40 ++++------------- .../Rest/Service/Order/Synchronizer.php} | 44 +++++++++---------- Model/Api/Rest/Service/Order/Tracker.php | 37 ++++++++++++++++ .../Rest/Service/Shipping/Fee/Calculator.php | 33 ++++++++++++++ .../Service/Shipping/Services/Provider.php | 34 ++++++++++++++ 11 files changed, 234 insertions(+), 66 deletions(-) create mode 100644 Api/Rest/Service/DistrictProviderInterface.php create mode 100644 Api/Rest/Service/Order/SynchronizerInterface.php create mode 100644 Api/Rest/Service/Order/TrackerInterface.php create mode 100644 Api/Rest/Service/Shipping/Fee/CalculatorInterface.php create mode 100644 Api/Rest/Service/Shipping/Services/ProviderInterface.php rename Model/{ => Api/Rest/Service}/DistrictProvider.php (55%) rename Model/{Order/Processor.php => Api/Rest/Service/Order/Synchronizer.php} (73%) create mode 100644 Model/Api/Rest/Service/Order/Tracker.php create mode 100644 Model/Api/Rest/Service/Shipping/Fee/Calculator.php create mode 100644 Model/Api/Rest/Service/Shipping/Services/Provider.php diff --git a/Api/Rest/Service/DistrictProviderInterface.php b/Api/Rest/Service/DistrictProviderInterface.php new file mode 100644 index 0000000..73ca2c1 --- /dev/null +++ b/Api/Rest/Service/DistrictProviderInterface.php @@ -0,0 +1,14 @@ +log = $log; + $this->config = $config; $this->serializer = $serializer; $this->httpClientFactory = $httpClientFactory; } @@ -48,11 +56,11 @@ public function __construct( * @param $url * @param array $rawData * @param string $method - * @return mixed|Zend_Http_Response + * @return array * @throws LocalizedException * @throws Zend_Http_Client_Exception */ - public function makeRequest($url, $rawData = [], $method = Zend_Http_Client::POST) + protected function makeRequest($url, $rawData = [], $method = Zend_Http_Client::POST) { $client = $this->httpClientFactory->create(); $client->setUri($url); @@ -70,14 +78,12 @@ public function makeRequest($url, $rawData = [], $method = Zend_Http_Client::POS } /** - * @param Zend_Http_Response $response - * @return mixed + * @param $response + * @return array */ - private function processResponse($response) + protected function processResponse($response) { - if (is_array($response)) { - return $response; - } + $data = []; try { $body = $this->serializer->unserialize((string)$response->getBody()); @@ -98,7 +104,7 @@ private function processResponse($response) * @param $response * @return bool */ - public function checkResponse($response) + protected function checkResponse($response) { if (!empty($response['response_status_code'])) { $code = $response['response_status_code']; diff --git a/Model/DistrictProvider.php b/Model/Api/Rest/Service/DistrictProvider.php similarity index 55% rename from Model/DistrictProvider.php rename to Model/Api/Rest/Service/DistrictProvider.php index c989c71..c695d6e 100644 --- a/Model/DistrictProvider.php +++ b/Model/Api/Rest/Service/DistrictProvider.php @@ -1,54 +1,30 @@ -apiService = $apiService; - $this->config = $config; - } - /** * @return array - * @throws NoSuchEntityException * @throws LocalizedException + * @throws NoSuchEntityException * @throws Zend_Http_Client_Exception */ public function getDistrictList() { $data = []; - $response = $this->apiService->makeRequest( + $response = $this->makeRequest( $this->config->getGettingDistrictsUrl(), ['token' => $this->config->getApiToken()] ); - if ($this->apiService->checkResponse($response)) { + if ($this->checkResponse($response)) { $responseObject = $response['response_object']; if (!empty($responseObject['data'])) { @@ -60,4 +36,4 @@ public function getDistrictList() return $data; } -} +} \ No newline at end of file diff --git a/Model/Order/Processor.php b/Model/Api/Rest/Service/Order/Synchronizer.php similarity index 73% rename from Model/Order/Processor.php rename to Model/Api/Rest/Service/Order/Synchronizer.php index ff4663d..7fe3b89 100644 --- a/Model/Order/Processor.php +++ b/Model/Api/Rest/Service/Order/Synchronizer.php @@ -1,25 +1,23 @@ -config = $config; - $this->apiService = $apiService; + parent::__construct($log, $config, $serializer, $httpClientFactory); $this->storeManager = $storeManager; $this->storeInformation = $storeInformation; $this->addressFactory = $addressFactory; @@ -65,7 +61,6 @@ public function __construct( /** * @param Order $order * @param array $additionalData - * @return bool * @throws LocalizedException * @throws NoSuchEntityException * @throws Zend_Http_Client_Exception @@ -104,8 +99,13 @@ public function syncOrder(Order $order, $additionalData) 'ExternalReturnCode' => $storeInfo->getName() ]; - $response = $this->apiService->makeRequest($config->getSynchronizingOrderUrl(), $data); + $response = $this->makeRequest($config->getSynchronizingOrderUrl(), $data); - return $this->apiService->checkResponse($response); + if ($this->checkResponse($response)) { + $order->setData('ghn_status', self::GHN_STATUS_SUCCESS); + $order->setData('tracking_code', $response['response_object']['data']['OrderCode']); + } else { + $order->setData('ghn_status', self::GHN_STATUS_FAIL); + } } } diff --git a/Model/Api/Rest/Service/Order/Tracker.php b/Model/Api/Rest/Service/Order/Tracker.php new file mode 100644 index 0000000..ce705fd --- /dev/null +++ b/Model/Api/Rest/Service/Order/Tracker.php @@ -0,0 +1,37 @@ +makeRequest( + $this->config->getGettingOrderInforUrl(), + [ + 'token' => $this->config->getApiToken(), + 'OrderCode' => $trackingCode + ] + ); + $data = ''; + + if ($this->checkResponse($response)) { + $data = $response['response_object']['data']['CurrentStatus']; + } + + return $data; + } +} diff --git a/Model/Api/Rest/Service/Shipping/Fee/Calculator.php b/Model/Api/Rest/Service/Shipping/Fee/Calculator.php new file mode 100644 index 0000000..5882b3f --- /dev/null +++ b/Model/Api/Rest/Service/Shipping/Fee/Calculator.php @@ -0,0 +1,33 @@ +makeRequest( + $this->config->getCalculatingFeeUrl(), + $request + ); + + if ($this->checkResponse($response)) { + return (float)$response['response_object']['data']['CalculatedFee']; + } + + return null; + } +} diff --git a/Model/Api/Rest/Service/Shipping/Services/Provider.php b/Model/Api/Rest/Service/Shipping/Services/Provider.php new file mode 100644 index 0000000..46e1ed9 --- /dev/null +++ b/Model/Api/Rest/Service/Shipping/Services/Provider.php @@ -0,0 +1,34 @@ +makeRequest($this->config->getGettingServicesUrl(), $request); + $data = []; + + if ($this->checkResponse($response)) { + + if (is_array($response['response_object']['data'])) { + $data = $response['response_object']['data']; + } + } + + return $data; + } +} From c39c30f1d6c5ed16aaa3d877089722d062408d30 Mon Sep 17 00:00:00 2001 From: mrnhi Date: Tue, 21 Apr 2020 01:04:07 +0700 Subject: [PATCH 27/70] refactor classes which are affected by changing code in Service classes --- Console/GenerateRegionCommand.php | 8 +- Model/Api/RequestProvider.php | 11 --- Model/Carrier/GHN.php | 90 ++++++++++------------ Observer/SalesOrderPlaceAfterSObserver.php | 48 ++---------- 4 files changed, 52 insertions(+), 105 deletions(-) delete mode 100644 Model/Api/RequestProvider.php diff --git a/Console/GenerateRegionCommand.php b/Console/GenerateRegionCommand.php index d97f3b4..55350ec 100644 --- a/Console/GenerateRegionCommand.php +++ b/Console/GenerateRegionCommand.php @@ -2,7 +2,7 @@ namespace Boolfly\GiaoHangNhanh\Console; -use Boolfly\GiaoHangNhanh\Model\DistrictProvider; +use Boolfly\GiaoHangNhanh\Api\Rest\Service\DistrictProviderInterface; use Magento\Directory\Model\RegionFactory; use Magento\Framework\App\ResourceConnection; use Magento\Framework\Exception\LocalizedException; @@ -25,7 +25,7 @@ class GenerateRegionCommand extends Command private $regionFactory; /** - * @var DistrictProvider + * @var DistrictProviderInterface */ private $districtProvider; @@ -33,13 +33,13 @@ class GenerateRegionCommand extends Command * GeneratingRegionData constructor. * @param ResourceConnection $resourceConnection * @param RegionFactory $regionFactory - * @param DistrictProvider $districtProvider + * @param DistrictProviderInterface $districtProvider * @param string|null $name */ public function __construct( ResourceConnection $resourceConnection, RegionFactory $regionFactory, - DistrictProvider $districtProvider, + DistrictProviderInterface $districtProvider, $name = null ) { $this->resourceConnection = $resourceConnection; diff --git a/Model/Api/RequestProvider.php b/Model/Api/RequestProvider.php deleted file mode 100644 index 05bb56d..0000000 --- a/Model/Api/RequestProvider.php +++ /dev/null @@ -1,11 +0,0 @@ -rateResultFactory = $rateResultFactory; $this->rateMethodFactory = $rateMethodFactory; - $this->restService = $restService; $this->config = $config; - $this->quoteRepository = $quoteRepository; + $this->calculator = $calculator; + $this->serviceProvider = $serviceProvider; } /** @@ -140,11 +142,9 @@ public function getAllowedMethods() */ protected function estimateShippingCost(RateRequest $request) { - $quote = $this->quoteRepository->getActive( - $request->getAllItems()[0]->getQuoteId() - ); - $shippingAddress = $quote->getShippingAddress(); - $districtId = $shippingAddress->getDistrict(); + $shippingAddress = $request->getShippingAddress(); + $districtId = $request->getDistrict(); + $shippingFee = null; if ($districtId) { $rate = $this->config->getWeightUnit() == 'kgs' ? Config::KGS_G : Config::LBS_G; @@ -159,44 +159,37 @@ protected function estimateShippingCost(RateRequest $request) if ($serviceId = $this->getAvailableService()) { $requestBody['ServiceID'] = $serviceId; - - if ($request->getLimitCarrier()) { - $shippingAddress->setData('shipping_service_id', $serviceId); - - try { - $shippingAddress->save(); - } catch (Exception $e) { - $this->_logger->error(__('Can\'t save shipping address.')); - } - } - - $response = $this->restService->makeRequest( - $this->config->getCalculatingFeeUrl(), - $requestBody - ); - - if ($this->restService->checkResponse($response)) { - return $response['response_object']['data']['CalculatedFee']; - } + $this->updateShippingServiceForAddress($request, $shippingAddress, $serviceId); + $shippingFee = $this->calculator->calculate($requestBody); } } - return null; + return $shippingFee; } - protected function prepareServices($request) + /** + * @param RateRequest $request + * @param Address $shippingAddress + * @param string $serviceId + */ + protected function updateShippingServiceForAddress(RateRequest $request, Address $shippingAddress, $serviceId) { - $response = $this->restService->makeRequest($this->config->getGettingServicesUrl(), $request); - - if ($this->restService->checkResponse($response)) { - $data = $response['response_object']['data']; - - if (is_array($data)) { - $this->availableServices = $data; - } + if ($request->getLimitCarrier()) { + $shippingAddress->setData('shipping_service_id', $serviceId); } } + /** + * @param array $request + * @throws LocalizedException + * @throws NoSuchEntityException + * @throws Zend_Http_Client_Exception + */ + protected function prepareServices($request) + { + $this->availableServices = $this->serviceProvider->getShippingServices($request); + } + /** * @return string */ @@ -205,7 +198,6 @@ protected function getAvailableService() if (count($this->availableServices)) { foreach ($this->availableServices as $serviceItem) { if (!empty($serviceItem['Name'])) { - if ($serviceItem['Name'] == static::SERVICE_NAME) { return $serviceItem['ServiceID']; } diff --git a/Observer/SalesOrderPlaceAfterSObserver.php b/Observer/SalesOrderPlaceAfterSObserver.php index bde700b..ad457ff 100644 --- a/Observer/SalesOrderPlaceAfterSObserver.php +++ b/Observer/SalesOrderPlaceAfterSObserver.php @@ -2,10 +2,8 @@ namespace Boolfly\GiaoHangNhanh\Observer; +use Boolfly\GiaoHangNhanh\Api\Rest\Service\Order\SynchronizerInterface; use Boolfly\GiaoHangNhanh\Model\Config; -use Boolfly\GiaoHangNhanh\Model\Order\Processor; -use Exception; -use Magento\Customer\Model\AddressFactory; use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; use Magento\Quote\Model\QuoteRepository; @@ -13,46 +11,35 @@ class SalesOrderPlaceAfterSObserver implements ObserverInterface { - const GHN_STATUS_FAIL = 0; - const GHN_STATUS_SUCCESS = 1; - /** * @var QuoteRepository */ private $quoteRepository; - /** - * @var AddressFactory - */ - private $customerAddressFactory; - /** * @var LoggerInterface */ private $logger; /** - * @var Processor + * @var SynchronizerInterface */ - private $orderProcessor; + private $synchronizer; /** * SalesOrderAfterSaveObserver constructor. * @param QuoteRepository $quoteRepository - * @param AddressFactory $customerAddressFactory * @param LoggerInterface $logger - * @param Processor $orderProcessor + * @param SynchronizerInterface $synchronizer */ public function __construct( QuoteRepository $quoteRepository, - AddressFactory $customerAddressFactory, LoggerInterface $logger, - Processor $orderProcessor + SynchronizerInterface $synchronizer ) { $this->logger = $logger; $this->quoteRepository = $quoteRepository; - $this->orderProcessor = $orderProcessor; - $this->customerAddressFactory = $customerAddressFactory; + $this->synchronizer = $synchronizer; } /** @@ -70,29 +57,8 @@ public function execute(Observer $observer) 'district' => $shippingAddress->getDistrict(), 'shipping_service_id' => $shippingAddress->getShippingServiceId() ]; - $result = $this->orderProcessor->syncOrder($order, $additionalData); - - if (true === $result) { - $order->setData('ghn_status', self::GHN_STATUS_SUCCESS); - } else { - $order->setData('ghn_status', self::GHN_STATUS_FAIL); - } - - if ($customerAddressId = $shippingAddress->getCustomerAddressId()) { - $customerAddress = $this->customerAddressFactory->create()->load($customerAddressId); - if ($customerAddress->getId()) { - try { - $customerAddress->setData('district', $shippingAddress->getDistrict()); - $customerAddress->save(); - } catch (Exception $e) { - $this->logger->error(__( - 'Can\'t set district for customer address with ID %1.', - $customerAddressId - )); - } - } - } + $this->synchronizer->syncOrder($order, $additionalData); } } } From 7498e97c89efea9f61f72cfa828c950b42a12728 Mon Sep 17 00:00:00 2001 From: mrnhi Date: Tue, 21 Apr 2020 01:06:13 +0700 Subject: [PATCH 28/70] update configuration --- Model/Config.php | 29 +++++++++++++++++++++++++++++ etc/adminhtml/system.xml | 3 +++ etc/config.xml | 1 + 3 files changed, 33 insertions(+) diff --git a/Model/Config.php b/Model/Config.php index 83610d9..b28aa7c 100644 --- a/Model/Config.php +++ b/Model/Config.php @@ -27,6 +27,7 @@ class Config const NOTE_CODE = 'giaohangnhanh_setting/general/note_code'; const DISTRICT = 'giaohangnhanh_setting/general/district'; const GETTING_SERVICES_URL = 'giaohangnhanh_setting/general/get_services_url'; + const GETTING_ORDER_INFOR = 'giaohangnhanh_setting/general/get_order_infor'; /** * @var int @@ -100,6 +101,15 @@ public function getGettingDistrictsUrl() return $this->getConfig(self::GETTING_DISTRICTS_URL); } + /** + * @return mixed + * @throws NoSuchEntityException + */ + public function getGettingOrderInforUrl() + { + return $this->getConfig(self::GETTING_ORDER_INFOR); + } + /** * @return mixed * @throws NoSuchEntityException @@ -162,6 +172,25 @@ public function getDistricts() return $connection->fetchAll($sql); } + /** + * @return array + */ + public function getDistrictOptions() + { + $districts = $this->getDistricts(); + $data = []; + foreach ($districts as $district) { + $districtName = $district['district_name']; + $data[] = [ + 'title' => $districtName, + 'value' => $district['district_id'], + 'region_id' => $district['region_id'], + 'label' => $districtName + ]; + } + return $data; + } + /** * @param $path * @return mixed diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index 156de17..afe7994 100644 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -133,6 +133,9 @@ + + + diff --git a/etc/config.xml b/etc/config.xml index cff19ec..9d11bc6 100644 --- a/etc/config.xml +++ b/etc/config.xml @@ -10,6 +10,7 @@ https://dev-online-gateway.ghn.vn/apiv3-api/api/v1/apiv3/GetDistricts CHOXEMHANGKHONGTHU https://dev-online-gateway.ghn.vn/apiv3-api/api/v1/apiv3/FindAvailableServices + https://dev-online-gateway.ghn.vn/apiv3-api/api/v1/apiv3/OrderInfo From 0473fe08f55bec3a0b01162e54319910ee462b2f Mon Sep 17 00:00:00 2001 From: mrnhi Date: Tue, 21 Apr 2020 01:08:34 +0700 Subject: [PATCH 29/70] update database --- etc/db_schema.xml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/etc/db_schema.xml b/etc/db_schema.xml index 852a327..a4fb5b4 100644 --- a/etc/db_schema.xml +++ b/etc/db_schema.xml @@ -14,6 +14,7 @@ +
@@ -22,5 +23,6 @@
+
\ No newline at end of file From 394acfc14cf586cf984dd66b6d9bd9c356d05ad9 Mon Sep 17 00:00:00 2001 From: mrnhi Date: Tue, 21 Apr 2020 01:13:33 +0700 Subject: [PATCH 30/70] update plugins --- .../Block/Checkout/DirectoryDataProcessor.php | 36 +++++++++++ .../Block/Checkout/LayoutProcessor.php | 17 +++-- .../Model/ShippingInformationManagement.php | 36 +++++------ .../Model/TotalsInformationManagement.php | 46 +++++++++++++ Plugin/Customer/Model/Address.php | 20 ++++++ .../Model/ResourceModel/AddressRepository.php | 32 ++++++++++ .../Model/EstimateByExtendedAddressBefore.php | 12 +--- Plugin/Quote/Model/Quote/Address.php | 17 +++++ Plugin/Sales/Model/Order.php | 48 ++++++++++++++ Plugin/Shipping/Model/Shipping.php | 64 +++++++++++++++++++ 10 files changed, 291 insertions(+), 37 deletions(-) create mode 100644 Plugin/Checkout/Block/Checkout/DirectoryDataProcessor.php create mode 100644 Plugin/Checkout/Model/TotalsInformationManagement.php create mode 100644 Plugin/Customer/Model/Address.php create mode 100644 Plugin/Customer/Model/ResourceModel/AddressRepository.php create mode 100644 Plugin/Quote/Model/Quote/Address.php create mode 100644 Plugin/Sales/Model/Order.php create mode 100644 Plugin/Shipping/Model/Shipping.php diff --git a/Plugin/Checkout/Block/Checkout/DirectoryDataProcessor.php b/Plugin/Checkout/Block/Checkout/DirectoryDataProcessor.php new file mode 100644 index 0000000..c1d3db5 --- /dev/null +++ b/Plugin/Checkout/Block/Checkout/DirectoryDataProcessor.php @@ -0,0 +1,36 @@ +config = $config; + } + + /** + * @param MageDirectoryDataProcessor $subject + * @param $result + * @return mixed + */ + public function afterProcess(MageDirectoryDataProcessor $subject, $result) + { + $result['components']['checkoutProvider']['dictionaries']['district'] = $this->config->getDistrictOptions(); + + return $result; + } +} diff --git a/Plugin/Checkout/Block/Checkout/LayoutProcessor.php b/Plugin/Checkout/Block/Checkout/LayoutProcessor.php index 5f5adc9..8738b2e 100644 --- a/Plugin/Checkout/Block/Checkout/LayoutProcessor.php +++ b/Plugin/Checkout/Block/Checkout/LayoutProcessor.php @@ -10,7 +10,7 @@ public function afterProcess(MageLayoutProcessor $subject, $result) { $result['components']['checkout']['children']['steps']['children']['shipping-step']['children'] ['shippingAddress']['children']['shipping-address-fieldset']['children']['district'] = [ - 'component' => 'Magento_Ui/js/form/element/select', + 'component' => 'Boolfly_GiaoHangNhanh/js/view/checkout/shipping/district', 'config' => [ 'customScope' => 'shippingAddress.custom_attributes', 'template' => 'ui/form/field', @@ -24,12 +24,15 @@ public function afterProcess(MageLayoutProcessor $subject, $result) 'validation' => ['required-entry' => false], 'sortOrder' => 255, 'id' => 'district', - 'options' => [ - [ - 'value' => '', - 'label' => __('Please select a district.'), - ] - ] + 'imports' => [ + 'initialOptions' => 'index = checkoutProvider:dictionaries.district', + 'setOptions' => 'index = checkoutProvider:dictionaries.district' + ], + 'filterBy' => [ + 'target' => 'checkoutProvider:shippingAddress.region_id', + 'field' => 'region_id' + ], + 'deps' => 'checkoutProvider' ]; return $result; diff --git a/Plugin/Checkout/Model/ShippingInformationManagement.php b/Plugin/Checkout/Model/ShippingInformationManagement.php index 3330390..568e17c 100644 --- a/Plugin/Checkout/Model/ShippingInformationManagement.php +++ b/Plugin/Checkout/Model/ShippingInformationManagement.php @@ -45,31 +45,29 @@ public function beforeSaveAddressInformation( $cartId, ShippingInformationInterface $addressInformation ) { - if (false !== strpos($addressInformation->getShippingMethodCode(), Config::GHN_CODE)) { - $quote = $this->quoteRepository->getActive($cartId); - $extensionAttributes = $addressInformation->getExtensionAttributes(); - $shippingAddress = $quote->getShippingAddress(); - $district = ''; + $quote = $this->quoteRepository->getActive($cartId); + $extensionAttributes = $addressInformation->getExtensionAttributes(); + $shippingAddress = $quote->getShippingAddress(); + $district = ''; - if ($shippingAddress->getDistrict()) { - return; - } + if ($shippingAddress->getDistrict()) { + return; + } - if (!$extensionAttributes->getDistrict()) { - if ($customerAddressId = $shippingAddress->getCustomerAddressId()) { - $address = $this->customerAddressFactory->create()->load($customerAddressId); + if (!$extensionAttributes->getDistrict()) { + if ($customerAddressId = $shippingAddress->getCustomerAddressId()) { + $address = $this->customerAddressFactory->create()->load($customerAddressId); - if ($address->getId()) { - $district = $address->getDistrict(); - } + if ($address->getId()) { + $district = $address->getDistrict(); } - } else { - $district = $extensionAttributes->getDistrict(); } + } else { + $district = $extensionAttributes->getDistrict(); + } - if ($district) { - $shippingAddress->setDistrict($district); - } + if ($district) { + $shippingAddress->setDistrict($district); } } } diff --git a/Plugin/Checkout/Model/TotalsInformationManagement.php b/Plugin/Checkout/Model/TotalsInformationManagement.php new file mode 100644 index 0000000..e9f1da5 --- /dev/null +++ b/Plugin/Checkout/Model/TotalsInformationManagement.php @@ -0,0 +1,46 @@ +cartRepository = $cartRepository; + } + + public function beforeCalculate( + MageTotalsInformationManagement $subject, + $cartId, + TotalsInformationInterface $addressInformation + ) { + /** @var \Magento\Quote\Model\Quote $quote */ + $quote = $this->cartRepository->get($cartId); + $shippingAddress = $quote->getShippingAddress(); + + if ($shippingAddress->getDistrict()) { + return; + } + + $district = $addressInformation->getExtensionAttributes()->getDistrict(); + + if ($district) { + $shippingAddress->setDistrict($district); + } + } +} diff --git a/Plugin/Customer/Model/Address.php b/Plugin/Customer/Model/Address.php new file mode 100644 index 0000000..d3ab527 --- /dev/null +++ b/Plugin/Customer/Model/Address.php @@ -0,0 +1,20 @@ +getExtensionAttributes()->getDistrict(); + + if ($district) { + $result->setDistrict($district); + } + + return $result; + } +} diff --git a/Plugin/Customer/Model/ResourceModel/AddressRepository.php b/Plugin/Customer/Model/ResourceModel/AddressRepository.php new file mode 100644 index 0000000..bc25f88 --- /dev/null +++ b/Plugin/Customer/Model/ResourceModel/AddressRepository.php @@ -0,0 +1,32 @@ +addressRegistry = $addressRegistry; + } + + public function afterGetById(MageAddressRepository $subject, $result, $addressId) + { + $address = $this->addressRegistry->retrieve($addressId); + $result->getExtensionAttributes()->setDistrict($address->getDistrict()); + + return $result; + } +} diff --git a/Plugin/Quote/Model/EstimateByExtendedAddressBefore.php b/Plugin/Quote/Model/EstimateByExtendedAddressBefore.php index 58a1db8..38690ff 100644 --- a/Plugin/Quote/Model/EstimateByExtendedAddressBefore.php +++ b/Plugin/Quote/Model/EstimateByExtendedAddressBefore.php @@ -37,17 +37,7 @@ public function beforeEstimateByExtendedAddress( ) { /** @var \Magento\Quote\Model\Quote $quote */ $quote = $this->quoteRepository->getActive($cartId); - $checkoutFields = $address->getExtensionAttributes()->getCheckoutFields(); - $district = ''; - - if ($checkoutFields) { - foreach ($checkoutFields as $field) { - if ($field->getAttributeCode() == 'district') { - $district = $field->getValue(); - break; - } - } - } + $district = $address->getExtensionAttributes()->getDistrict(); if (!$district) { return; diff --git a/Plugin/Quote/Model/Quote/Address.php b/Plugin/Quote/Model/Quote/Address.php new file mode 100644 index 0000000..4dcb320 --- /dev/null +++ b/Plugin/Quote/Model/Quote/Address.php @@ -0,0 +1,17 @@ +getDistrict()) { + $result->getExtensionAttributes()->setDistrict($district); + } + + return $result; + } +} diff --git a/Plugin/Sales/Model/Order.php b/Plugin/Sales/Model/Order.php new file mode 100644 index 0000000..f93b14a --- /dev/null +++ b/Plugin/Sales/Model/Order.php @@ -0,0 +1,48 @@ +tracker = $tracker; + } + + /** + * @param MageOrder $subject + * @param $result + * @return bool + * @throws LocalizedException + * @throws NoSuchEntityException + * @throws Zend_Http_Client_Exception + */ + public function afterCanCancel(MageOrder $subject, $result) + { + $trackingCode = $subject->getData('tracking_code'); + $status = $subject->getData('ghn_status'); + + if ($status && $trackingCode) { + if ($this->tracker->getOrderStatus($trackingCode) != TrackerInterface::DEFAULT_ORDER_STATUS) { + $result = false; + } + } + + return $result; + } +} diff --git a/Plugin/Shipping/Model/Shipping.php b/Plugin/Shipping/Model/Shipping.php new file mode 100644 index 0000000..616b676 --- /dev/null +++ b/Plugin/Shipping/Model/Shipping.php @@ -0,0 +1,64 @@ +getShippingAddress($rateRequest); + $rateRequest->setShippingAddress($shippingAddress); + + if ($district = $shippingAddress->getDistrict()) { + $rateRequest->setDistrict($district); + } + } catch (LocalizedException $exception) { + return; + } + } + + /** + * Normalize rate request items. In rare cases they are not set at all. + * + * @param RateRequest $rateRequest + * @return AbstractItem[] + */ + private function getItems(RateRequest $rateRequest) + { + if (!$rateRequest->getAllItems()) { + return []; + } + + return $rateRequest->getAllItems(); + } + + /** + * Extract shipping address from rate request. + * + * @param RateRequest $rateRequest + * @return Address + * @throws LocalizedException + */ + private function getShippingAddress(RateRequest $rateRequest) + { + $itemsToShip = $this->getItems($rateRequest); + $currentItem = current($itemsToShip); + + if ($currentItem === false) { + throw new LocalizedException(__('No items to ship found in rates request.')); + } + + return $currentItem->getAddress(); + } +} From e41813e1b7aeea2cf425fe72b961f01bc58d41ae Mon Sep 17 00:00:00 2001 From: mrnhi Date: Tue, 21 Apr 2020 01:15:08 +0700 Subject: [PATCH 31/70] delete ConfigProvider class --- Model/ConfigProvider.php | 42 ---------------------------------------- 1 file changed, 42 deletions(-) delete mode 100644 Model/ConfigProvider.php diff --git a/Model/ConfigProvider.php b/Model/ConfigProvider.php deleted file mode 100644 index 0db4bb7..0000000 --- a/Model/ConfigProvider.php +++ /dev/null @@ -1,42 +0,0 @@ -config = $config; - } - - /** - * @inheritDoc - */ - public function getConfig() - { - $districts = $this->config->getDistricts(); - $data = []; - foreach ($districts as $district) { - $data[$district['region_id']][] = [ - 'districtName' => $district['district_name'], - 'districtID' => $district['district_id'], - 'provinceID' => $district['province_id'] - ]; - } - return [ - 'districts' => $data - ]; - } -} From c28d841f7416d482f8f68dcc0e9befa6f08723fe Mon Sep 17 00:00:00 2001 From: mrnhi Date: Tue, 21 Apr 2020 01:16:07 +0700 Subject: [PATCH 32/70] update di.xml --- etc/di.xml | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/etc/di.xml b/etc/di.xml index 55636ca..be2af36 100755 --- a/etc/di.xml +++ b/etc/di.xml @@ -1,5 +1,13 @@ + + + + + + + + @@ -19,6 +27,7 @@ sales_order.ghn_status + sales_order.tracking_code @@ -29,4 +38,25 @@ + + + + + + + + + + + + + + + + + + + + + From 64553634d045988de4c915c954be7484cc07d264 Mon Sep 17 00:00:00 2001 From: mrnhi Date: Tue, 21 Apr 2020 01:16:53 +0700 Subject: [PATCH 33/70] update etc/frontend/di.xml --- etc/frontend/di.xml | 9 --------- 1 file changed, 9 deletions(-) diff --git a/etc/frontend/di.xml b/etc/frontend/di.xml index 760f73f..c6f3581 100644 --- a/etc/frontend/di.xml +++ b/etc/frontend/di.xml @@ -1,14 +1,5 @@ - - - - - Boolfly\GiaoHangNhanh\Model\ConfigProvider - - - - From 86fc26483586a4e69003589d4dfba651c759a72b Mon Sep 17 00:00:00 2001 From: mrnhi Date: Tue, 21 Apr 2020 01:17:51 +0700 Subject: [PATCH 34/70] update Setup/InstallData.php --- Setup/InstallData.php | 55 ++++++++++++++++++++++++------------------- 1 file changed, 31 insertions(+), 24 deletions(-) diff --git a/Setup/InstallData.php b/Setup/InstallData.php index d9834da..302c884 100644 --- a/Setup/InstallData.php +++ b/Setup/InstallData.php @@ -2,6 +2,7 @@ namespace Boolfly\GiaoHangNhanh\Setup; +use Magento\Customer\Api\AddressMetadataInterface; use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface; use Magento\Eav\Setup\EavSetupFactory; use Magento\Eav\Model\Config; @@ -46,36 +47,42 @@ public function __construct( */ public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context) { + /** @var \Magento\Eav\Setup\EavSetup $eavSetup */ + $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]); + $setup->startSetup(); - $eavSetup = $this->eavSetupFactory->create(); - $eavSetup->addAttribute( - 'customer_address', - 'district', - [ - 'group' => 'General', - 'type' => 'varchar', - 'label' => 'District', - 'input' => 'select', - 'source' => 'Boolfly\GiaoHangNhanh\Model\Attribute\Source\District', - 'required' => false, - 'sort_order' => 110, - 'global' => ScopedAttributeInterface::SCOPE_GLOBAL, - 'is_used_in_grid' => true, - 'is_visible_in_grid' => true, - 'is_filterable_in_grid' => false, - 'visible' => true, - 'is_html_allowed_on_front' => true, - 'visible_on_front' => true - ] - ); - $customAttribute = $this->eavConfig->getAttribute('customer_address', 'district'); + $attributeCode = 'district'; + $eavSetup->addAttribute(AddressMetadataInterface::ENTITY_TYPE_ADDRESS, $attributeCode, [ + 'group' => 'General', + 'type' => 'varchar', + 'label' => 'District', + 'input' => 'text', + 'required' => false, + 'sort_order' => 110, + 'global' => ScopedAttributeInterface::SCOPE_GLOBAL, + 'is_used_in_grid' => true, + 'is_visible_in_grid' => true, + 'is_filterable_in_grid' => false, + 'visible' => true, + 'user_defined' => true, + 'is_html_allowed_on_front' => true, + 'visible_on_front' => true + ]); + + $eavSetup->addAttributeToSet( + AddressMetadataInterface::ENTITY_TYPE_ADDRESS, + AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS, + 1, + $attributeCode + ); - $customAttribute->setData( + $district = $this->eavConfig->getAttribute(AddressMetadataInterface::ENTITY_TYPE_ADDRESS, $attributeCode); + $district->setData( 'used_in_forms', ['adminhtml_customer_address','customer_address_edit','customer_register_address'] ); - $customAttribute->save(); + $district->getResource()->save($district); $setup->endSetup(); } From cdb167675914c2babfe46f6023753227f2c537ca Mon Sep 17 00:00:00 2001 From: mrnhi Date: Tue, 21 Apr 2020 01:18:41 +0700 Subject: [PATCH 35/70] update etc/extension_attributes.xml --- etc/extension_attributes.xml | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/etc/extension_attributes.xml b/etc/extension_attributes.xml index c143e8e..a0a0e8c 100644 --- a/etc/extension_attributes.xml +++ b/etc/extension_attributes.xml @@ -4,4 +4,13 @@ + + + + + + + + + \ No newline at end of file From aae9f045a08628116df338a930bb5642b9514465 Mon Sep 17 00:00:00 2001 From: mrnhi Date: Tue, 21 Apr 2020 01:20:55 +0700 Subject: [PATCH 36/70] delete unnecessary js mixin --- .../web/js/form/element/region-mixin.js | 26 ------------------- 1 file changed, 26 deletions(-) delete mode 100644 view/frontend/web/js/form/element/region-mixin.js diff --git a/view/frontend/web/js/form/element/region-mixin.js b/view/frontend/web/js/form/element/region-mixin.js deleted file mode 100644 index d14daff..0000000 --- a/view/frontend/web/js/form/element/region-mixin.js +++ /dev/null @@ -1,26 +0,0 @@ -define(['jquery'], function ($) { - 'use strict'; - - var mixin = { - - /** - * @param {String} value - */ - update: function (value) { - this._super(); - let districtField = $('[name="custom_attributes[district]"]'); - - if (value !== 'VN') { - districtField.hide(); - } else { - if (districtField.is(":hidden")) { - districtField.show(); - } - } - } - }; - - return function (target) { - return target.extend(mixin); - }; -}); \ No newline at end of file From bff65b2f02f939e364c12c974b4cd6ec63eeffd1 Mon Sep 17 00:00:00 2001 From: mrnhi Date: Tue, 21 Apr 2020 01:22:39 +0700 Subject: [PATCH 37/70] update layouts --- view/frontend/layout/checkout_cart_index.xml | 49 +++++++++++++++++++ view/frontend/layout/checkout_index_index.xml | 15 ------ .../frontend/layout/customer_address_form.xml | 6 +++ 3 files changed, 55 insertions(+), 15 deletions(-) create mode 100755 view/frontend/layout/checkout_cart_index.xml diff --git a/view/frontend/layout/checkout_cart_index.xml b/view/frontend/layout/checkout_cart_index.xml new file mode 100755 index 0000000..fc113d3 --- /dev/null +++ b/view/frontend/layout/checkout_cart_index.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + Boolfly_GiaoHangNhanh/js/view/shipping-rates-validation + + + + + + + + + + + + + Boolfly_GiaoHangNhanh/js/view/cart/shipping/district + 152 + + ui/form/field + ui/form/element/select + + + + + region_id + + + + + + + + + + + + + + diff --git a/view/frontend/layout/checkout_index_index.xml b/view/frontend/layout/checkout_index_index.xml index 4c69623..3d40f7f 100644 --- a/view/frontend/layout/checkout_index_index.xml +++ b/view/frontend/layout/checkout_index_index.xml @@ -11,21 +11,6 @@ - - - - uiComponent - shippingAdditional - - - - Boolfly_GiaoHangNhanh/js/view/checkout/shipping/district - - - - - - diff --git a/view/frontend/layout/customer_address_form.xml b/view/frontend/layout/customer_address_form.xml index 58b0778..e43c7b0 100755 --- a/view/frontend/layout/customer_address_form.xml +++ b/view/frontend/layout/customer_address_form.xml @@ -5,6 +5,12 @@ Boolfly_GiaoHangNhanh::address/edit.phtml + + + + Boolfly\GiaoHangNhanh\Block\Customer\DataProviders\AdditionalConfig + + From b2649aeb525052dc51b3a5ee34096a6ee6259647 Mon Sep 17 00:00:00 2001 From: mrnhi Date: Tue, 21 Apr 2020 01:33:18 +0700 Subject: [PATCH 38/70] add js files to serve shipping method giaohangnhanh --- view/frontend/requirejs-config.js | 11 +- view/frontend/templates/address/edit.phtml | 8 ++ view/frontend/web/js/district-updater.js | 59 ++++++++++ .../js/model/cart/totals-processor/default.js | 102 ++++++++++++++++++ .../shipping-rate-processor/new-address.js | 15 ++- .../web/js/view/cart/shipping/district.js | 14 +++ .../web/js/view/checkout/shipping/district.js | 25 ++--- 7 files changed, 210 insertions(+), 24 deletions(-) create mode 100644 view/frontend/web/js/district-updater.js create mode 100644 view/frontend/web/js/model/cart/totals-processor/default.js create mode 100644 view/frontend/web/js/view/cart/shipping/district.js diff --git a/view/frontend/requirejs-config.js b/view/frontend/requirejs-config.js index cfa767e..65da46b 100644 --- a/view/frontend/requirejs-config.js +++ b/view/frontend/requirejs-config.js @@ -2,14 +2,9 @@ var config = { map: { "*": { 'Magento_Checkout/js/model/shipping-save-processor/default': 'Boolfly_GiaoHangNhanh/js/model/shipping-save-processor/default', - 'Magento_Checkout/js/model/shipping-rate-processor/new-address': 'Boolfly_GiaoHangNhanh/js/model/shipping-rate-processor/new-address' - } - }, - config: { - mixins: { - 'Magento_Ui/js/form/element/region': { - 'Boolfly_GiaoHangNhanh/js/form/element/region-mixin': true - } + 'Magento_Checkout/js/model/shipping-rate-processor/new-address': 'Boolfly_GiaoHangNhanh/js/model/shipping-rate-processor/new-address', + 'Magento_Checkout/js/model/cart/totals-processor/default': 'Boolfly_GiaoHangNhanh/js/model/cart/totals-processor/default', + districtUpdater: 'Boolfly_GiaoHangNhanh/js/district-updater' } } }; \ No newline at end of file diff --git a/view/frontend/templates/address/edit.phtml b/view/frontend/templates/address/edit.phtml index 8a78957..eab5eca 100644 --- a/view/frontend/templates/address/edit.phtml +++ b/view/frontend/templates/address/edit.phtml @@ -211,6 +211,14 @@ "defaultRegion": "getRegionId() ?>", "countriesWithOptionalZip": helper(\Magento\Directory\Helper\Data::class)->getCountriesWithOptionalZip(true) ?> } + }, + "#region_id": { + "districtUpdater": { + "districtListId": "#district_id", + "defaultRegion": "getRegionId() ?>", + "defaultDistrict": "getAddress()->getExtensionAttributes()->getDistrict() ?>", + "jsonConfig": getAdditionalConfig()->getJsonData(); ?> + } } } diff --git a/view/frontend/web/js/district-updater.js b/view/frontend/web/js/district-updater.js new file mode 100644 index 0000000..7a5d142 --- /dev/null +++ b/view/frontend/web/js/district-updater.js @@ -0,0 +1,59 @@ +define([ + 'jquery', + 'underscore', + 'jquery/ui', + 'mage/validation', + 'domReady!' +], function ($, _) { + 'use strict'; + + $.widget('boolfly.districtUpdater', { + options: { + isRegionRequired: true, + currentRegion: null, + districtList: null, + defaultDistrict: '' + }, + + /** + * + * @private + */ + _create: function () { + let self = this; + let defaultDistrict = self.options.defaultDistrict; + let districtSelector = $(self.options.districtListId); + let regionId = self.options.defaultRegion; + + self.updateDistricts(regionId); + + if (defaultDistrict) { + districtSelector.val(defaultDistrict); + } + + self._bind(); + }, + + _bind: function () { + let self = this; + + self.element.on('change', function () { + self.updateDistricts($(this).val()); + }); + }, + + updateDistricts: function (regionId) { + let self = this; + let districtSelector = $(self.options.districtListId); + let districtList = self.options.jsonConfig.districts[regionId]; + + districtSelector.children('option:not(:first)').remove(); + + $.each(districtList, function (k, v) { + districtSelector.append(new Option(v.districtName, v.districtID)); + }); + } + }); + + return $.boolfly.districtUpdater; +}); diff --git a/view/frontend/web/js/model/cart/totals-processor/default.js b/view/frontend/web/js/model/cart/totals-processor/default.js new file mode 100644 index 0000000..bef23e3 --- /dev/null +++ b/view/frontend/web/js/model/cart/totals-processor/default.js @@ -0,0 +1,102 @@ +define([ + 'underscore', + 'Magento_Checkout/js/model/resource-url-manager', + 'Magento_Checkout/js/model/quote', + 'mage/storage', + 'Magento_Checkout/js/model/totals', + 'Magento_Checkout/js/model/error-processor', + 'Magento_Checkout/js/model/cart/cache', + 'Magento_Customer/js/customer-data' +], function (_, resourceUrlManager, quote, storage, totalsService, errorProcessor, cartCache, customerData) { + 'use strict'; + + /** + * Load data from server. + * + * @param {Object} address + */ + var loadFromServer = function (address) { + var serviceUrl, + payload; + + // Start loader for totals block + totalsService.isLoading(true); + serviceUrl = resourceUrlManager.getUrlForTotalsEstimationForNewAddress(quote); + let district = jQuery('[name="district"]').val(); + payload = { + addressInformation: { + address: _.pick(address, cartCache.requiredFields), + extension_attributes: { + district: district + } + } + }; + + if (quote.shippingMethod() && quote.shippingMethod()['method_code']) { + payload.addressInformation['shipping_method_code'] = quote.shippingMethod()['method_code']; + payload.addressInformation['shipping_carrier_code'] = quote.shippingMethod()['carrier_code']; + } + + return storage.post( + serviceUrl, JSON.stringify(payload), false + ).done(function (result) { + var data = { + totals: result, + address: address, + cartVersion: customerData.get('cart')()['data_id'], + shippingMethodCode: null, + shippingCarrierCode: null + }; + + if (quote.shippingMethod() && quote.shippingMethod()['method_code']) { + data.shippingMethodCode = quote.shippingMethod()['method_code']; + data.shippingCarrierCode = quote.shippingMethod()['carrier_code']; + } + + quote.setTotals(result); + cartCache.set('cart-data', data); + }).fail(function (response) { + errorProcessor.process(response); + }).always(function () { + // Stop loader for totals block + totalsService.isLoading(false); + }); + }; + + return { + /** + * Array of required address fields. + * @property {Array.String} requiredFields + * @deprecated Use cart cache. + */ + requiredFields: cartCache.requiredFields, + + /** + * Get shipping rates for specified address. + * @param {Object} address + */ + estimateTotals: function (address) { + var data = { + shippingMethodCode: null, + shippingCarrierCode: null + }; + + if (quote.shippingMethod() && quote.shippingMethod()['method_code']) { + data.shippingMethodCode = quote.shippingMethod()['method_code']; + data.shippingCarrierCode = quote.shippingMethod()['carrier_code']; + } + + if (!cartCache.isChanged('cartVersion', customerData.get('cart')()['data_id']) && + !cartCache.isChanged('shippingMethodCode', data.shippingMethodCode) && + !cartCache.isChanged('shippingCarrierCode', data.shippingCarrierCode) && + !cartCache.isChanged('address', address) && + cartCache.get('totals') && + !cartCache.isChanged('subtotal', parseFloat(quote.totals().subtotal)) + ) { + quote.setTotals(cartCache.get('totals')); + } else { + return loadFromServer(address); + } + } + }; +}); diff --git a/view/frontend/web/js/model/shipping-rate-processor/new-address.js b/view/frontend/web/js/model/shipping-rate-processor/new-address.js index e9f86c5..9331d5b 100644 --- a/view/frontend/web/js/model/shipping-rate-processor/new-address.js +++ b/view/frontend/web/js/model/shipping-rate-processor/new-address.js @@ -15,10 +15,22 @@ define([ */ getRates: function (address) { var cache, serviceUrl, payload; + var district = ''; shippingService.isLoading(true); cache = rateRegistry.get(address.getCacheKey()); serviceUrl = resourceUrlManager.getUrlForEstimationShippingMethodsForNewAddress(quote); + + if (typeof address.customAttributes === "undefined") { + district = jQuery('[name="district"]').val(); + } else { + jQuery.each(address.customAttributes, function (k, v) { + if (v.attribute_code == 'district') { + district = v.value; + } + }); + } + payload = JSON.stringify({ address: { 'street': address.street, @@ -40,8 +52,7 @@ define([ 'fax': address.fax, 'custom_attributes': address.customAttributes, 'extension_attributes': { - 'checkout_fields': address.customAttributes - + 'district': district }, 'save_in_address_book': address.saveInAddressBook } diff --git a/view/frontend/web/js/view/cart/shipping/district.js b/view/frontend/web/js/view/cart/shipping/district.js new file mode 100644 index 0000000..03032e6 --- /dev/null +++ b/view/frontend/web/js/view/cart/shipping/district.js @@ -0,0 +1,14 @@ +define([ + 'jquery', + 'Boolfly_GiaoHangNhanh/js/view/checkout/shipping/district' +], function ($, Component) { + 'use strict'; + + return Component.extend({ + defaults: { + imports: { + update: '${ $.parentName }.country_id:value' + } + } + }); +}); \ No newline at end of file diff --git a/view/frontend/web/js/view/checkout/shipping/district.js b/view/frontend/web/js/view/checkout/shipping/district.js index 8104881..0737fb8 100644 --- a/view/frontend/web/js/view/checkout/shipping/district.js +++ b/view/frontend/web/js/view/checkout/shipping/district.js @@ -1,27 +1,24 @@ define([ 'jquery', - 'Magento_Ui/js/form/element/select', - 'Magento_Checkout/js/model/quote', - 'Magento_Checkout/js/model/shipping-rate-registry' -], function ($, Component, quote, rateRegistry) { + 'Magento_Ui/js/form/element/select' +], function ($, Select) { 'use strict'; - let checkoutConfigDistricts = window.checkoutConfig.districts; - return Component.extend({ + return Select.extend({ defaults: { imports: { - update: 'checkout.steps.shipping-step.shippingAddress.shipping-address-fieldset.region_id:value' + update: 'checkout.steps.shipping-step.shippingAddress.shipping-address-fieldset.country_id:value' } }, update: function (value) { - let district = $('[name="custom_attributes[district]"]'); - let districtList = checkoutConfigDistricts[parseInt(value)]; - district.children('option:not(:first)').remove(); - - $.each(districtList, function (k, v) { - district.append(new Option(v.districtName, v.districtID)); - }); + if (value === 'VN') { + this.validation['required-entry'] = true; + this.required(true); + this.setVisible(true); + } else { + this.setVisible(false); + } } }); }); \ No newline at end of file From b34316b2960db29a5a03c0b17fa383fffd5f7dac Mon Sep 17 00:00:00 2001 From: mrnhi Date: Tue, 21 Apr 2020 01:37:24 +0700 Subject: [PATCH 39/70] add preference class for Magento\Customer\Controller\Address\FormPost --- Controller/Customer/Address/FormPost.php | 55 ++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Controller/Customer/Address/FormPost.php diff --git a/Controller/Customer/Address/FormPost.php b/Controller/Customer/Address/FormPost.php new file mode 100644 index 0000000..c09c781 --- /dev/null +++ b/Controller/Customer/Address/FormPost.php @@ -0,0 +1,55 @@ +_formKeyValidator->validate($this->getRequest())) { + return $this->resultRedirectFactory->create()->setPath('*/*/'); + } + + if (!$this->getRequest()->isPost()) { + $this->_getSession()->setAddressFormData($this->getRequest()->getPostValue()); + return $this->resultRedirectFactory->create()->setUrl( + $this->_redirect->error($this->_buildUrl('*/*/edit')) + ); + } + + try { + $address = $this->_extractAddress(); + /*custom code*/ + $address->getExtensionAttributes()->setDistrict($this->getRequest()->getParam('district_id')); + /*end*/ + $this->_addressRepository->save($address); + $this->messageManager->addSuccessMessage(__('You saved the address.')); + $url = $this->_buildUrl('*/*/index', ['_secure' => true]); + return $this->resultRedirectFactory->create()->setUrl($this->_redirect->success($url)); + } catch (InputException $e) { + $this->messageManager->addErrorMessage($e->getMessage()); + foreach ($e->getErrors() as $error) { + $this->messageManager->addErrorMessage($error->getMessage()); + } + } catch (\Exception $e) { + $redirectUrl = $this->_buildUrl('*/*/index'); + $this->messageManager->addExceptionMessage($e, __('We can\'t save the address.')); + } + + $url = $redirectUrl; + if (!$redirectUrl) { + $this->_getSession()->setAddressFormData($this->getRequest()->getPostValue()); + $url = $this->_buildUrl('*/*/edit', ['id' => $this->getRequest()->getParam('id')]); + } + + return $this->resultRedirectFactory->create()->setUrl($this->_redirect->error($url)); + } +} From 79ca44e033f00d1d4dc74efbba11c3a26596bf60 Mon Sep 17 00:00:00 2001 From: mrnhi Date: Tue, 21 Apr 2020 01:40:37 +0700 Subject: [PATCH 40/70] update layout configurations --- Block/Cart/LayoutProcessor.php | 110 +++++++++++++++++++++++++++++ Block/Checkout/AttributeMerger.php | 95 +++++++++++++++++++++++++ 2 files changed, 205 insertions(+) create mode 100644 Block/Cart/LayoutProcessor.php create mode 100644 Block/Checkout/AttributeMerger.php diff --git a/Block/Cart/LayoutProcessor.php b/Block/Cart/LayoutProcessor.php new file mode 100644 index 0000000..ee4a3c8 --- /dev/null +++ b/Block/Cart/LayoutProcessor.php @@ -0,0 +1,110 @@ +config = $config; + $this->topDestinationCountries = $topDestinationCountries ?: + ObjectManager::getInstance()->get(TopDestinationCountries::class); + } + + /** + * Process js Layout of block + * + * @param array $jsLayout + * @return array + * @SuppressWarnings(PHPMD.NPathComplexity) + */ + public function process($jsLayout) + { + $elements = [ + 'city' => [ + 'visible' => $this->isCityActive(), + 'formElement' => 'input', + 'label' => __('City'), + 'value' => null + ], + 'country_id' => [ + 'visible' => true, + 'formElement' => 'select', + 'label' => __('Country'), + 'options' => [], + 'value' => null + ], + 'region_id' => [ + 'visible' => true, + 'formElement' => 'select', + 'label' => __('State/Province'), + 'options' => [], + 'value' => null + ], + 'postcode' => [ + 'visible' => true, + 'formElement' => 'input', + 'label' => __('Zip/Postal Code'), + 'value' => null + ], + 'district' => [ + 'visible' => true, + 'formElement' => 'select', + 'label' => __('District'), + 'options' => [], + 'value' => null + ] + ]; + + if (!isset($jsLayout['components']['checkoutProvider']['dictionaries'])) { + $jsLayout['components']['checkoutProvider']['dictionaries'] = [ + 'country_id' => $this->countryCollection->loadByStore()->setForegroundCountries( + $this->topDestinationCountries->getTopDestinations() + )->toOptionArray(), + 'region_id' => $this->regionCollection->addAllowedCountriesFilter()->toOptionArray(), + 'district' => $this->config->getDistrictOptions() + ]; + } + if (isset($jsLayout['components']['block-summary']['children']['block-shipping']['children'] + ['address-fieldsets']['children']) + ) { + $fieldSetPointer = &$jsLayout['components']['block-summary']['children']['block-shipping'] + ['children']['address-fieldsets']['children']; + $fieldSetPointer = $this->merger->merge($elements, 'checkoutProvider', 'shippingAddress', $fieldSetPointer); + $fieldSetPointer['region_id']['config']['skipValidation'] = true; + } + return $jsLayout; + } +} diff --git a/Block/Checkout/AttributeMerger.php b/Block/Checkout/AttributeMerger.php new file mode 100644 index 0000000..4f3fd2f --- /dev/null +++ b/Block/Checkout/AttributeMerger.php @@ -0,0 +1,95 @@ +inputValidationMap[$validationRule]] = true; + unset($attributeConfig['validation']['input_validation']); + } + + if ($attributeConfig['formElement'] == 'multiline') { + return $this->getMultilineFieldConfig($attributeCode, $attributeConfig, $providerName, $dataScopePrefix); + } + + $uiComponent = isset($this->formElementMap[$attributeConfig['formElement']]) + ? $this->formElementMap[$attributeConfig['formElement']] + : 'Magento_Ui/js/form/element/abstract'; + $elementTemplate = isset($this->templateMap[$attributeConfig['formElement']]) + ? 'ui/form/element/' . $this->templateMap[$attributeConfig['formElement']] + : 'ui/form/element/' . $attributeConfig['formElement']; + + $element = [ + 'component' => isset($additionalConfig['component']) ? $additionalConfig['component'] : $uiComponent, + 'config' => $this->mergeConfigurationNode( + 'config', + $additionalConfig, + [ + 'config' => [ + // customScope is used to group elements within a single + // form (e.g. they can be validated separately) + 'customScope' => $dataScopePrefix, + 'template' => 'ui/form/field', + 'elementTmpl' => $elementTemplate, + ], + ] + ), + 'dataScope' => $dataScopePrefix . '.' . $attributeCode, + 'label' => $attributeConfig['label'], + 'provider' => $providerName, + 'sortOrder' => isset($additionalConfig['sortOrder']) + ? $additionalConfig['sortOrder'] + : $attributeConfig['sortOrder'], + 'validation' => $this->mergeConfigurationNode('validation', $additionalConfig, $attributeConfig), + 'options' => $this->getFieldOptions($attributeCode, $attributeConfig), + 'filterBy' => isset($additionalConfig['filterBy']) ? $additionalConfig['filterBy'] : null, + 'customEntry' => isset($additionalConfig['customEntry']) ? $additionalConfig['customEntry'] : null, + 'visible' => isset($additionalConfig['visible']) ? $additionalConfig['visible'] : true, + ]; + + if ($attributeCode === 'region_id' || $attributeCode === 'country_id' || $attributeCode === 'district') { + unset($element['options']); + $element['deps'] = [$providerName]; + $element['imports'] = [ + 'initialOptions' => 'index = ' . $providerName . ':dictionaries.' . $attributeCode, + 'setOptions' => 'index = ' . $providerName . ':dictionaries.' . $attributeCode + ]; + } + + if (isset($attributeConfig['value']) && $attributeConfig['value'] != null) { + $element['value'] = $attributeConfig['value']; + } elseif (isset($attributeConfig['default']) && $attributeConfig['default'] != null) { + $element['value'] = $attributeConfig['default']; + } else { + $defaultValue = $this->getDefaultValue($attributeCode); + if (null !== $defaultValue) { + $element['value'] = $defaultValue; + } + } + return $element; + } +} \ No newline at end of file From 98f00253cabc81670ae466bfdba9c89193870a7d Mon Sep 17 00:00:00 2001 From: mrnhi Date: Tue, 21 Apr 2020 01:44:26 +0700 Subject: [PATCH 41/70] add Block/Customer/DataProviders/AdditionalConfig.php as an arguments of customer_address_edit block --- .../DataProviders/AdditionalConfig.php | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 Block/Customer/DataProviders/AdditionalConfig.php diff --git a/Block/Customer/DataProviders/AdditionalConfig.php b/Block/Customer/DataProviders/AdditionalConfig.php new file mode 100644 index 0000000..4bb4b6f --- /dev/null +++ b/Block/Customer/DataProviders/AdditionalConfig.php @@ -0,0 +1,62 @@ +config = $config; + $this->serializer = $serializer; + } + + /** + * Get districts + * + * @return array + */ + public function getSerializedDistricts() + { + $districts = $this->config->getDistricts(); + $data = []; + foreach ($districts as $district) { + $data[$district['region_id']][] = [ + 'districtName' => $district['district_name'], + 'districtID' => $district['district_id'] + ]; + } + return $data; + } + + /** + * @return string + */ + public function getJsonData(): string + { + return $this->serializer->serialize([ + 'districts' => $this->getSerializedDistricts() + ]); + } +} From 203496b569b9c9ed47bea9fffb7f79e01ff62dbf Mon Sep 17 00:00:00 2001 From: mrnhi Date: Tue, 21 Apr 2020 02:40:17 +0700 Subject: [PATCH 42/70] delete unnecessary plugins --- Plugin/Customer/Model/Address.php | 20 ------------ .../Model/ResourceModel/AddressRepository.php | 32 ------------------- etc/di.xml | 6 ---- 3 files changed, 58 deletions(-) delete mode 100644 Plugin/Customer/Model/Address.php delete mode 100644 Plugin/Customer/Model/ResourceModel/AddressRepository.php diff --git a/Plugin/Customer/Model/Address.php b/Plugin/Customer/Model/Address.php deleted file mode 100644 index d3ab527..0000000 --- a/Plugin/Customer/Model/Address.php +++ /dev/null @@ -1,20 +0,0 @@ -getExtensionAttributes()->getDistrict(); - - if ($district) { - $result->setDistrict($district); - } - - return $result; - } -} diff --git a/Plugin/Customer/Model/ResourceModel/AddressRepository.php b/Plugin/Customer/Model/ResourceModel/AddressRepository.php deleted file mode 100644 index bc25f88..0000000 --- a/Plugin/Customer/Model/ResourceModel/AddressRepository.php +++ /dev/null @@ -1,32 +0,0 @@ -addressRegistry = $addressRegistry; - } - - public function afterGetById(MageAddressRepository $subject, $result, $addressId) - { - $address = $this->addressRegistry->retrieve($addressId); - $result->getExtensionAttributes()->setDistrict($address->getDistrict()); - - return $result; - } -} diff --git a/etc/di.xml b/etc/di.xml index be2af36..b9f8610 100755 --- a/etc/di.xml +++ b/etc/di.xml @@ -38,18 +38,12 @@ - - - - - - From 7b3ce6de272e74f1fae2d3b5b2eca0e71eac0499 Mon Sep 17 00:00:00 2001 From: mrnhi Date: Tue, 21 Apr 2020 02:41:55 +0700 Subject: [PATCH 43/70] refactor code --- Controller/Customer/Address/FormPost.php | 2 +- Plugin/Quote/Model/Quote/Address.php | 2 +- Setup/InstallData.php | 1 + view/frontend/templates/address/edit.phtml | 2 +- 4 files changed, 4 insertions(+), 3 deletions(-) diff --git a/Controller/Customer/Address/FormPost.php b/Controller/Customer/Address/FormPost.php index c09c781..c82acef 100644 --- a/Controller/Customer/Address/FormPost.php +++ b/Controller/Customer/Address/FormPost.php @@ -28,7 +28,7 @@ public function execute() try { $address = $this->_extractAddress(); /*custom code*/ - $address->getExtensionAttributes()->setDistrict($this->getRequest()->getParam('district_id')); + $address->setCustomAttribute('district', $this->getRequest()->getParam('district_id')); /*end*/ $this->_addressRepository->save($address); $this->messageManager->addSuccessMessage(__('You saved the address.')); diff --git a/Plugin/Quote/Model/Quote/Address.php b/Plugin/Quote/Model/Quote/Address.php index 4dcb320..659f76a 100644 --- a/Plugin/Quote/Model/Quote/Address.php +++ b/Plugin/Quote/Model/Quote/Address.php @@ -9,7 +9,7 @@ class Address public function afterExportCustomerAddress(MageQuoteAddress $subject, $result) { if ($district = $subject->getDistrict()) { - $result->getExtensionAttributes()->setDistrict($district); + $result->setCustomAttribute('district', $district); } return $result; diff --git a/Setup/InstallData.php b/Setup/InstallData.php index 302c884..5933f03 100644 --- a/Setup/InstallData.php +++ b/Setup/InstallData.php @@ -66,6 +66,7 @@ public function install(ModuleDataSetupInterface $setup, ModuleContextInterface 'is_filterable_in_grid' => false, 'visible' => true, 'user_defined' => true, + 'system' => 0, 'is_html_allowed_on_front' => true, 'visible_on_front' => true ]); diff --git a/view/frontend/templates/address/edit.phtml b/view/frontend/templates/address/edit.phtml index eab5eca..8873c0a 100644 --- a/view/frontend/templates/address/edit.phtml +++ b/view/frontend/templates/address/edit.phtml @@ -216,7 +216,7 @@ "districtUpdater": { "districtListId": "#district_id", "defaultRegion": "getRegionId() ?>", - "defaultDistrict": "getAddress()->getExtensionAttributes()->getDistrict() ?>", + "defaultDistrict": "getAddress()->getCustomAttribute('district')->getValue() ?>", "jsonConfig": getAdditionalConfig()->getJsonData(); ?> } } From 7ca660744748f7fa992c2d85a4808a64dc17ce22 Mon Sep 17 00:00:00 2001 From: mrnhi Date: Fri, 24 Apr 2020 15:28:27 +0700 Subject: [PATCH 44/70] delete unnecessary interfaces --- Api/Rest/Service/DistrictProviderInterface.php | 14 -------------- .../Service/Order/SynchronizerInterface.php | 18 ------------------ Api/Rest/Service/Order/TrackerInterface.php | 18 ------------------ .../Shipping/Fee/CalculatorInterface.php | 16 ---------------- .../Shipping/Services/ProviderInterface.php | 16 ---------------- 5 files changed, 82 deletions(-) delete mode 100644 Api/Rest/Service/DistrictProviderInterface.php delete mode 100644 Api/Rest/Service/Order/SynchronizerInterface.php delete mode 100644 Api/Rest/Service/Order/TrackerInterface.php delete mode 100644 Api/Rest/Service/Shipping/Fee/CalculatorInterface.php delete mode 100644 Api/Rest/Service/Shipping/Services/ProviderInterface.php diff --git a/Api/Rest/Service/DistrictProviderInterface.php b/Api/Rest/Service/DistrictProviderInterface.php deleted file mode 100644 index 73ca2c1..0000000 --- a/Api/Rest/Service/DistrictProviderInterface.php +++ /dev/null @@ -1,14 +0,0 @@ - Date: Fri, 24 Apr 2020 15:31:08 +0700 Subject: [PATCH 45/70] rename observer class --- ...r.php => SalesOrderPlaceAfterObserver.php} | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) rename Observer/{SalesOrderPlaceAfterSObserver.php => SalesOrderPlaceAfterObserver.php} (71%) diff --git a/Observer/SalesOrderPlaceAfterSObserver.php b/Observer/SalesOrderPlaceAfterObserver.php similarity index 71% rename from Observer/SalesOrderPlaceAfterSObserver.php rename to Observer/SalesOrderPlaceAfterObserver.php index ad457ff..fcb07f6 100644 --- a/Observer/SalesOrderPlaceAfterSObserver.php +++ b/Observer/SalesOrderPlaceAfterObserver.php @@ -2,14 +2,17 @@ namespace Boolfly\GiaoHangNhanh\Observer; -use Boolfly\GiaoHangNhanh\Api\Rest\Service\Order\SynchronizerInterface; +use Boolfly\GiaoHangNhanh\Model\Api\Rest\Service\Order\Synchronizer; use Boolfly\GiaoHangNhanh\Model\Config; use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Exception\NoSuchEntityException; use Magento\Quote\Model\QuoteRepository; use Psr\Log\LoggerInterface; +use Zend_Http_Client_Exception; -class SalesOrderPlaceAfterSObserver implements ObserverInterface +class SalesOrderPlaceAfterObserver implements ObserverInterface { /** * @var QuoteRepository @@ -22,7 +25,7 @@ class SalesOrderPlaceAfterSObserver implements ObserverInterface private $logger; /** - * @var SynchronizerInterface + * @var Synchronizer */ private $synchronizer; @@ -30,12 +33,12 @@ class SalesOrderPlaceAfterSObserver implements ObserverInterface * SalesOrderAfterSaveObserver constructor. * @param QuoteRepository $quoteRepository * @param LoggerInterface $logger - * @param SynchronizerInterface $synchronizer + * @param Synchronizer $synchronizer */ public function __construct( QuoteRepository $quoteRepository, LoggerInterface $logger, - SynchronizerInterface $synchronizer + Synchronizer $synchronizer ) { $this->logger = $logger; $this->quoteRepository = $quoteRepository; @@ -44,6 +47,10 @@ public function __construct( /** * @inheritDoc + * @param Observer $observer + * @throws NoSuchEntityException + * @throws LocalizedException + * @throws Zend_Http_Client_Exception */ public function execute(Observer $observer) { @@ -51,7 +58,7 @@ public function execute(Observer $observer) $order = $observer->getEvent()->getOrder(); if (false !== strpos($order->getShippingMethod(), Config::GHN_CODE)) { - $quote = $this->quoteRepository->getActive($order->getQuoteId()); + $quote = $this->quoteRepository->get($order->getQuoteId()); $shippingAddress = $quote->getShippingAddress(); $additionalData = [ 'district' => $shippingAddress->getDistrict(), From b7774839e6e9f98134f235a697d28718e793d417 Mon Sep 17 00:00:00 2001 From: mrnhi Date: Fri, 24 Apr 2020 15:33:35 +0700 Subject: [PATCH 46/70] update Block/Customer/DataProviders/AdditionalConfig.php --- Block/Customer/DataProviders/AdditionalConfig.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Block/Customer/DataProviders/AdditionalConfig.php b/Block/Customer/DataProviders/AdditionalConfig.php index 4bb4b6f..b81b6eb 100644 --- a/Block/Customer/DataProviders/AdditionalConfig.php +++ b/Block/Customer/DataProviders/AdditionalConfig.php @@ -37,7 +37,7 @@ public function __construct( * * @return array */ - public function getSerializedDistricts() + private function getDistricts() { $districts = $this->config->getDistricts(); $data = []; @@ -56,7 +56,7 @@ public function getSerializedDistricts() public function getJsonData(): string { return $this->serializer->serialize([ - 'districts' => $this->getSerializedDistricts() + 'districts' => $this->getDistricts() ]); } } From 1533a233535913877f9a8a4b6b394c7cbb928bb9 Mon Sep 17 00:00:00 2001 From: mrnhi Date: Fri, 24 Apr 2020 15:56:54 +0700 Subject: [PATCH 47/70] add classes to process canceling order --- Model/Api/Rest/Service/Order/Cancellation.php | 31 +++++++++++ Observer/SalesOrderCancelAfterObserver.php | 51 +++++++++++++++++++ Plugin/Sales/Model/Order.php | 10 ++-- 3 files changed, 87 insertions(+), 5 deletions(-) create mode 100644 Model/Api/Rest/Service/Order/Cancellation.php create mode 100644 Observer/SalesOrderCancelAfterObserver.php diff --git a/Model/Api/Rest/Service/Order/Cancellation.php b/Model/Api/Rest/Service/Order/Cancellation.php new file mode 100644 index 0000000..0c633f4 --- /dev/null +++ b/Model/Api/Rest/Service/Order/Cancellation.php @@ -0,0 +1,31 @@ +makeRequest( + $this->config->getCancelingOrderUrl(), + [ + 'token' => $this->config->getApiToken(), + 'OrderCode' => $trackingCode + ] + ); + + return $this->checkResponse($response); + } +} diff --git a/Observer/SalesOrderCancelAfterObserver.php b/Observer/SalesOrderCancelAfterObserver.php new file mode 100644 index 0000000..438e6c4 --- /dev/null +++ b/Observer/SalesOrderCancelAfterObserver.php @@ -0,0 +1,51 @@ +cancellation = $cancellation; + } + + /** + * @param Observer $observer + * @throws LocalizedException + * @throws NoSuchEntityException + * @throws Zend_Http_Client_Exception + */ + public function execute(Observer $observer) + { + /** @var \Magento\Sales\Model\Order $order */ + $order = $observer->getEvent()->getOrder(); + $status = $order->getData('ghn_status'); + $trackingCode = $order->getData('tracking_code'); + + if ($status && $trackingCode) { + $result = $this->cancellation->cancel($trackingCode); + + if ($result) { + $order->setData('ghn_canceling_status', self::GHN_SUCCESS_CANCELING_STATUS); + } + } + } +} diff --git a/Plugin/Sales/Model/Order.php b/Plugin/Sales/Model/Order.php index f93b14a..105d812 100644 --- a/Plugin/Sales/Model/Order.php +++ b/Plugin/Sales/Model/Order.php @@ -2,7 +2,7 @@ namespace Boolfly\GiaoHangNhanh\Plugin\Sales\Model; -use Boolfly\GiaoHangNhanh\Api\Rest\Service\Order\TrackerInterface; +use Boolfly\GiaoHangNhanh\Model\Api\Rest\Service\Order\Tracker; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\NoSuchEntityException; use Magento\Sales\Model\Order as MageOrder; @@ -11,15 +11,15 @@ class Order { /** - * @var TrackerInterface + * @var Tracker */ private $tracker; /** * Order constructor. - * @param TrackerInterface $tracker + * @param Tracker $tracker */ - public function __construct(TrackerInterface $tracker) + public function __construct(Tracker $tracker) { $this->tracker = $tracker; } @@ -38,7 +38,7 @@ public function afterCanCancel(MageOrder $subject, $result) $status = $subject->getData('ghn_status'); if ($status && $trackingCode) { - if ($this->tracker->getOrderStatus($trackingCode) != TrackerInterface::DEFAULT_ORDER_STATUS) { + if ($this->tracker->getOrderStatus($trackingCode) != Tracker::DEFAULT_ORDER_STATUS) { $result = false; } } From d0e7e7b942f3c10b2a8cc0a608443c2f61f2f2c4 Mon Sep 17 00:00:00 2001 From: mrnhi Date: Fri, 24 Apr 2020 16:02:41 +0700 Subject: [PATCH 48/70] update service classes --- Model/Api/Rest/Service/DistrictProvider.php | 5 ++--- Model/Api/Rest/Service/Order/Synchronizer.php | 6 ++++-- Model/Api/Rest/Service/Order/Tracker.php | 5 +++-- Model/Api/Rest/Service/Shipping/Fee/Calculator.php | 3 +-- Model/Api/Rest/Service/Shipping/Services/Provider.php | 4 +--- 5 files changed, 11 insertions(+), 12 deletions(-) diff --git a/Model/Api/Rest/Service/DistrictProvider.php b/Model/Api/Rest/Service/DistrictProvider.php index c695d6e..5484831 100644 --- a/Model/Api/Rest/Service/DistrictProvider.php +++ b/Model/Api/Rest/Service/DistrictProvider.php @@ -2,13 +2,12 @@ namespace Boolfly\GiaoHangNhanh\Model\Api\Rest\Service; -use Boolfly\GiaoHangNhanh\Api\Rest\Service\DistrictProviderInterface; use Boolfly\GiaoHangNhanh\Model\Api\Rest\Service; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\NoSuchEntityException; use Zend_Http_Client_Exception; -class DistrictProvider extends Service implements DistrictProviderInterface +class DistrictProvider extends Service { /** * @return array @@ -36,4 +35,4 @@ public function getDistrictList() return $data; } -} \ No newline at end of file +} diff --git a/Model/Api/Rest/Service/Order/Synchronizer.php b/Model/Api/Rest/Service/Order/Synchronizer.php index 7fe3b89..7c3a67b 100644 --- a/Model/Api/Rest/Service/Order/Synchronizer.php +++ b/Model/Api/Rest/Service/Order/Synchronizer.php @@ -2,7 +2,6 @@ namespace Boolfly\GiaoHangNhanh\Model\Api\Rest\Service\Order; -use Boolfly\GiaoHangNhanh\Api\Rest\Service\Order\SynchronizerInterface; use Boolfly\GiaoHangNhanh\Model\Api\Rest\Service; use Boolfly\GiaoHangNhanh\Model\Config; use Magento\Framework\Exception\LocalizedException; @@ -16,8 +15,11 @@ use Psr\Log\LoggerInterface; use Zend_Http_Client_Exception; -class Synchronizer extends Service implements SynchronizerInterface +class Synchronizer extends Service { + const GHN_STATUS_FAIL = 0; + const GHN_STATUS_SUCCESS = 1; + /** * @var StoreManagerInterface */ diff --git a/Model/Api/Rest/Service/Order/Tracker.php b/Model/Api/Rest/Service/Order/Tracker.php index ce705fd..c9cbdeb 100644 --- a/Model/Api/Rest/Service/Order/Tracker.php +++ b/Model/Api/Rest/Service/Order/Tracker.php @@ -2,14 +2,15 @@ namespace Boolfly\GiaoHangNhanh\Model\Api\Rest\Service\Order; -use Boolfly\GiaoHangNhanh\Api\Rest\Service\Order\TrackerInterface; use Boolfly\GiaoHangNhanh\Model\Api\Rest\Service; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\NoSuchEntityException; use Zend_Http_Client_Exception; -class Tracker extends Service implements TrackerInterface +class Tracker extends Service { + const DEFAULT_ORDER_STATUS = 'ReadyToPick'; + /** * @param string $trackingCode * @return string diff --git a/Model/Api/Rest/Service/Shipping/Fee/Calculator.php b/Model/Api/Rest/Service/Shipping/Fee/Calculator.php index 5882b3f..e1c438c 100644 --- a/Model/Api/Rest/Service/Shipping/Fee/Calculator.php +++ b/Model/Api/Rest/Service/Shipping/Fee/Calculator.php @@ -2,13 +2,12 @@ namespace Boolfly\GiaoHangNhanh\Model\Api\Rest\Service\Shipping\Fee; -use Boolfly\GiaoHangNhanh\Api\Rest\Service\Shipping\Fee\CalculatorInterface; use Boolfly\GiaoHangNhanh\Model\Api\Rest\Service; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\NoSuchEntityException; use Zend_Http_Client_Exception; -class Calculator extends Service implements CalculatorInterface +class Calculator extends Service { /** * @param array $request diff --git a/Model/Api/Rest/Service/Shipping/Services/Provider.php b/Model/Api/Rest/Service/Shipping/Services/Provider.php index 46e1ed9..d127760 100644 --- a/Model/Api/Rest/Service/Shipping/Services/Provider.php +++ b/Model/Api/Rest/Service/Shipping/Services/Provider.php @@ -2,13 +2,12 @@ namespace Boolfly\GiaoHangNhanh\Model\Api\Rest\Service\Shipping\Services; -use Boolfly\GiaoHangNhanh\Api\Rest\Service\Shipping\Services\ProviderInterface; use Boolfly\GiaoHangNhanh\Model\Api\Rest\Service; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\NoSuchEntityException; use Zend_Http_Client_Exception; -class Provider extends Service implements ProviderInterface +class Provider extends Service { /** * @param array $request @@ -23,7 +22,6 @@ public function getShippingServices($request) $data = []; if ($this->checkResponse($response)) { - if (is_array($response['response_object']['data'])) { $data = $response['response_object']['data']; } From 878cc881a70933c9617b2908ba297e9b6759ba29 Mon Sep 17 00:00:00 2001 From: mrnhi Date: Fri, 24 Apr 2020 16:03:33 +0700 Subject: [PATCH 49/70] update Console/GenerateRegionCommand.php --- Console/GenerateRegionCommand.php | 54 ++++++++++++++++++++++++------- 1 file changed, 43 insertions(+), 11 deletions(-) diff --git a/Console/GenerateRegionCommand.php b/Console/GenerateRegionCommand.php index 55350ec..1c21b03 100644 --- a/Console/GenerateRegionCommand.php +++ b/Console/GenerateRegionCommand.php @@ -2,7 +2,7 @@ namespace Boolfly\GiaoHangNhanh\Console; -use Boolfly\GiaoHangNhanh\Api\Rest\Service\DistrictProviderInterface; +use Boolfly\GiaoHangNhanh\Model\Api\Rest\Service\DistrictProvider; use Magento\Directory\Model\RegionFactory; use Magento\Framework\App\ResourceConnection; use Magento\Framework\Exception\LocalizedException; @@ -25,7 +25,7 @@ class GenerateRegionCommand extends Command private $regionFactory; /** - * @var DistrictProviderInterface + * @var DistrictProvider */ private $districtProvider; @@ -33,13 +33,13 @@ class GenerateRegionCommand extends Command * GeneratingRegionData constructor. * @param ResourceConnection $resourceConnection * @param RegionFactory $regionFactory - * @param DistrictProviderInterface $districtProvider + * @param DistrictProvider $districtProvider * @param string|null $name */ public function __construct( ResourceConnection $resourceConnection, RegionFactory $regionFactory, - DistrictProviderInterface $districtProvider, + DistrictProvider $districtProvider, $name = null ) { $this->resourceConnection = $resourceConnection; @@ -70,16 +70,18 @@ protected function execute(InputInterface $input, OutputInterface $output) $output->writeln('Generating data. Please wait...'); foreach ($data as $item) { $provinceId = $item['ProvinceID']; + $districtId = $item['DistrictID']; $region = $this->regionFactory->create() ->loadByCode($provinceId, 'VN'); $this->insertData( 'boolfly_giaohangnhanh_district', [ - 'district_id' => $item['DistrictID'], + 'district_id' => $districtId, 'province_id' => $provinceId, 'district_name' => $item['DistrictName'] - ] + ], + ['col' => 'district_id', 'val' => $districtId] ); if (!$region->getId()) { @@ -102,12 +104,42 @@ protected function execute(InputInterface $input, OutputInterface $output) /** * @param string $tableName * @param array $data + * @param array $pairOfColAndVal */ - private function insertData($tableName, $data) + private function insertData($tableName, $data, $pairOfColAndVal = []) { - $this->resourceConnection->getConnection()->insert( - $this->resourceConnection->getTableName($tableName), - $data - ); + if (!$this->checkRecordExist($tableName, $pairOfColAndVal)) { + $this->resourceConnection->getConnection()->insert( + $this->resourceConnection->getTableName($tableName), + $data + ); + } + } + + + /** + * @param string $tableName + * @param array $pairOfColAndVal + * @return bool + */ + private function checkRecordExist($tableName, $pairOfColAndVal = []) + { + $checkingFlag = false; + + if ($pairOfColAndVal) { + $connection = $this->resourceConnection->getConnection(); + $sql = $connection->select()->from( + ['districtTable' => $this->resourceConnection->getTableName($tableName)], + $pairOfColAndVal['col'] + )->where($pairOfColAndVal['col'] . ' = ?', $pairOfColAndVal['val']); + + $rows = $connection->fetchAll($sql); + + if (count($rows)) { + $checkingFlag = true; + } + } + + return $checkingFlag; } } From 436c58d5553a57e34f74f61c7d5f832a9f583ece Mon Sep 17 00:00:00 2001 From: mrnhi Date: Fri, 24 Apr 2020 16:44:30 +0700 Subject: [PATCH 50/70] update Model/Carrier/GHN.php --- Model/Carrier/GHN.php | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Model/Carrier/GHN.php b/Model/Carrier/GHN.php index b51e0e5..93389dc 100644 --- a/Model/Carrier/GHN.php +++ b/Model/Carrier/GHN.php @@ -2,8 +2,8 @@ namespace Boolfly\GiaoHangNhanh\Model\Carrier; -use Boolfly\GiaoHangNhanh\Api\Rest\Service\Shipping\Fee\CalculatorInterface; -use Boolfly\GiaoHangNhanh\Api\Rest\Service\Shipping\Services\ProviderInterface; +use Boolfly\GiaoHangNhanh\Model\Api\Rest\Service\Shipping\Fee\Calculator; +use Boolfly\GiaoHangNhanh\Model\Api\Rest\Service\Shipping\Services\Provider; use Exception; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\NoSuchEntityException; @@ -51,12 +51,12 @@ abstract class GHN extends AbstractCarrier implements CarrierInterface protected $config; /** - * @var CalculatorInterface + * @var Calculator */ protected $calculator; /** - * @var ProviderInterface + * @var Provider */ protected $serviceProvider; @@ -73,8 +73,8 @@ abstract class GHN extends AbstractCarrier implements CarrierInterface * @param ResultFactory $rateResultFactory * @param MethodFactory $rateMethodFactory * @param Config $config - * @param CalculatorInterface $calculator - * @param ProviderInterface $serviceProvider + * @param Calculator $calculator + * @param Provider $serviceProvider * @param array $data */ public function __construct( @@ -84,8 +84,8 @@ public function __construct( ResultFactory $rateResultFactory, MethodFactory $rateMethodFactory, Config $config, - CalculatorInterface $calculator, - ProviderInterface $serviceProvider, + Calculator $calculator, + Provider $serviceProvider, array $data = [] ) { parent::__construct($scopeConfig, $rateErrorFactory, $logger, $data); From c320a62c95e5abcb9afd14841c7b7bc227f274af Mon Sep 17 00:00:00 2001 From: mrnhi Date: Fri, 24 Apr 2020 16:46:38 +0700 Subject: [PATCH 51/70] update configuration --- Model/Config.php | 12 +++++++++++- etc/adminhtml/system.xml | 7 +++++-- etc/config.xml | 3 ++- 3 files changed, 18 insertions(+), 4 deletions(-) diff --git a/Model/Config.php b/Model/Config.php index b28aa7c..d426099 100644 --- a/Model/Config.php +++ b/Model/Config.php @@ -27,7 +27,8 @@ class Config const NOTE_CODE = 'giaohangnhanh_setting/general/note_code'; const DISTRICT = 'giaohangnhanh_setting/general/district'; const GETTING_SERVICES_URL = 'giaohangnhanh_setting/general/get_services_url'; - const GETTING_ORDER_INFOR = 'giaohangnhanh_setting/general/get_order_infor'; + const GETTING_ORDER_INFOR = 'giaohangnhanh_setting/general/get_order_infor_url'; + const CANCELING_ORDER_URL = 'giaohangnhanh_setting/general/cancel_order_url'; /** * @var int @@ -119,6 +120,15 @@ public function getGettingServicesUrl() return $this->getConfig(self::GETTING_SERVICES_URL); } + /** + * @return mixed + * @throws NoSuchEntityException + */ + public function getCancelingOrderUrl() + { + return $this->getConfig(self::CANCELING_ORDER_URL); + } + /** * @return mixed * @throws NoSuchEntityException diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index afe7994..2e8eb49 100644 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -127,15 +127,18 @@ Boolfly\GiaoHangNhanh\Model\Config\Source\NoteCode
- + Boolfly\GiaoHangNhanh\Model\Config\Source\District - + + + + diff --git a/etc/config.xml b/etc/config.xml index 9d11bc6..b4eda81 100644 --- a/etc/config.xml +++ b/etc/config.xml @@ -10,7 +10,8 @@ https://dev-online-gateway.ghn.vn/apiv3-api/api/v1/apiv3/GetDistricts CHOXEMHANGKHONGTHU https://dev-online-gateway.ghn.vn/apiv3-api/api/v1/apiv3/FindAvailableServices - https://dev-online-gateway.ghn.vn/apiv3-api/api/v1/apiv3/OrderInfo + https://dev-online-gateway.ghn.vn/apiv3-api/api/v1/apiv3/OrderInfo + https://dev-online-gateway.ghn.vn/apiv3-api/api/v1/apiv3/CancelOrder From b6231ce7a48977949ec0836073d1b699f86e8776 Mon Sep 17 00:00:00 2001 From: mrnhi Date: Fri, 24 Apr 2020 16:49:18 +0700 Subject: [PATCH 52/70] add new plugins --- .../Order/Create/Billing/Address.php | 48 +++++++++++++++++++ .../Order/Create/Shipping/Address.php | 48 +++++++++++++++++++ 2 files changed, 96 insertions(+) create mode 100644 Plugin/Sales/Block/Adminhtml/Order/Create/Billing/Address.php create mode 100644 Plugin/Sales/Block/Adminhtml/Order/Create/Shipping/Address.php diff --git a/Plugin/Sales/Block/Adminhtml/Order/Create/Billing/Address.php b/Plugin/Sales/Block/Adminhtml/Order/Create/Billing/Address.php new file mode 100644 index 0000000..a438d9c --- /dev/null +++ b/Plugin/Sales/Block/Adminhtml/Order/Create/Billing/Address.php @@ -0,0 +1,48 @@ +addressRepository = $addressRepository; + } + + /** + * @param MageAddress $subject + * @throws LocalizedException + */ + public function beforeGetFormValues(MageAddress $subject) + { + $customerAddressId = $subject->getAddressId(); + + if ($customerAddressId) { + try { + $customerAddress = $this->addressRepository->getById($customerAddressId); + $district = $customerAddress->getCustomAttribute('district'); + + if ($district) { + $subject->getCreateOrderModel()->getBillingAddress()->setDistrict($district->getValue()); + } + } catch (LocalizedException $e) { + throw new LocalizedException( + __("No such customer address with ID %1.", $customerAddressId) + ); + } + } + } +} diff --git a/Plugin/Sales/Block/Adminhtml/Order/Create/Shipping/Address.php b/Plugin/Sales/Block/Adminhtml/Order/Create/Shipping/Address.php new file mode 100644 index 0000000..0fd2642 --- /dev/null +++ b/Plugin/Sales/Block/Adminhtml/Order/Create/Shipping/Address.php @@ -0,0 +1,48 @@ +addressRepository = $addressRepository; + } + + /** + * @param MageAddress $subject + * @throws LocalizedException + */ + public function beforeGetFormValues(MageAddress $subject) + { + $customerAddressId = $subject->getAddressId(); + + if ($customerAddressId) { + try { + $customerAddress = $this->addressRepository->getById($customerAddressId); + $district = $customerAddress->getCustomAttribute('district'); + + if ($district) { + $subject->getAddress()->setDistrict($district->getValue()); + } + } catch (LocalizedException $e) { + throw new LocalizedException( + __("No such customer address with ID %1.", $customerAddressId) + ); + } + } + } +} From 6c5637c5f673fa103e1ec30b135616f6c2ac25db Mon Sep 17 00:00:00 2001 From: mrnhi Date: Fri, 24 Apr 2020 16:50:54 +0700 Subject: [PATCH 53/70] add ui resource to process order in admin --- .../sales_order_create_load_block_data.xml | 27 ++++ ...der_create_load_block_shipping_address.xml | 27 ++++ .../templates/order/create/form/address.phtml | 146 ++++++++++++++++++ .../js/order/create/form/field/district.js | 83 ++++++++++ 4 files changed, 283 insertions(+) create mode 100755 view/adminhtml/layout/sales_order_create_load_block_data.xml create mode 100755 view/adminhtml/layout/sales_order_create_load_block_shipping_address.xml create mode 100644 view/adminhtml/templates/order/create/form/address.phtml create mode 100644 view/adminhtml/web/js/order/create/form/field/district.js diff --git a/view/adminhtml/layout/sales_order_create_load_block_data.xml b/view/adminhtml/layout/sales_order_create_load_block_data.xml new file mode 100755 index 0000000..1d59beb --- /dev/null +++ b/view/adminhtml/layout/sales_order_create_load_block_data.xml @@ -0,0 +1,27 @@ + + + + + + Boolfly_GiaoHangNhanh::order/create/form/address.phtml + + + + + Boolfly\GiaoHangNhanh\Block\Customer\DataProviders\AdditionalConfig + + + + + + Boolfly_GiaoHangNhanh::order/create/form/address.phtml + + + + + Boolfly\GiaoHangNhanh\Block\Customer\DataProviders\AdditionalConfig + + + + + \ No newline at end of file diff --git a/view/adminhtml/layout/sales_order_create_load_block_shipping_address.xml b/view/adminhtml/layout/sales_order_create_load_block_shipping_address.xml new file mode 100755 index 0000000..f6c54ad --- /dev/null +++ b/view/adminhtml/layout/sales_order_create_load_block_shipping_address.xml @@ -0,0 +1,27 @@ + + + + + + Boolfly_GiaoHangNhanh::order/create/form/address.phtml + + + + + Boolfly\GiaoHangNhanh\Block\Customer\DataProviders\AdditionalConfig + + + + + + Boolfly_GiaoHangNhanh::order/create/form/address.phtml + + + + + Boolfly\GiaoHangNhanh\Block\Customer\DataProviders\AdditionalConfig + + + + + diff --git a/view/adminhtml/templates/order/create/form/address.phtml b/view/adminhtml/templates/order/create/form/address.phtml new file mode 100644 index 0000000..60934f0 --- /dev/null +++ b/view/adminhtml/templates/order/create/form/address.phtml @@ -0,0 +1,146 @@ +getData('customerAddressCollection'); + +$addressArray = []; +if ($block->getCustomerId()) { + $addressArray = $addressCollection->setCustomerFilter([$block->getCustomerId()])->toArray(); +} + +/** + * @var \Magento\Sales\ViewModel\Customer\AddressFormatter $customerAddressFormatter + */ +$customerAddressFormatter = $block->getData('customerAddressFormatter'); + +/** + * @var \Magento\Sales\Block\Adminhtml\Order\Create\Billing\Address|\Magento\Sales\Block\Adminhtml\Order\Create\Shipping\Address $block + */ + +$defaultRegion = null; +$defaultDistrict = null; + +if (!empty($block->getFormValues()['region_id'])) { + $defaultRegion = $block->getFormValues()['region_id']; +} + +if (!empty($block->getFormValues()['district'])) { + $defaultDistrict = $block->getFormValues()['district']; +} + +if ($block->getIsShipping()): + $_fieldsContainerId = 'order-shipping_address_fields'; + $_addressChoiceContainerId = 'order-shipping_address_choice'; + ?> + + + + + + + +
+ + getHeaderText() ?> +
+ +
+ getIsShipping()): ?> +
+ getIsAsBilling()): ?>checked /> + +
+ +
+ + getForm()->getHtmlIdPrefix() . 'customer_address_id' ?> +
+ +
+
+
+ +
+ getForm()->toHtml() ?> + +
+ getDontSaveInAddressBook()): ?> checked="checked" class="admin__control-checkbox"/> + +
+
+ getIsShipping() ? 'shipping' : 'billing') . '-overlay'; ?> + + + +
diff --git a/view/adminhtml/web/js/order/create/form/field/district.js b/view/adminhtml/web/js/order/create/form/field/district.js new file mode 100644 index 0000000..1b0e60b --- /dev/null +++ b/view/adminhtml/web/js/order/create/form/field/district.js @@ -0,0 +1,83 @@ +/* global AdminOrder */ +define([ + 'jquery', + 'mage/translate', + 'domReady!' +], function ($, $t) { + 'use strict'; + + $.widget('boolfly.adminDistrictUpdater', { + options: { + districtList: null, + defaultDistrict: null, + districtInput: '#order-shipping_address_district', + districtSelector: '#order-shipping_address_district_id', + regionSelector: '#order-shipping_address_region_id', + addressBox: '#order-shipping_address_fields', + districtSelectorID: 'order-shipping_address_district_id' + }, + + /** + * + * @private + */ + _create: function () { + this.prepairAdditionalField(); + this._bind(); + }, + + _bind: function () { + let self = this, + districtInput = $(self.options.districtInput); + + $(self.options.regionSelector).on('change', function () { + self.updateDistricts($(this).val()); + $(self.options.districtSelector).trigger("change"); + }); + + $(self.options.districtSelector).on('change', function () { + districtInput.val($(this).val()); + districtInput.trigger("change"); + }); + }, + + prepairAdditionalField: function () { + let self = this, + defaultRegion = self.options.defaultRegion, + defaultDistrict = self.options.defaultDistrict; + + $(self.options.districtInput).hide(); + + $(self.options.addressBox + " > .field-district > .control").append( + '' + ); + + if (defaultRegion) { + self.updateDistricts(defaultRegion); + + if (defaultDistrict) { + if ($(self.options.districtSelector + " option[value=" + defaultDistrict + "]").length > 0) { + $(self.options.districtSelector).val(defaultDistrict); + } + } + } + }, + + updateDistricts: function (regionId) { + let self = this; + let districtSelector = $(self.options.districtSelector); + let districtList = self.options.jsonConfig.districts[parseInt(regionId)]; + + districtSelector.children('option:not(:first)').remove(); + + $.each(districtList, function (k, v) { + districtSelector.append(new Option(v.districtName, v.districtID)); + }); + } + }); + + return $.boolfly.adminDistrictUpdater; +}); + From d07d922ddf81e222154353d6709faad6ca2c6849 Mon Sep 17 00:00:00 2001 From: mrnhi Date: Fri, 24 Apr 2020 16:52:03 +0700 Subject: [PATCH 54/70] update database --- etc/db_schema.xml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/etc/db_schema.xml b/etc/db_schema.xml index a4fb5b4..2ad67a7 100644 --- a/etc/db_schema.xml +++ b/etc/db_schema.xml @@ -15,6 +15,8 @@ + @@ -24,5 +26,7 @@ +
\ No newline at end of file From 6699debca77ed0addf77143352bab7de027b15b4 Mon Sep 17 00:00:00 2001 From: mrnhi Date: Fri, 24 Apr 2020 16:53:14 +0700 Subject: [PATCH 55/70] refactor code --- etc/di.xml | 12 +++++++----- etc/events.xml | 5 ++++- view/frontend/templates/address/edit.phtml | 6 +++++- view/frontend/web/js/district-updater.js | 1 - 4 files changed, 16 insertions(+), 8 deletions(-) diff --git a/etc/di.xml b/etc/di.xml index b9f8610..d6eebdc 100755 --- a/etc/di.xml +++ b/etc/di.xml @@ -3,11 +3,6 @@ - - - - - @@ -28,6 +23,7 @@ sales_order.ghn_status sales_order.tracking_code + sales_order.ghn_canceling_status @@ -53,4 +49,10 @@ + + + + + + diff --git a/etc/events.xml b/etc/events.xml index 3c493ec..950c17d 100644 --- a/etc/events.xml +++ b/etc/events.xml @@ -1,6 +1,9 @@ - + + + + \ No newline at end of file diff --git a/view/frontend/templates/address/edit.phtml b/view/frontend/templates/address/edit.phtml index 8873c0a..7292690 100644 --- a/view/frontend/templates/address/edit.phtml +++ b/view/frontend/templates/address/edit.phtml @@ -193,6 +193,10 @@ +getAddress()->getCustomAttribute('district'); +?> +?>