PriceList.php 12.5 KB
Newer Older
1
2
3
4
<?php

namespace Drupal\commerce_pricelist\Entity;

5
use Drupal\commerce\EntityHelper;
6
use Drupal\Core\Datetime\DrupalDateTime;
7
8
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Field\BaseFieldDefinition;
9
use Drupal\commerce\Entity\CommerceContentEntityBase;
10
11
use Drupal\Core\Entity\EntityChangedTrait;
use Drupal\Core\Entity\EntityTypeInterface;
12
use Drupal\datetime\Plugin\Field\FieldType\DateTimeItemInterface;
13
use Drupal\user\EntityOwnerTrait;
14
use Drupal\user\UserInterface;
15
16
17
18
19

/**
 * Defines the Price list entity.
 *
 * @ContentEntityType(
20
 *   id = "commerce_pricelist",
21
 *   label = @Translation("Price list"),
22
23
24
25
26
27
28
 *   label_collection = @Translation("Price lists"),
 *   label_singular = @Translation("price list"),
 *   label_plural = @Translation("price lists"),
 *   label_count = @PluralTranslation(
 *     singular = "@count price list",
 *     plural = "@count price lists",
 *   ),
29
 *   handlers = {
30
31
 *     "event" = "Drupal\commerce_pricelist\Event\PriceListEvent",
 *     "storage" = "Drupal\commerce\CommerceContentEntityStorage",
32
33
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
 *     "list_builder" = "Drupal\commerce_pricelist\PriceListListBuilder",
34
 *     "views_data" = "Drupal\commerce\CommerceEntityViewsData",
35
36
37
38
 *     "form" = {
 *       "default" = "Drupal\commerce_pricelist\Form\PriceListForm",
 *       "add" = "Drupal\commerce_pricelist\Form\PriceListForm",
 *       "edit" = "Drupal\commerce_pricelist\Form\PriceListForm",
39
 *       "duplicate" = "Drupal\commerce_pricelist\Form\PriceListForm",
40
 *       "delete" = "Drupal\Core\Entity\ContentEntityDeleteForm",
41
 *     },
42
43
44
 *     "local_task_provider" = {
 *       "default" = "Drupal\entity\Menu\DefaultEntityLocalTaskProvider",
 *     },
45
 *     "route_provider" = {
46
 *       "default" = "Drupal\commerce_pricelist\PriceListRouteProvider",
47
 *       "delete-multiple" = "Drupal\entity\Routing\DeleteMultipleRouteProvider",
48
49
 *     },
 *   },
50
51
 *   admin_permission = "administer commerce_pricelist",
 *   base_table = "commerce_pricelist",
52
53
54
55
56
 *   entity_keys = {
 *     "id" = "id",
 *     "bundle" = "type",
 *     "label" = "name",
 *     "uuid" = "uuid",
57
 *     "status" = "status",
58
59
 *     "owner" = "uid",
 *     "uid" = "uid",
60
61
 *   },
 *   links = {
62
63
64
 *     "add-page" = "/price-list/add",
 *     "add-form" = "/price-list/add/{type}",
 *     "edit-form" = "/price-list/{commerce_pricelist}/edit",
65
 *     "duplicate-form" = "/price-list/{commerce_pricelist}/duplicate",
66
67
68
 *     "delete-form" = "/price-list/{commerce_pricelist}/delete",
 *     "delete-multiple-form" = "/admin/commerce/price-lists/delete",
 *     "collection" = "/admin/commerce/price-lists",
69
 *   },
70
 *   field_ui_base_route = "entity.commerce_pricelist.bundle_list"
71
72
 * )
 */
73
74
class PriceList extends CommerceContentEntityBase implements PriceListInterface {

75
  use EntityChangedTrait;
76
  use EntityOwnerTrait;
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95

