-
Notifications
You must be signed in to change notification settings - Fork 169
/
ShippingCategories.php
296 lines (248 loc) · 9.35 KB
/
ShippingCategories.php
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
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\commerce\services;
use Craft;
use craft\commerce\db\Table;
use craft\commerce\elements\Product;
use craft\commerce\models\ShippingCategory;
use craft\commerce\records\ShippingCategory as ShippingCategoryRecord;
use craft\db\Query;
use craft\helpers\ArrayHelper;
use craft\queue\jobs\ResaveElements;
use yii\base\Component;
use yii\base\Exception;
use yii\base\InvalidConfigException;
/**
* Shipping category service.
*
* @property array|ShippingCategory[] $allShippingCategories all Shipping Categories
* @property null|ShippingCategory $defaultShippingCategory the default shipping category
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 2.0
*/
class ShippingCategories extends Component
{
/**
* @var ShippingCategory[]|null
*/
private $_allShippingCategories = null;
/**
* Returns all Shipping Categories
*
* @return ShippingCategory[]
*/
public function getAllShippingCategories(): array
{
if ($this->_allShippingCategories === null) {
$results = $this->_createShippingCategoryQuery()->all();
$this->_allShippingCategories = [];
foreach ($results as $result) {
$shippingCategory = new ShippingCategory($result);
$this->_allShippingCategories[] = $shippingCategory;
}
}
return $this->_allShippingCategories;
}
/**
* Returns all Shipping category names, by ID.
*
* @return array
*/
public function getAllShippingCategoriesAsList(): array
{
$categories = $this->getAllShippingCategories();
return ArrayHelper::map($categories, 'id', 'name');
}
/**
* Get a shipping category by its ID.
*
* @param int $shippingCategoryId
* @return ShippingCategory|null
*/
public function getShippingCategoryById(int $shippingCategoryId)
{
$categories = $this->getAllShippingCategories();
return ArrayHelper::firstWhere($categories, 'id', $shippingCategoryId);
}
/**
* Get a shipping category by its handle.
*
* @param string $shippingCategoryHandle
* @return ShippingCategory|null
*/
public function getShippingCategoryByHandle(string $shippingCategoryHandle)
{
$categories = $this->getAllShippingCategories();
return ArrayHelper::firstWhere($categories, 'handle', $shippingCategoryHandle);
}
/**
* Returns the default shipping category.
*
* @return ShippingCategory
* @throws InvalidConfigException
*/
public function getDefaultShippingCategory(): ShippingCategory
{
$categories = $this->getAllShippingCategories();
$default = ArrayHelper::firstWhere($categories, 'default', true);
if (!$default) {
$default = ArrayHelper::firstValue($categories);
}
if (!$default) {
throw new InvalidConfigException('Commerce must have at least one (default) shipping category set up.');
}
return $default;
}
/**
* @param ShippingCategory $shippingCategory
* @param bool $runValidation should we validate this before saving.
* @return bool
* @throws Exception
* @throws \Exception
*/
public function saveShippingCategory(ShippingCategory $shippingCategory, bool $runValidation = true): bool
{
if ($shippingCategory->id) {
$record = ShippingCategoryRecord::findOne($shippingCategory->id);
if (!$record) {
throw new Exception(Craft::t('commerce', 'No shipping category exists with the ID “{id}”',
['id' => $shippingCategory->id]));
}
} else {
$record = new ShippingCategoryRecord();
}
if ($runValidation && !$shippingCategory->validate()) {
Craft::info('Shipping category not saved due to validation error.', __METHOD__);
return false;
}
$record->name = $shippingCategory->name;
$record->handle = $shippingCategory->handle;
$record->description = $shippingCategory->description;
$record->default = $shippingCategory->default;
// Save it!
$record->save(false);
// Now that we have a record ID, save it on the model
$shippingCategory->id = $record->id;
// If this was the default make all others not the default.
if ($shippingCategory->default) {
ShippingCategoryRecord::updateAll(['default' => false], ['not', ['id' => $record->id]]);
}
// Product type IDs this shipping category is available to
$currentProductTypeIds = (new Query())
->select(['productTypeId'])
->from([Table::PRODUCTTYPES_SHIPPINGCATEGORIES])
->where(['shippingCategoryId' => $shippingCategory->id])
->column();
// Newly set product types this shipping category is available to
$newProductTypeIds = ArrayHelper::getColumn($shippingCategory->getProductTypes(), 'id');
foreach ($currentProductTypeIds as $oldProductTypeId) {
// If we are removing a product type for this shipping category the products of that type should be re-saved
if (!in_array($oldProductTypeId, $newProductTypeIds, false)) {
// Re-save all products that no longer have this shipping category available to them
$this->_resaveProductsByProductTypeId($oldProductTypeId);
}
}
foreach ($newProductTypeIds as $newProductTypeId) {
// If we are adding a product type for this shipping category the products of that type should be re-saved
if (!in_array($newProductTypeId, $currentProductTypeIds, false)) {
// Re-save all products when assigning this shipping category available to them
$this->_resaveProductsByProductTypeId($newProductTypeId);
}
}
// Remove existing Categories <-> ProductType relationships
Craft::$app->getDb()->createCommand()->delete(Table::PRODUCTTYPES_SHIPPINGCATEGORIES, ['shippingCategoryId' => $shippingCategory->id])->execute();
// Add back the new categories
foreach ($shippingCategory->getProductTypes() as $productType) {
$data = ['productTypeId' => (int)$productType->id, 'shippingCategoryId' => (int)$shippingCategory->id];
Craft::$app->getDb()->createCommand()->insert(Table::PRODUCTTYPES_SHIPPINGCATEGORIES, $data)->execute();
}
// Clear Service cache
$this->_allShippingCategories = null;
return true;
}
/**
* Re-save products by product type id
*
* @param int $productTypeId
*/
private function _resaveProductsByProductTypeId(int $productTypeId)
{
Craft::$app->getQueue()->push(new ResaveElements([
'elementType' => Product::class,
'criteria' => [
'typeId' => $productTypeId,
'siteId' => '*',
'unique' => true,
'status' => null,
'enabledForSite' => false,
],
]));
}
/**
* @param int $id
* @return bool
*/
public function deleteShippingCategoryById($id): bool
{
$all = $this->getAllShippingCategories();
if (count($all) === 1) {
return false;
}
$record = ShippingCategoryRecord::findOne($id);
if ($record) {
return (bool)$record->delete();
}
// Clear cache
$this->_allShippingCategories = null;
return false;
}
/**
* @param $productTypeId
* @return array
*/
public function getShippingCategoriesByProductTypeId($productTypeId): array
{
$rows = $this->_createShippingCategoryQuery()
->innerJoin(Table::PRODUCTTYPES_SHIPPINGCATEGORIES . ' productTypeShippingCategories', '[[shippingCategories.id]] = [[productTypeShippingCategories.shippingCategoryId]]')
->where(['productTypeShippingCategories.productTypeId' => $productTypeId])
->all();
// Always need at least the default category
if (empty($rows)) {
$category = $this->getDefaultShippingCategory();
if (!$category) {
return [];
}
$shippingCategory = $this->getDefaultShippingCategory();
return [$shippingCategory->id => $shippingCategory];
}
$shippingCategories = [];
foreach ($rows as $row) {
$key = $row['id'];
$shippingCategories[$key] = new ShippingCategory($row);
}
return $shippingCategories;
}
/**
* Returns a Query object prepped for retrieving shipping categories.
*
* @return Query
*/
private function _createShippingCategoryQuery(): Query
{
return (new Query())
->select([
'shippingCategories.id',
'shippingCategories.name',
'shippingCategories.handle',
'shippingCategories.description',
'shippingCategories.default',
'shippingCategories.dateCreated',
'shippingCategories.dateUpdated',
])
->from([Table::SHIPPINGCATEGORIES . ' shippingCategories']);
}
}