Version: current

      1 <?php
      2
      3 /**
      4  * Элемент заказа
      5  *
      6  * @package cart
      7  * @author inxo, menedem, dvp
      8  */
      9 class OrderItem extends DataObject {
     10
     11     // кол-во товара
     12     protected $_quantity;
     13     protected $_title;
     14     protected $_price;
     15     protected $_id;
     16     // id-товара
     17     protected $_productId;
     18     // id-вариации
     19     protected $_variationId = 0;
     20
     21     public static $db = array(
     22         'Title' => 'Text',
     23         'ItemPrice' => 'CatalogPrice',
     24         'Quantity' => 'Int'
     25     );
     26
     27     public static $has_one = array(
     28         'Order' => 'Order',
     29         'Linked' => 'Product',
     30     );
     31
     32     public static $summary_fields = array('ImportID', 'Title', 'ItemPrice', 'Quantity', 'TotalPrice');
     33
     34     public static $casting = array(
     35         'Price' => 'CatalogPrice',
     36         'ItemPrice' => 'CatalogPrice',
     37         'TotalPrice' => 'CatalogPrice',
     38         'ImportID' => 'Varchar',
     39         'Link' => 'Varchar'
     40     );
     41
     42     function getCMSFields() {
     43         $fields = parent::getCMSFields();
     44         $fields->removeByName('LinkedID');
     45         $fields->removeByName('Order');
     46         $fields->replaceField('Title', new OrderItemField('LinkedID', _t('Cart.ProductTitle', 'Title')));
     47         $fields->removeByName('ItemPrice');
     48
     49         return $fields;
     50     }
     51
     52     function fieldLabels($includerelations = true) {
     53         $labels = parent::fieldLabels($includerelations);
     54         $labels['TotalPrice'] = _t('OrderItem.TotalPrice', 'Total Price');
     55         $labels['ImportID'] = singleton('Product')->fieldLabel('ImportID');
     56         $labels['Link'] = _t('OrderItem.Link', 'Product Link');
     57         return $labels;
     58     }
     59
     60     public function __construct($product = null, $quantity = 1) {
     61         parent::__construct();
     62
     63         if (is_array($product)) {
     64             $this->ID = $this->_id = $product['ID'];
     65             $this->Title = $this->_title = $product['Title'];
     66             $this->ItemPrice = $this->_price = $product['ItemPrice'];
     67             $this->LinkedID = $this->_productId = $product['LinkedID'];
     68             $this->OrderID = $product['OrderID'];
     69             $this->_quantity = $quantity;
     70             $this->Quantity = $this->_quantity = $product['Quantity'];
     71             if (isset($product['VariationID']))
     72                 $this->VariationID = $this->_variationId = $product['VariationID'];
     73             // !!! почему только для массивов ?
     74             $this->extend('updateConstructor', $product);
     75         }
     76
     77         if (is_object($product)) {
     78             $this->_productId = $product->ID;
     79             $this->_quantity = $quantity;
     80             $this->Title = $this->_title = $product->Title;
     81             $this->_price = $this->getPrice();
     82             if (isset($product->VariationID))
     83                 $this->VariationID = $this->_variationId = $product->VariationID;
     84         }
     85
     86     }
     87
     88     public function Order() {
     89         if ($this->ID) {
     90             return DataObject::get_by_id('Order', $this->OrderID);
     91         } else {
     92             if ($this->Order) {
     93                 return $this->Order;
     94             } else {
     95                 return Cart::current_order();
     96             }
     97         }
     98     }
     99
    100     /**
    101      * Сравнение элементов заказа
    102      * @param OrderItem элемент заказа
    103      * @return Boolean
    104      */
    105     function hasSameContent($orderItem) {
    106         $rs = $orderItem instanceof OrderItem && $this->_productId == $orderItem->_productId;
    107         $rs = $rs && ($this->_variationId == $orderItem->_variationId);
    108
    109         if ($rs) {
    110             $this->extend('hasSameContent', $orderItem, $rs);
    111         }
    112         return $rs;
    113     }
    114
    115     function getProduct() {
    116         $product = false;
    117         if($this->_variationId){
    118             $product = DataObject::get_by_id('ProductVariation', $this->_variationId);
    119         }
    120         if($this->_productId){
    121             $product = DataObject::get_by_id('Product', $this->_productId);
    122         }
    123         if(!$product && $this->_productId){
    124             $product = Versioned::get_by_stage('Product', 'Stage', "SiteTree.ID = {$this->_productId}");
    125             if($product){
    126                 $product = $product->pop();
    127             }
    128         }
    129
    130         return $product;
    131
    132         // // Здравствуйте я умею в тернарные, но не умею в простой и понятный код.
    133         // return ($this->_variationId) ? DataObject::get_by_id('ProductVariation', $this->_variationId) : (($this->_productId) ? DataObject::get_by_id('Product', $this->_productId) : false);
    134     }
    135
    136     function getProductID() {
    137         $productID = $this->_productId;
    138         if ($this->_variationId) {
    139             $productID .= "_{$this->_variationId}";
    140         }
    141         $this->extend('updateProductID', $productID);
    142         return $productID;
    143     }
    144
    145     function getImportID() {
    146         $product = $this->getProduct();
    147         return ($product) ? $product->ImportID : false;
    148     }
    149
    150     function getItemsPrice() {
    151         return $this->getPrice() * $this->_quantity; //специально реализованная ф-ия получения цены
    152     }
    153
    154     function onBeforeWrite() {
    155         // изменили при редактировании заказа
    156         if ($this->isChanged('LinkedID')) {
    157             $this->_productId = $this->LinkedID;
    158         }
    159
    160         if (!$this->isInDB() && $this->_productId) {
    161             $this->LinkedID = $this->_productId; // связанный продукт
    162             if ($product = $this->getProduct()) {
    163                 $this->Title = $product->Title;
    164             }
    165             if (!isset($this->record['ItemPrice'])) { // Если цена элемента не задана (она может быть задана при специальном добавлении в корзину, напр. товары с параметром)
    166                 $this->ItemPrice = $this->getPrice(); // то берем ее из товара
    167             }
    168         }
    169         //else return; // выругаться что не выбран товар!!!
    170         if (!$this->isChanged('Quantity')) {
    171             $this->Quantity = $this->_quantity;
    172         }
    173
    174         parent::onBeforeWrite();
    175     }
    176
    177     /*
    178      * Операции с количеством
    179      */
    180
    181     /**
    182      * Текущее кол-во
    183      * @return Int
    184      */
    185     public function getQuantity() {
    186         return $this->_quantity;
    187     }
    188
    189     public function getPrice() {
    190         if ($this->isInDB()) {
    191             $this->_price = $this->ItemPrice;
    192         } else {
    193             if ($product = $this->getProduct()) {
    194                 $this->_price = $product->Price($this->_quantity);
    195             }
    196         }
    197         $this->extend('updateItemPrice', $this->_price);
    198         return ($this->_price) ? $this->_price : 0;
    199     }
    200
    201     public function Avaliable() {
    202         if ($this->getProduct())
    203             return true;
    204         else
    205             return false;
    206     }
    207
    208     public function getItemPrice() {
    209         return $this->_price;
    210     }
    211
    212     public function getLink() {
    213         $p = DataObject::get_by_id('Product', (int)$this->_productId);
    214         return ($p) ? $p->Link() : null;
    215     }
    216
    217     public function getTitle() {
    218         $title = $this->_title;
    219         if ($this->_variationId && ($variation = $this->getProduct())) {
    220             $title = $variation->Title;
    221         }
    222         $this->extend('updateItemTitle', $title);
    223         return $title;
    224     }
    225
    226     /**
    227      * Добавление кол-ва
    228      * @param Int количество
    229      */
    230     public function addQuantityValue($quantity) {
    231         if ($this->canAddQuantityValue($this->_quantity + $quantity)) {
    232             $this->_quantity += $quantity;
    233         }
    234     }
    235
    236     /**
    237      * Установка кол-ва
    238      * @param Int количество
    239      */
    240     public function setQuantityValue($quantity=null) {
    241         if ($this->canAddQuantityValue($quantity)) {
    242             $this->_quantity = $quantity;
    243         }
    244     }
    245
    246     function canAddQuantityValue($quantity) {
    247         $canAdd = true;
    248         $this->extend('updateCanSetQuantity', $canAdd, $quantity);
    249         return $canAdd;
    250     }
    251
    252     public function getTotalPrice() {
    253         return ($this->getPrice() * $this->_quantity);
    254         //return ($this->_price * $this->_quantity);
    255     }
    256
    257     function Currency() {
    258         return SiteConfig::current_site_config()->CatalogCurrency;
    259     }
    260
    261     function updateForAjax(array &$js) {
    262         $js[] = array(
    263             'product' => array(
    264                 'itemId' => $this->getProductID(),
    265                 'Title' => $this->TableTitle(),
    266                 'ItemPrice' => $this->getItemPrice(),
    267                 'TotalPrice' => $this->getTotalPrice(),
    268                 'Quantity' => $this->getQuantity()
    269             )
    270         );
    271     }
    272
    273     function TableTitle() { return $this->Title; }
    274     function UnitPrice() { return $this->ItemPrice; }
    275
    276     function PlusLink() {
    277         return Cart_Controller::add_item_link($this->getProductID());
    278     }
    279
    280     function MinusLink() {
    281         return Cart_Controller::remove_item_link($this->getProductID());
    282     }
    283
    284     function DeleteLink() {
    285         return Cart_Controller::remove_item_link($this->getProductID());
    286     }
    287
    288     function SetQuantityLink() {
    289         return Cart_Controller::set_quantity_item_link($this->getProductID());
    290     }
    291 }
    292

[Raise a SilverStripe Framework issue/bug](https://github.com/silverstripe/silverstripe-framework/issues/new)
- [Raise a SilverStripe CMS issue/bug](https://github.com/silverstripe/silverstripe-cms/issues/new)
- Please use the Silverstripe Forums to ask development related questions. -