Source of file GiftVoucherOrderItem.php
Size: 2,550 Bytes - Last Modified: 2021-12-24T06:35:13+00:00
/var/www/docs.ssmods.com/process/src/src/Model/GiftVoucherOrderItem.php
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 | <?php namespace SilverShop\Discounts\Model; use SilverShop\Model\Product\OrderItem; use SilverStripe\Control\Email\Email; class GiftVoucherOrderItem extends OrderItem { private static $db = [ 'GiftedTo' => 'Varchar' ]; private static $has_many = [ 'Coupons' => OrderCoupon::class ]; private static $required_fields = [ 'UnitPrice' ]; private static $table_name = 'SilverShop_GiftVoucherOrderItem'; /** * Don't get unit price from product */ public function UnitPrice() { if ($this->Product()->VariableAmount) { return $this->UnitPrice; } return parent::UnitPrice(); } /** * Create vouchers on order payment success event */ public function onPayment() { parent::onPayment(); if ($this->Coupons()->Count() < $this->Quantity) { $remaining = $this->Quantity - $this->Coupons()->Count(); for ($i = 0; $i < $remaining; $i++) { if ($coupon = $this->createCoupon()) { $this->sendVoucher($coupon); } } } } /** * Create a new coupon * * @return OrderCoupon * @throws \SilverStripe\ORM\ValidationException */ public function createCoupon() { if (!$this->Product()) { return false; } $coupon = new OrderCoupon( [ 'Title' => $this->Product()->Title, 'Type' => 'Amount', 'Amount' => $this->UnitPrice, 'UseLimit' => 1, 'MinOrderValue' => $this->UnitPrice //safeguard that means coupons must be used entirely ] ); $this->extend('updateCreateCupon', $coupon); $coupon->write(); $this->Coupons()->add($coupon); return $coupon; } /* * Send the voucher to the appropriate email */ public function sendVoucher(OrderCoupon $coupon) { $from = Email::config()->admin_email; $to = $this->Order()->getLatestEmail(); $subject = _t('Order.GIFTVOUCHERSUBJECT', 'Gift voucher'); $email = Email::create(); $email->setFrom($from); $email->setTo($to); $email->setSubject($subject); $email->setHTMLTemplate('GiftVoucherEmail'); $email->setData( [ 'Coupon' => $coupon ] ); $this->extend('updateVoucherMail', $email, $coupon); return $email->send(); } } |