1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Shipping table rates
*
* @author Magento Core Team <core@magentocommerce.com>
*/
namespace Magento\OfflineShipping\Model\ResourceModel\Carrier;
use Magento\Framework\Filesystem;
use Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate\Import;
use Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate\RateQuery;
use Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate\RateQueryFactory;
/**
* @SuppressWarnings(PHPMD.TooManyFields)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*
* @api
* @since 100.0.2
*/
class Tablerate extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{
/**
* Import table rates website ID
*
* @var int
*/
protected $_importWebsiteId = 0;
/**
* Errors in import process
*
* @var array
*/
protected $_importErrors = [];
/**
* Count of imported table rates
*
* @var int
*/
protected $_importedRows = 0;
/**
* Array of unique table rate keys to protect from duplicates
*
* @var array
*/
protected $_importUniqueHash = [];
/**
* Array of countries keyed by iso2 code
*
* @var array
*/
protected $_importIso2Countries;
/**
* Array of countries keyed by iso3 code
*
* @var array
*/
protected $_importIso3Countries;
/**
* Associative array of countries and regions
* [country_id][region_code] = region_id
*
* @var array
*/
protected $_importRegions;
/**
* Import Table Rate condition name
*
* @var string
*/
protected $_importConditionName;
/**
* Array of condition full names
*
* @var array
*/
protected $_conditionFullNames = [];
/**
* @var \Magento\Framework\App\Config\ScopeConfigInterface
* @since 100.1.0
*/
protected $coreConfig;
/**
* @var \Psr\Log\LoggerInterface
* @since 100.1.0
*/
protected $logger;
/**
* @var \Magento\Store\Model\StoreManagerInterface
* @since 100.1.0
*/
protected $storeManager;
/**
* @var \Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate
* @since 100.1.0
*/
protected $carrierTablerate;
/**
* Filesystem instance
*
* @var \Magento\Framework\Filesystem
* @since 100.1.0
*/
protected $filesystem;
/**
* @var Import
*/
private $import;
/**
* @var RateQueryFactory
*/
private $rateQueryFactory;
/**
* Tablerate constructor.
* @param \Magento\Framework\Model\ResourceModel\Db\Context $context
* @param \Psr\Log\LoggerInterface $logger
* @param \Magento\Framework\App\Config\ScopeConfigInterface $coreConfig
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Magento\OfflineShipping\Model\Carrier\Tablerate $carrierTablerate
* @param Filesystem $filesystem
* @param RateQueryFactory $rateQueryFactory
* @param Import $import
* @param null $connectionName
*/
public function __construct(
\Magento\Framework\Model\ResourceModel\Db\Context $context,
\Psr\Log\LoggerInterface $logger,
\Magento\Framework\App\Config\ScopeConfigInterface $coreConfig,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\OfflineShipping\Model\Carrier\Tablerate $carrierTablerate,
\Magento\Framework\Filesystem $filesystem,
Import $import,
RateQueryFactory $rateQueryFactory,
$connectionName = null
) {
parent::__construct($context, $connectionName);
$this->coreConfig = $coreConfig;
$this->logger = $logger;
$this->storeManager = $storeManager;
$this->carrierTablerate = $carrierTablerate;
$this->filesystem = $filesystem;
$this->import = $import;
$this->rateQueryFactory = $rateQueryFactory;
}
/**
* Define main table and id field name
*
* @return void
*/
protected function _construct()
{
$this->_init('shipping_tablerate', 'pk');
}
/**
* Return table rate array or false by rate request
*
* @param \Magento\Quote\Model\Quote\Address\RateRequest $request
* @return array|bool
*/
public function getRate(\Magento\Quote\Model\Quote\Address\RateRequest $request)
{
$connection = $this->getConnection();
$select = $connection->select()->from($this->getMainTable());
/** @var RateQuery $rateQuery */
$rateQuery = $this->rateQueryFactory->create(['request' => $request]);
$rateQuery->prepareSelect($select);
$bindings = $rateQuery->getBindings();
$result = $connection->fetchRow($select, $bindings);
// Normalize destination zip code
if ($result && $result['dest_zip'] == '*') {
$result['dest_zip'] = '';
}
return $result;
}
/**
* @param array $condition
* @return $this
* @throws \Magento\Framework\Exception\LocalizedException
*/
private function deleteByCondition(array $condition)
{
$connection = $this->getConnection();
$connection->beginTransaction();
$connection->delete($this->getMainTable(), $condition);
$connection->commit();
return $this;
}
/**
* @param array $fields
* @param array $values
* @throws \Magento\Framework\Exception\LocalizedException
* @return void
*/
private function importData(array $fields, array $values)
{
$connection = $this->getConnection();
$connection->beginTransaction();
try {
if (count($fields) && count($values)) {
$this->getConnection()->insertArray($this->getMainTable(), $fields, $values);
$this->_importedRows += count($values);
}
} catch (\Magento\Framework\Exception\LocalizedException $e) {
$connection->rollBack();
throw new \Magento\Framework\Exception\LocalizedException(__('Unable to import data'), $e);
} catch (\Exception $e) {
$connection->rollBack();
$this->logger->critical($e);
throw new \Magento\Framework\Exception\LocalizedException(
__('Something went wrong while importing table rates.')
);
}
$connection->commit();
}
/**
* Upload table rate file and import data from it
*
* @param \Magento\Framework\DataObject $object
* @throws \Magento\Framework\Exception\LocalizedException
* @return \Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate
* @todo: this method should be refactored as soon as updated design will be provided
* @see https://wiki.corp.x.com/display/MCOMS/Magento+Filesystem+Decisions
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function uploadAndImport(\Magento\Framework\DataObject $object)
{
/**
* @var \Magento\Framework\App\Config\Value $object
*/
if (empty($_FILES['groups']['tmp_name']['tablerate']['fields']['import']['value'])) {
return $this;
}
$filePath = $_FILES['groups']['tmp_name']['tablerate']['fields']['import']['value'];
$websiteId = $this->storeManager->getWebsite($object->getScopeId())->getId();
$conditionName = $this->getConditionName($object);
$file = $this->getCsvFile($filePath);
try {
// delete old data by website and condition name
$condition = [
'website_id = ?' => $websiteId,
'condition_name = ?' => $conditionName,
];
$this->deleteByCondition($condition);
$columns = $this->import->getColumns();
$conditionFullName = $this->_getConditionFullName($conditionName);
foreach ($this->import->getData($file, $websiteId, $conditionName, $conditionFullName) as $bunch) {
$this->importData($columns, $bunch);
}
} catch (\Exception $e) {
$this->logger->critical($e);
throw new \Magento\Framework\Exception\LocalizedException(
__('Something went wrong while importing table rates.')
);
} finally {
$file->close();
}
if ($this->import->hasErrors()) {
$error = __(
'We couldn\'t import this file because of these errors: %1',
implode(" \n", $this->import->getErrors())
);
throw new \Magento\Framework\Exception\LocalizedException($error);
}
}
/**
* @param \Magento\Framework\DataObject $object
* @return mixed|string
* @since 100.1.0
*/
public function getConditionName(\Magento\Framework\DataObject $object)
{
if ($object->getData('groups/tablerate/fields/condition_name/inherit') == '1') {
$conditionName = (string)$this->coreConfig->getValue('carriers/tablerate/condition_name', 'default');
} else {
$conditionName = $object->getData('groups/tablerate/fields/condition_name/value');
}
return $conditionName;
}
/**
* @param string $filePath
* @return \Magento\Framework\Filesystem\File\ReadInterface
*/
private function getCsvFile($filePath)
{
$pathInfo = pathinfo($filePath);
$dirName = isset($pathInfo['dirname']) ? $pathInfo['dirname'] : '';
$fileName = isset($pathInfo['basename']) ? $pathInfo['basename'] : '';
$directoryRead = $this->filesystem->getDirectoryReadByPath($dirName);
return $directoryRead->openFile($fileName);
}
/**
* Return import condition full name by condition name code
*
* @param string $conditionName
* @return string
*/
protected function _getConditionFullName($conditionName)
{
if (!isset($this->_conditionFullNames[$conditionName])) {
$name = $this->carrierTablerate->getCode('condition_name_short', $conditionName);
$this->_conditionFullNames[$conditionName] = $name;
}
return $this->_conditionFullNames[$conditionName];
}
/**
* Save import data batch
*
* @param array $data
* @return \Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate
*/
protected function _saveImportData(array $data)
{
if (!empty($data)) {
$columns = [
'website_id',
'dest_country_id',
'dest_region_id',
'dest_zip',
'condition_name',
'condition_value',
'price',
];
$this->getConnection()->insertArray($this->getMainTable(), $columns, $data);
$this->_importedRows += count($data);
}
return $this;
}
}