  /**
   * {@inheritdoc}
   */
  public function getName() {
    return $this->get('name')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setName($name) {
    $this->set('name', $name);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
96
97
  public function getStores() {
    return $this->getTranslatedReferencedEntities('stores');
98
99
100
101
102
  }

  /**
   * {@inheritdoc}
   */
103
104
  public function setStores(array $stores) {
    $this->set('stores', $stores);
105
106
107
108
109
110
    return $this;
  }

  /**
   * {@inheritdoc}
   */
111
112
113
114
115
116
  public function getStoreIds() {
    $store_ids = [];
    foreach ($this->get('stores') as $field_item) {
      $store_ids[] = $field_item->target_id;
    }
    return $store_ids;
117
118
119
120
121
  }

  /**
   * {@inheritdoc}
   */
122
123
  public function setStoreIds(array $store_ids) {
    $this->set('stores', $store_ids);
124
125
126
    return $this;
  }

127
128
129
130
  /**
   * {@inheritdoc}
   */
  public function getCustomer() {
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
    if ($this->get('customers')->isEmpty()) {
      return NULL;
    }
    return $this->get('customers')->get(0)->entity;
  }

  /**
   * {@inheritdoc}
   */
  public function getCustomers() {
    $customers = [];
    foreach ($this->get('customers') as $field_item) {
      if ($field_item->isEmpty() || !$field_item->entity) {
        continue;
      }
      $customers[] = $field_item->entity;
    }
    return $customers;
149
150
151
152
153
154
  }

  /**
   * {@inheritdoc}
   */
  public function setCustomer(UserInterface $user) {
155
156
157
158
159
160
161
162
    return $this->setCustomers([$user]);
  }

  /**
   * {@inheritdoc}
   */
  public function setCustomers(array $users) {
    $this->set('customers', $users);
163
164
165
166
167
168
169
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getCustomerId() {
170
171
172
173
    if ($this->get('customers')->isEmpty()) {
      return NULL;
    }
    return $this->get('customers')->get(0)->target_id;
174
175
176
177
178
179
  }

  /**
   * {@inheritdoc}
   */
  public function setCustomerId($uid) {
180
    $this->set('customers', ['target_id' => $uid]);
181
182
183
184
185
186
    return $this;
  }

  /**
   * {@inheritdoc}
   */
187
188
189
190
191
192
  public function getCustomerRoles() {
    $roles = [];
    foreach ($this->get('customer_roles') as $field_item) {
      $roles[] = $field_item->target_id;
    }
    return $roles;
193
194
195
196
197
  }

  /**
   * {@inheritdoc}
   */
198
199
  public function setCustomerRoles(array $rids) {
    $this->set('customer_roles', $rids);
200
201
202
    return $this;
  }

203
204
205
  /**
   * {@inheritdoc}
   */
206
207
  public function getStartDate($store_timezone = 'UTC') {
    return new DrupalDateTime($this->get('start_date')->value, $store_timezone);
208
209
210
211
212
213
  }

  /**
   * {@inheritdoc}
   */
  public function setStartDate(DrupalDateTime $start_date) {
214
    $this->get('start_date')->value = $start_date->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT);
215
216
217
218
219
220
    return $this;
  }

  /**
   * {@inheritdoc}
   */
221
  public function getEndDate($store_timezone = 'UTC') {
222
    if (!$this->get('end_date')->isEmpty()) {
223
      return new DrupalDateTime($this->get('end_date')->value, $store_timezone);
224
    }
225
226
227
228
229
  }

  /**
   * {@inheritdoc}
   */
230
  public function setEndDate(DrupalDateTime $end_date = NULL) {
231
232
233
234
    $this->get('end_date')->value = NULL;
    if ($end_date) {
      $this->get('end_date')->value = $end_date->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT);
    }
235
236
237
    return $this;
  }

238
239
240
  /**
   * {@inheritdoc}
   */
241
242
243
244
245
246
247
248
249
250
  public function getWeight() {
    return (int) $this->get('weight')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setWeight($weight) {
    $this->set('weight', $weight);
    return $this;
251
252
  }

253
254
255
  /**
   * {@inheritdoc}
   */
256
257
  public function isEnabled() {
    return (bool) $this->getEntityKey('status');
258
259
260
261
262
  }

  /**
   * {@inheritdoc}
   */
263
264
265
266
267
268
269
270
271
272
273
  public function setEnabled($enabled) {
    $this->set('status', (bool) $enabled);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getItemIds() {
    if ($this->isNew()) {
      return [];
274
    }
275
276
277
278
279
    $query = $this->entityTypeManager()->getStorage('commerce_pricelist_item')->getQuery();
    $query->condition('price_list_id', $this->id());
    $result = $query->execute();

    return $result;
280
281
  }

282
283
284
285
  /**
   * {@inheritdoc}
   */
  public static function postDelete(EntityStorageInterface $storage, array $entities) {
286
287
288
289
290
291
292
    $price_list_item_storage = \Drupal::entityTypeManager()->getStorage('commerce_pricelist_item');
    $query = $price_list_item_storage->getQuery();
    $query->condition('price_list_id', EntityHelper::extractIds($entities), 'IN');
    $result = $query->execute();
    if (!empty($result)) {
      // @todo This can crash due to there potentially being thousands of items.
      $price_list_items = $price_list_item_storage->loadMultiple($result);
293
294
295
296
      $price_list_item_storage->delete($price_list_items);
    }
  }

297
298
299
300
  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
301
    $fields = parent::baseFieldDefinitions($entity_type);
302
303
304
305
306
    $fields += static::ownerBaseFieldDefinitions($entity_type);

    $fields['uid']
      ->setLabel(t('Owner'))
      ->setDescription(t('The user that owns this price list.'));
307
308
309

    $fields['name'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Name'))
310
      ->setDescription(t('The name of the price list.'))
311
312
313
314
315
316
317
318
319
320
321
322
      ->setRequired(TRUE)
      ->setSettings([
        'max_length' => 50,
        'text_processing' => 0,
      ])
      ->setDefaultValue('')
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => 1,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);
323

324
325
326
327
328
329
    $fields['stores'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Stores'))
      ->setDescription(t('The stores for which the price list is valid.'))
      ->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
      ->setRequired(TRUE)
      ->setSetting('target_type', 'commerce_store')
330
331
      ->setSetting('handler', 'default')
      ->setTranslatable(TRUE)
332
      ->setDisplayConfigurable('form', TRUE)
333
      ->setDisplayOptions('form', [
334
        'type' => 'commerce_entity_select',
335
        'weight' => 2,
336
      ]);
337

338
339
340
    $fields['customers'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Customers'))
      ->setDescription(t('The customers for which the price list is valid.'))
341
342
      ->setSetting('target_type', 'user')
      ->setSetting('handler', 'default')
343
      ->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
344
345
346
347
348
349
350
351
352
      ->setDisplayOptions('form', [
        'type' => 'entity_reference_autocomplete',
        'settings' => [
          'match_operator' => 'CONTAINS',
          'size' => '60',
          'placeholder' => '',
        ],
      ]);

353
354
355
356
    $fields['customer_roles'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Customer roles'))
      ->setDescription(t('The customer roles for which the price list is valid.'))
      ->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
357
358
      ->setSetting('target_type', 'user_role')
      ->setDisplayOptions('form', [
359
        'type' => 'options_buttons',
360
361
      ]);

362
363
    $fields['start_date'] = BaseFieldDefinition::create('datetime')
      ->setLabel(t('Start date'))
364
365
      ->setDescription(t('The date the price list becomes valid.'))
      ->setRequired(TRUE)
366
      ->setSetting('datetime_type', 'datetime')
367
      ->setDefaultValueCallback('Drupal\commerce_pricelist\Entity\PriceList::getDefaultStartDate')
368
      ->setDisplayOptions('form', [
369
        'type' => 'commerce_store_datetime',
370
371
        'weight' => 5,
      ]);
372

373
374
    $fields['end_date'] = BaseFieldDefinition::create('datetime')
      ->setLabel(t('End date'))
375
376
      ->setDescription(t('The date after which the price list is invalid.'))
      ->setRequired(FALSE)
377
378
      ->setSetting('datetime_type', 'datetime')
      ->setSetting('datetime_optional_label', t('Provide an end date'))
379
      ->setDisplayConfigurable('form', TRUE)
380
      ->setDisplayOptions('form', [
381
        'type' => 'commerce_store_datetime',
382
383
384
385
386
387
388
389
390
        'weight' => 6,
      ]);

    $fields['weight'] = BaseFieldDefinition::create('integer')
      ->setLabel(t('Weight'))
      ->setDescription(t('The weight of this price list in relation to other price lists.'))
      ->setDefaultValue(0);

    $fields['status'] = BaseFieldDefinition::create('boolean')
391
      ->setLabel(t('Status'))
392
393
      ->setDescription(t('Whether the price list is enabled.'))
      ->setDefaultValue(TRUE)
394
395
396
397
398
      ->setRequired(TRUE)
      ->setSettings([
        'on_label' => t('Enabled'),
        'off_label' => t('Disabled'),
      ])
399
      ->setDisplayConfigurable('form', TRUE)
400
      ->setDisplayOptions('form', [
401
        'type' => 'options_buttons',
402
      ]);
403
404
405

    $fields['changed'] = BaseFieldDefinition::create('changed')
      ->setLabel(t('Changed'))
406
      ->setDescription(t('The time when the price list was last edited.'));
407
408
409
410

    return $fields;
  }

411
412
413
414
415
416
417
418
419
420
  /**
   * Default value callback for 'start_date' base field definition.
   *
   * @see ::baseFieldDefinitions()
   *
   * @return string
   *   The default value (date string).
   */
  public static function getDefaultStartDate() {
    $timestamp = \Drupal::time()->getRequestTime();
421
    return gmdate(DateTimeItemInterface::DATETIME_STORAGE_FORMAT, $timestamp);
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
  }

  /**
   * Helper callback for uasort() to sort price lists by weight and label.
   *
   * @param \Drupal\commerce_pricelist\Entity\PriceListInterface $a
   *   The first price list to sort.
   * @param \Drupal\commerce_pricelist\Entity\PriceListInterface $b
   *   The second priice list to sort.
   *
   * @return int
   *   The comparison result for uasort().
   */
  public static function sort(PriceListInterface $a, PriceListInterface $b) {
    $a_weight = $a->getWeight();
    $b_weight = $b->getWeight();
    if ($a_weight == $b_weight) {
      $a_label = $a->label();
      $b_label = $b->label();
      return strnatcasecmp($a_label, $b_label);
    }
    return ($a_weight < $b_weight) ? -1 : 1;
  }

446
}