<?php
// vim: set ts=4 sw=4 sts=4 et:
/**
* X-Cart
*
* NOTICE OF LICENSE
*
* This source file is subject to the software license agreement
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.litecommerce.com/module-eula.html
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to redsqui@gmail.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not modify this file if you wish to upgrade X-Cart to newer versions
* in the future. If you wish to customize X-Cart for your needs please
* refer to http://www.x-cart.com/ for more information.
*
*
* @category X-Cart Next
* @author Vladimir Serov <redsqui@gmail.com>
* @copyright Copyright (c) 2012-present Vladimir Serov <redsqui@gmail.com>. All rights reserved
* @license http://www.litecommerce.com/module-eula.html LiteCommerce Module License Agreement
*/
namespace RedSqui\GiftCertificates\Model;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use XLite\Core\Config;
use XLite\Core\Database;
use XLite\Model\TaxClass;
use RedSqui\GiftCertificates\View\FormField\Select\CardTypesMenu;
use RedSqui\GiftCertificates\Model\UseGiftCard;
/**
* Gift Certificate model
*
* @ORM\Entity (repositoryClass="\RedSqui\GiftCertificates\Model\Repo\GiftCerts")
* @ORM\Table (name="gift_certificates",
* indexes={
* @ORM\Index (name="status", columns={"status"}),
* @ORM\Index (name="add_date", columns={"add_date"}),
* @ORM\Index (name="gcid", columns={"gcid"})
* }
* )
* @ORM\HasLifecycleCallbacks
*/
class GiftCerts extends \XLite\Model\AEntity implements \XLite\Model\Base\IOrderItem
{
/*
* Gift card statuses
*/
public const STATUS_ACTIVE = 'A';
public const STATUS_NOT_PAYED_YET = 'N';
public const STATUS_REDEEMED = 'R';
public const STATUS_EXPIRED = 'E';
/*
* Gift card types
*/
public const TYPE_VIRTUAL = 'V';
public const TYPE_TANGIBLE = 'T';
/*
* Fields length limits
*/
public const LENGTH_LIMIT_ADDRESS = 550;
public const LENGTH_LIMIT_NAME = 128;
public const LENGTH_LIMIT_MESSAGE = 300;
public const LENGTH_LIMIT_SIGNATURE = 128;
/*
* template card code
*
*/
public const TEMPLATE_GCID = '/^[A-Z0-9\-]+$/';
/**
* Field const for sku
*
*/
public const GC_SKU_PREFIX = "gc-";
/**
* Validation fields
*
* @var array
*/
protected static $validationFields = [
'gcid' => 'Gcid',
'recipient_email' => 'RecipientEmail',
'recipient_address' => 'RecipientAddress',
'recipient_name' => 'RecipientName',
'sender_signature' => 'SenderSignature',
'amount' => 'Amount',
'message' => 'Message',
'delivery_date' => 'DeliveryDate',
];
/**
* Consecutive number
*
* @ORM\Id
* @ORM\GeneratedValue (strategy="AUTO")
* @ORM\Column (type="integer")
*/
protected $card_id;
/**
* Card code
*
* @var string
*
* @ORM\Column (type="string", length=255)
*/
protected $gcid = '';
/**
* Card type (Virtual, Tangible)
*
* @var string
*
* @ORM\Column (type="string", length=1)
*/
protected $card_type = 'V';
/**
* Is card available or not
*
* @var boolean
*
* @ORM\Column (type="boolean")
*/
protected $enabled = true;
/**
* Buy in order
*
* @var \XLite\Model\Order
*
* @ORM\ManyToOne (targetEntity="XLite\Model\Order", cascade={"persist"})
* @ORM\JoinColumn (name="order_id", referencedColumnName="order_id", onDelete="SET NULL")
*/
protected $order;
/**
* Order item where buy card
*
* @var \XLite\Model\OrderItem
*
* @ORM\OneToOne (targetEntity="XLite\Model\OrderItem", inversedBy="gift_card", cascade={"persist"})
* @ORM\JoinColumn (name="order_item_id", referencedColumnName="item_id", onDelete="SET NULL")
*/
protected $order_item;
/**
* recipient
*
* @var string
*
* @ORM\Column (type="string", length=64)
*/
protected $recipient_email = '';
/**
* recipient_address
*
* @var string
*
* @ORM\Column (type="string", length=550)
*/
protected $recipient_address = '';
/**
* recipient_name
*
* @var string
*
* @ORM\Column (type="string", length=128)
*/
protected $recipient_name = '';
/**
* message
*
* @var string
*
* @ORM\Column (type="string", length=300)
*/
protected $message = '';
/**
* sender_signature
*
* @var string
*
* @ORM\Column (type="string", length=128)
*/
protected $sender_signature = '';
/**
* amount
*
* @var float
*
* @ORM\Column (type="decimal", precision=14, scale=4)
*/
protected $amount = 0.0000;
/**
* balance
*
* @var float
*
* @ORM\Column (type="decimal", precision=14, scale=4)
*/
protected $balance = 0.0000;
/**
* status (Not payment yet, active, Redeemed)
*
* @var string
*
* @ORM\Column (type="string", length=1)
*/
protected $status = 'A';
/**
* add_date
*
* @var integer
*
* @ORM\Column (type="integer")
*/
protected $add_date = 0;
/**
* delivery date
*
* @var integer
*
* @ORM\Column (type="integer")
*/
protected $delivery_date = 0;
/**
* used
*
* @var boolean
*
* @ORM\Column (type="boolean")
*/
protected $used = 0;
/**
* Categories
*
* @var ArrayCollection
*
* @ORM\ManyToMany (targetEntity="XLite\Model\Category", inversedBy="gift_certs")
* @ORM\JoinTable (name="gift_certificates_categories",
* joinColumns={@ORM\JoinColumn (name="card_id", referencedColumnName="card_id", onDelete="CASCADE")},
* inverseJoinColumns={@ORM\JoinColumn (name="category_id", referencedColumnName="category_id", onDelete="CASCADE")}
* )
*/
protected $categories;
/**
* Expiration date
*
* @var integer
*
* @ORM\Column (type="integer", options={ "unsigned": true })
*/
protected $expiration_date = 0;
/**
* Constructor
*
* @param array $data Entity properties OPTIONAL
*/
public function __construct(array $data = [])
{
$this->categories = new ArrayCollection();
parent::__construct($data);
}
/**
* Check if gift card with this code is exist
*
* @param string $cardCode Gift card's code
*
* @return boolean
*/
public static function isExistGiftCard($cardCode)
{
$card = null;
$cardCode = trim($cardCode);
$card = Database::getRepo(static::class)
->getCardByCode($cardCode);
return !empty($card);
}
protected static function getRedSquiGCConfig()
{
return Config::getInstance()->RedSqui->GiftCertificates;
}
/**
* Check is set option use available code
*
* @return boolean
*/
public static function isUseAvailableCode()
{
return (self::getRedSquiGCConfig()->the_codes_for_tangible_cards == '0');
}
/**
* Check is set option use available code
*
* @return boolean
*/
public static function isUseVirtualAvailableCode()
{
return (self::getRedSquiGCConfig()->the_codes_for_virtual_cards == '0');
}
/**
* Config show tangible card type
*
* @return boolean
*/
public static function isShowTangible()
{
return self::getRedSquiGCConfig()->card_types != CardTypesMenu::TYPE_VIRTUAL;
}
/**
* Config show virtual card type
*
* @return boolean
*/
public static function isShowVirtual()
{
return self::getRedSquiGCConfig()->card_types != CardTypesMenu::TYPE_TANGIBLE;
}
/**
* Check is set gift_message option in config
*
* @return boolean
*/
public static function isShowMessage()
{
return self::getRedSquiGCConfig()->gift_message == 'Y';
}
/**
* Check is set delivery_date option in config
*
* @return boolean
*/
public static function isShowDeliveryDate()
{
return self::getRedSquiGCConfig()->delivery_date == 'Y';
}
/**
* Check is exists available codes
*
* @return boolean
*/
public static function isExistsAvailableCodes()
{
$result = self::isShowTangible();
if ($result && self::isUseAvailableCode()) {
$code = Database::getRepo(static::class)->getFirstAvailableCode();
$result = $result && !empty($code);
}
return $result;
}
/**
* Validate fields
*
* @param array $values Value fields
* @param int $cardId excluding card
*
* @return string
*/
public static function validateFields($values, $cardId = 0)
{
$errors = '';
foreach ($values as $key => $value) {
if (isset(static::$validationFields[$key])) {
$fValid = 'valid' . ucfirst(static::$validationFields[$key]);
if ($fValid == 'validGcid') {
$error = static::$fValid($value, false, $cardId);
} else {
$error = static::$fValid($value);
}
if ($error) {
$errors = $errors . $error . '. ';
}
}
}
return $errors;
}
/**
* Validate field "gcid"
*
* @param string $value Field value
*
* @return string
*/
public static function validGcid($value, $key = false, $cardId = 0)
{
$error = '';
$giftCardsRepo = Database::getRepo(static::class);
if (!empty($value)) {
$codeLength = strlen($value);
if (
$codeLength < $giftCardsRepo::PARAM_MIN_CODE_LENGTH
&& $codeLength > $giftCardsRepo::PARAM_MAX_CODE_LENGTH
) {
$error = ($key === false)
? static::t('There is incorrect code')
: static::t('There is incorrect code on X string', ['string' => $key + 1]);
} elseif (preg_match(self::TEMPLATE_GCID, $value)) {
$isNoSameCode = $giftCardsRepo->isNoSameCode($value, $cardId);
if (!$isNoSameCode) {
$error = ($key === false)
? static::t('Code already exists')
: static::t('Code already exists on X string', ['string' => $key + 1]);
}
} else {
$error = ($key === false)
? static::t('There is incorrect code')
: static::t('There is incorrect code on X string', ['string' => $key + 1]);
}
}
return $error;
}
/**
* Validate field "recipient's email"
*
* @param string $value Field value
*
* @return string
*/
protected static function validRecipientEmail($value)
{
$error = '';
if (empty($value)) {
$error = static::t(
'Field X is not defined or empty',
['name' => 'recipient\'s email']
);
} else {
$error = (filter_var($value, FILTER_VALIDATE_EMAIL) === false)
? static::t('Not an email address')
: '';
}
return $error;
}
/**
* Validate field "recipient's address"
*
* @param string $value Field value
*
* @return string
*/
protected static function validRecipientAddress($value)
{
$error = '';
if (empty($value)) {
$error = static::t(
'Field X is not defined or empty',
['name' => 'recipient\'s address']
);
} else {
$error = (strlen($value) > self::LENGTH_LIMIT_ADDRESS)
? static::t(
'The field X should contain no more than Y characters',
[
'name' => 'recipient\'s address',
'count' => self::LENGTH_LIMIT_ADDRESS
]
)
: '';
}
return $error;
}
/**
* Validate field "amount"
*
* @param string $value Field value
*
* @return string
*/
protected static function validAmount($value)
{
$error = '';
if (empty($value)) {
$error = static::t(
'Field X is not defined or empty',
['name' => 'amount']
);
} elseif (!is_numeric($value)) {
$error = static::t(
'Field X must be numeric',
['name' => 'amount']
);
} else {
$cardAmount = self::getRedSquiGCConfig()->card_amount;
if ($cardAmount == '1') {
//open_amount
$range = self::getRedSquiGCConfig()->range;
if ($range[0] > $value || $value > $range[1]) {
$error = static::t(
'Value of the field X should be in the range [Y, Z]',
[
'name' => 'amount',
'range_left' => $range[0],
'range_right' => $range[1]
]
);
}
} else {
$amountOptions = self::getRedSquiGCConfig()->amount_options;
if (!in_array($value, $amountOptions)) {
$error = static::t(
'Incorrect value of the field X',
['name' => 'amount']
);
}
}
}
return $error;
}
/**
* Validate field "message"
*
* @param string $value Field value
*
* @return string
*/
protected static function validMessage($value)
{
$error = '';
if (!empty($value)) {
if (self::LENGTH_LIMIT_MESSAGE < strlen($value)) {
$error = static::t(
'The field X should contain no more than Y characters',
['name' => 'message', 'count' => self::LENGTH_LIMIT_MESSAGE]
);
}
}
return $error;
}
/**
* Validate field "recipient's name"
*
* @param string $value Field value
*
* @return string
*/
protected static function validRecipientName($value)
{
$error = '';
if (!empty($value)) {
if (self::LENGTH_LIMIT_NAME < strlen($value)) {
$error = static::t(
'The field X should contain no more than Y characters',
[
'name' => 'recipient\'s name',
'count' => self::LENGTH_LIMIT_NAME
]
);
}
}
return $error;
}
/**
* Validate field "SenderSignature"
*
* @param string $value Field value
*
* @return string
*/
protected static function validSenderSignature($value)
{
$error = '';
if (!empty($value)) {
if (self::LENGTH_LIMIT_SIGNATURE < strlen($value)) {
$error = static::t(
'The field X should contain no more than Y characters',
[
'name' => 'sender\'s signature',
'count' => self::LENGTH_LIMIT_SIGNATURE
]
);
}
}
return $error;
}
/**
* Validate field "Delivery date"
*
* @param string $value Field value
*
* @return string
*/
protected static function validDeliveryDate($value)
{
$error = '';
if ($value) {
$date = strtotime(date('Y-m-d'));
if ($value < $date) {
$error = static::t('Delivery date shall be not earlier than the current date');
}
}
return $error;
}
/**
* Get gift card code for list cards
*
* @return string
*/
public function getCode()
{
return ($this->getGcid())
? $this->getGcid()
: static::t('Not setted');
}
/**
* Get value for 'created' field in card table
*
* @param boolean $withTime Date or datetime created OPTIONAL
*
* @return string
*/
public function getCreated($withTime = false)
{
return ($withTime)
? date('M d, Y, H:i', $this->getAddDate())
: date('M d, Y', $this->getAddDate());
}
/**
* Get order's number for 'created' field in card table
*
* @return integer|null
*/
public function getNumberCreatedOrder()
{
$order = $this->getOrder();
return (!empty($order))
? $order->getOrderNumber()
: null;
}
/**
* Get format gift card balance
*
* @return string
*/
public function getFormatBalance()
{
$currency = $this->getCurrency();
$balance = $currency->formatParts($this->getBalance());
return implode('', $balance);
}
/**
* Get use in orders
*
* @return array
*/
public function getUsedIn()
{
$records = Database::getRepo(UseGiftCard::class)
->findByParams(['card' => $this->getCardId()]);
$ordersId = [];
if ($records) {
foreach ($records as $record) {
$ordersId[] = $record->getOrder()->getOrderNumber();
}
}
return $ordersId;
}
/**
* Get gift card status by user role
*
* @return string
*/
public function getStatus()
{
$status = '';
if ($this->getEnabled()) {
$status = (!\XLite::isAdminZone() && $this->status == self::STATUS_NOT_PAYED_YET)
? static::t('Inactive')
: $this->getStatusFull();
} else {
$status = (\XLite::isAdminZone())
? $this->getStatusFull()
: static::t('Inactive');
}
return $status;
}
/**
* Get gift card type
*
* @return string
*/
public function getFullType()
{
$type = '';
if ($this->isVirtual()) {
$type = static::t('Virtual');
} else {
$type = ($this->isTangible())
? static::t('Tangible')
: '';
}
return $type;
}
/**
* Check if gift card is tangible
*
* @return boolean
*/
public function isTangible()
{
return ($this->getCardType() == self::TYPE_TANGIBLE);
}
/**
* Check if gift card is virtual
*
* @return boolean
*/
public function isVirtual()
{
return ($this->getCardType() == self::TYPE_VIRTUAL);
}
/**
* Check gift card for use in order
*
* @return boolean
*/
public function checkAvailability()
{
return $this->getEnabled()
&& $this->isActive()
&& !$this->checkExpired();
}
/**
* Check if card has status "active"
*
* @return boolean
*/
public function isActive()
{
return $this->status == self::STATUS_ACTIVE;
}
/**
* Check if card has status "redeemed"
*
* @return boolean
*/
public function isRedeemed()
{
return $this->status == self::STATUS_REDEEMED;
}
/**
* Check if card has status "not payed yet"
*
* @return boolean
*/
public function isNotPayedYet()
{
return $this->status == self::STATUS_NOT_PAYED_YET;
}
/**
* Check if card has status "expired"
*
* @return boolean
*/
public function isExpired()
{
return $this->status == self::STATUS_EXPIRED;
}
/**
* Use card in order
*
* @return boolean
*/
public function useAmount($cost)
{
$isSuccess = true;
$newBalance = $this->getBalance() - $cost;
if ($newBalance < 0) {
$isSuccess = false;
} else {
$this->setBalance($newBalance);
if ($this->getBalance() == 0) {
$this->setStatus(self::STATUS_REDEEMED);
}
Database::getEM()->persist($this);
Database::getEM()->flush();
}
return $isSuccess;
}
/**
* Return amount for card in order
*
* @return boolean
*/
public function returnAmount($cost)
{
$isSuccess = true;
$newBalance = $this->getBalance() + $cost;
if ($newBalance > $this->getAmount() || 0 > $newBalance) {
$isSuccess = false;
} else {
$this->setBalance($newBalance);
if ($this->isRedeemed()) {
$this->setStatus(self::STATUS_ACTIVE);
}
Database::getEM()->persist($this);
Database::getEM()->flush();
}
return $isSuccess;
}
/**
* Since Doctrine lifecycle callbacks do not allow to modify associations, we've added this method
*
* @param string $type Type of current operation
*
* @return void
*/
public function prepareEntityBeforeCommit($type)
{
if ($type == self::ACTION_INSERT) {
$this->setBalance($this->getAmount());
$this->setAddDate(time());
if (!\XLite::isAdminZone()) {
$this->setUsed(1);
}
} elseif ($type == self::ACTION_UPDATE) {
if (\XLite::isAdminZone()) {
if ($this->getUsed() == 0) {
$this->setUsed(1);
$this->setAddDate(time());
$this->setBalance($this->getAmount());
}
} else {
$this->setBalance($this->getAmount());
}
}
}
/**
* Get recipient address with <br/>
*
* @return string
*/
public function getRecipientAddressBreak()
{
$address = $this->getRecipientAddress();
if ($address) {
$explSymbols = '';
if (strpos($address, "\r") !== false) {
$explSymbols = $explSymbols . "\r";
}
if (strpos($address, "\n") !== false) {
$explSymbols = $explSymbols . "\n";
}
if ($explSymbols) {
$address = str_replace($explSymbols, '<br/>', $address);
}
}
return $address;
}
/**
* Check if exist gift_message
*
* @return boolean
*/
public function isExistMessage()
{
return $this->getMessage()
|| $this->getRecipientName()
|| $this->getSenderSignature();
}
/**
* 'Type' card will be sent to 'person'
*
* @return string
*/
public function getTypeInfo()
{
$typeMessage = 'card will be sent to X';
$sentTo = '';
if ($this->isSentToFriend()) {
$sentTo = static::t('your friend');
} else {
$sentTo = ($this->isTangible())
? static::t('your address')
: static::t('your e-mail');
}
return $this->getFullType() . ' ' . static::t($typeMessage, ['whom' => $sentTo]);
}
/**
* Check if card will be sent to friend
*
* @return boolean
*/
public function isSentToFriend()
{
return ($this->isTangible())
? ((bool)$this->getRecipientAddress())
: ((bool)$this->getRecipientEmail());
}
/************ IOrderItem *************/
/**
* Get free shipping flag
*
* @return boolean
*/
public function getFreeShipping()
{
return true;
}
/**
* Get image
*
* @return \XLite\Model\Base\Image|null
*/
public function getImage()
{
return null;
}
/**
* Get image URL
*
* @return string
*/
public function getImageURL()
{
return \XLite\Core\Layout::getInstance()->getResourceWebPath(
'modules/RedSqui/GiftCertificates/img/gift_card_photo_small.png',
\XLite\Core\Layout::WEB_PATH_OUTPUT_URL,
\XLite::INTERFACE_WEB,
\XLite::ZONE_CUSTOMER
);
}
/**
* Get image URL
*
* @return string
*/
public function getImagePath()
{
return \XLite\Core\Layout::getInstance()->getResourceFullPath(
'modules/RedSqui/GiftCertificates/img/gift_card_photo_small.png',
\XLite::INTERFACE_WEB,
\XLite::ZONE_CUSTOMER
);
}
/**
* @return string
*/
public function getImageRelativeURL()
{
return \Includes\Utils\FileManager::getRelativePath($this->getImagePath(), LC_DIR_ROOT);
}
/**
* Maximal available amount
*
* @return integer
*/
public function getMaxPurchaseLimit()
{
return 1;
}
/**
* Minimal available amount
*
* @return integer
*/
public function getMinPurchaseLimit()
{
return 1;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
$currency = $this->getCurrency();
$amount = $currency->formatParts($this->getAmount());
$result = static::t('gift card (X)', ['amount' => implode('', $amount)]);
return $result;
}
/**
* Get currency symbol for card
*
* @return string
*/
public function getCurrencySymbol()
{
return $this->getCurrency()->getSymbol();
}
/**
* Get currency for card
*
* @return \XLite\Model\Currency
*/
public function getCurrency()
{
return ($this->getOrder())
? $this->getOrder()->getCurrency()
: \XLite::getInstance()->getCurrency();
}
/**
* Get currency for card
*
* @return \XLite\Model\Currency
*/
public function getEditCurrency()
{
return $this->getCurrency();
}
/**
* Get currency for card
*
* @return string
*/
public function getEditCurrencySymbol()
{
return $this->getEditCurrency()->getSymbol();
}
/**
* Get price: modules should never overwrite this method
*
* @return float
*/
public function getPrice()
{
$price = $this->getAmount();
if ($this->isTangible()) {
$price = $price + self::getRedSquiGCConfig()->shipping_surcharge;
}
return $price;
}
/**
* Get SKU
*
* @return string
*/
public function getSku()
{
return self::GC_SKU_PREFIX . $this->getId();
}
/**
* Get Url
*
* @return string
*/
public function getURL()
{
return ($this->getCardId())
? \XLite\Core\Converter::buildURL('gift_certs', '', ['card_id' => $this->getCardId()])
: null;
}
/**
* getWeight
*
* @return float
*/
public function getWeight()
{
return 0;
}
/**
* Get object unique id
*
* @return integer
*/
public function getId()
{
return $this->getCardId();
}
/**
* Check if card is accessible (for order)
*
* @return boolean
*/
public function isAvailable()
{
return true;
}
/**
* Price not modificators
*
* @return float
*/
public function getNetPrice()
{
return $this->getAmount();
}
/**
* Get taxable basis
*
* @return float
*/
public function getTaxableBasis()
{
return $this->getNetPrice();
}
/**
* Price not modificators
*
* @return float
*/
public function getDisplayPrice()
{
return $this->getAmount();
}
/**
* Price not modificators
*
* @return float
*/
public function getClearPrice()
{
return $this->getAmount();
}
/**
* Get memberships
*
* @return ArrayCollection
*/
public function getMemberships()
{
$result = new ArrayCollection();
return $result;
}
/**************************/
/**
* Get gift card status
*
* @return string
*/
protected function getStatusFull()
{
switch ($this->status) {
case self::STATUS_ACTIVE:
$status = static::t('Active');
break;
case self::STATUS_REDEEMED:
$status = static::t('Redeemed');
break;
case self::STATUS_NOT_PAYED_YET:
$status = static::t('Not payed yet');
break;
case self::STATUS_EXPIRED:
$status = static::t('Expired');
break;
default:
$status = '';
break;
}
return $status;
}
/**
* Get card_id
*
* @return int
*/
public function getCardId()
{
return $this->card_id;
}
/**
* Set gcid
*
* @param string $gcid
*
* @return GiftCerts
*/
public function setGcid($gcid)
{
$this->gcid = $gcid;
return $this;
}
/**
* Get gcid
*
* @return string
*/
public function getGcid()
{
return $this->gcid;
}
/**
* Set card_type
*
* @param string $cardType
*
* @return GiftCerts
*/
public function setCardType($cardType)
{
$this->card_type = $cardType;
return $this;
}
/**
* Get card_type
*
* @return string
*/
public function getCardType()
{
return $this->card_type;
}
/**
* Set enabled
*
* @param boolean $enabled
*
* @return GiftCerts
*/
public function setEnabled($enabled)
{
$this->enabled = $enabled;
return $this;
}
/**
* Get enabled
*
* @return boolean
*/
public function getEnabled()
{
return $this->enabled;
}
/**
* Set recipient_email
*
* @param string $recipientEmail
*
* @return GiftCerts
*/
public function setRecipientEmail($recipientEmail)
{
$this->recipient_email = $recipientEmail;
return $this;
}
/**
* Get recipient_email
*
* @return string
*/
public function getRecipientEmail()
{
return $this->recipient_email;
}
/**
* Set recipient_address
*
* @param string $recipientAddress
*
* @return GiftCerts
*/
public function setRecipientAddress($recipientAddress)
{
$this->recipient_address = $recipientAddress;
return $this;
}
/**
* Get recipient_address
*
* @return string
*/
public function getRecipientAddress()
{
return $this->recipient_address;
}
/**
* Set recipient_name
*
* @param string $recipientName
*
* @return GiftCerts
*/
public function setRecipientName($recipientName)
{
$this->recipient_name = $recipientName;
return $this;
}
/**
* Get recipient_name
*
* @return string
*/
public function getRecipientName()
{
return $this->recipient_name;
}
/**
* Set message
*
* @param string $message
*
* @return GiftCerts
*/
public function setMessage($message)
{
$this->message = $message;
return $this;
}
/**
* Get message
*
* @return string
*/
public function getMessage()
{
return $this->message;
}
/**
* Set sender_signature
*
* @param string $senderSignature
*
* @return GiftCerts
*/
public function setSenderSignature($senderSignature)
{
$this->sender_signature = $senderSignature;
return $this;
}
/**
* Get sender_signature
*
* @return string
*/
public function getSenderSignature()
{
return $this->sender_signature;
}
/**
* Set amount
*
* @param float $amount
*
* @return GiftCerts
*/
public function setAmount($amount)
{
$this->amount = $amount;
return $this;
}
/**
* Get amount
*
* @return float
*/
public function getAmount()
{
return $this->amount;
}
/**
* Get amount
*
* @return float
*/
public function getEditAmount()
{
return $this->getAmount();
}
/**
* Set balance
*
* @param float $balance
*
* @return GiftCerts
*/
public function setBalance($balance)
{
$this->balance = $balance;
return $this;
}
/**
* Get balance
*
* @return float
*/
public function getBalance()
{
return $this->balance;
}
/**
* Set status
*
* @param string $status
*
* @return GiftCerts
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Set add_date
*
* @param integer $addDate
*
* @return GiftCerts
*/
public function setAddDate($addDate)
{
$this->add_date = $addDate;
return $this;
}
/**
* Get add_date
*
* @return integer
*/
public function getAddDate()
{
return $this->add_date;
}
/**
* Set delivery_date
*
* @param integer $deliveryDate
*
* @return GiftCerts
*/
public function setDeliveryDate($deliveryDate)
{
$this->delivery_date = $deliveryDate;
return $this;
}
/**
* Get delivery_date
*
* @return integer
*/
public function getDeliveryDate()
{
return $this->delivery_date;
}
/**
* Set used
*
* @param boolean $used
*
* @return GiftCerts
*/
public function setUsed($used)
{
$this->used = $used;
return $this;
}
/**
* Get used
*
* @return boolean
*/
public function getUsed()
{
return $this->used;
}
/**
* Set expiration_date
*
* @param integer $expirationDate
*
* @return GiftCerts
*/
public function setExpirationDate($expirationDate)
{
$this->expiration_date = $expirationDate;
return $this;
}
/**
* Get expiration_date
*
* @return integer
*/
public function getExpirationDate()
{
return $this->expiration_date;
}
/**
* Set order
*
* @param \XLite\Model\Order $order
*
* @return GiftCerts
*/
public function setOrder(\XLite\Model\Order $order = null)
{
$this->order = $order;
return $this;
}
/**
* Get order
*
* @return \XLite\Model\Order
*/
public function getOrder()
{
return $this->order;
}
/**
* Set order_item
*
* @param \XLite\Model\OrderItem $orderItem
* @return GiftCerts
*/
public function setOrderItem(\XLite\Model\OrderItem $orderItem = null)
{
$this->order_item = $orderItem;
return $this;
}
/**
* Get order_item
*
* @return \XLite\Model\OrderItem
*/
public function getOrderItem()
{
return $this->order_item;
}
/**
* Get coe tax class
*
* @return int
*/
public function getCodeTaxClass()
{
$codeTaxClass = ($this->isVirtual())
? self::getRedSquiGCConfig()->gc_virtual_tax_class
: self::getRedSquiGCConfig()->gc_tangible_tax_class;
return $codeTaxClass;
}
/**
* getTaxClass
*
* @return TaxClass
*/
public function getTaxClass()
{
$codeTaxClass = $this->getCodeTaxClass();
$taxClass = Database::getRepo(TaxClass::class)->find($codeTaxClass);
return $taxClass;
}
/**
* Is certificate taxable
*
* @return bool
*/
public function getTaxable()
{
$codeTaxClass = $this->getCodeTaxClass();
return (!empty($codeTaxClass) && $codeTaxClass > -2);
}
/**
* Add categories
*
* @param \XLite\Model\Category $categories
*
* @return GiftCerts
*/
public function addCategories(\XLite\Model\Category $categories)
{
$this->getCategories()->add($categories);
return $this;
}
/**
* Get categories
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getCategories()
{
return $this->categories;
}
/**
* Clear categories
*/
public function clearCategories()
{
foreach ($this->getCategories()->getKeys() as $key) {
$this->getCategories()->remove($key);
}
}
/**
* Is gift cert valid for product
*
* @param \XLite\Model\Product $product Product
*
* @return boolean
*/
public function isValidForProduct(\XLite\Model\Product $product)
{
$result = true;
if (0 < $this->getCategories()->count()) {
$result = false;
foreach ($product->getCategories() as $category) {
if ($this->getCategories()->contains($category)) {
$result = true;
break;
}
}
}
return $result;
}
/**
* Check gift card category
*
* @param \XLite\Model\Order $order Order
*
* @return bool
*/
public function checkCategory(\XLite\Model\Order $order)
{
$found = true;
if (0 < $this->getCategories()->count()) {
$found = false;
foreach ($order->getItems() as $item) {
foreach ($item->getProduct()->getCategories() as $category) {
if ($this->getCategories()->contains($category)) {
$found = true;
break;
}
}
if ($found) {
break;
}
}
}
return $found;
}
/**
* Get items for gift card with categories
*
* @param \XLite\Model\Order $order Order
*
* @return \XLite\Model\OrderItem[]
*/
public function getValidOrderItems(\XLite\Model\Order $order)
{
$items = [];
foreach ($order->getItems() as $item) {
if ($this->isValidForProduct($item->getProduct())) {
$items[] = $item;
}
}
return $items;
}
/**
* Get order total
*
* @param \XLite\Model\Order $order Order
*
* @return float
*/
public function getOrderTotalForProducts(\XLite\Model\Order $order)
{
return array_reduce($this->getValidOrderItems($order), static function ($carry, $item) {
return $carry + $item->getSubtotal();
}, 0);
}
/**
* Check - gift card is expired or not
*
* @return boolean
*/
public function checkExpired()
{
$expirationDate = $this->getExpirationDate();
if (0 >= $expirationDate) {
$expirationPeriod = self::getRedSquiGCConfig()->gc_expiration_period_days;
if (0 < $expirationPeriod) {
$addDate = $this->getAddDate();
$expirationDate = $addDate + $expirationPeriod * 86400;
}
}
$date = getdate(\XLite\Core\Converter::time());
$today = mktime(0, 0, 0, $date['mon'], $date['mday'], $date['year']);
$expired = 0 < $expirationDate && $expirationDate < $today;
if ($expired && $this->isActive()) {
$this->setStatus(self::STATUS_EXPIRED);
}
if (!$expired && $this->isExpired()) {
if ($this->getBalance() == 0) {
$this->setStatus(self::STATUS_REDEEMED);
} else {
if (empty($this->getCode())) {
$this->setStatus(self::STATUS_NOT_PAYED_YET);
} else {
$this->setStatus(self::STATUS_ACTIVE);
}
}
}
return $expired;
}
/**
* get statuses
*
* @return array
*/
public static function getListStatuses()
{
$result = [
self::STATUS_ACTIVE => static::t('Active'),
self::STATUS_REDEEMED => static::t('Redeemed'),
self::STATUS_NOT_PAYED_YET => static::t('Not paid yet'),
self::STATUS_EXPIRED => static::t('Expired'),
];
return $result;
}
/**
* check if products from gift card categories is discounted all
*
* @param \XLite\Model\Order $order Order
*
* @return bool
*/
public function isPaidItemsForGiftCard(\XLite\Model\Order $order)
{
$result = false;
$validItems = $this->getValidOrderItems($order);
if ($validItems) {
$subtotal = 0;
foreach ($validItems as $key => $item) {
$subtotal += $item->getDiscountedSubtotal();
}
$result = ($subtotal <= 0);
}
return $result;
}
}