Inheritance: extends Illuminate\Database\Migrations\Migration
Exemplo n.º 1
0
 /**
  * Generates child coupons with the $code property generated by the RandomGenerator input settings
  *
  * @param $number
  * @param int $length
  * @param string $type
  * @param string $pattern
  * @param int $separateEvery
  * @param string $separator
  * @return array
  * @throws ShopException
  */
 public function generateBulk($number, $length = 10, $type = RandomGenerator::TYPE_ALPHANUM, $pattern = 'X', $separateEvery = 0, $separator = '-')
 {
     if (!$this->isPersisted()) {
         throw new ShopException('Current coupon is not persisted, can\'t be used as parent');
     }
     $bulk = array();
     $i = 0;
     while ($i < $number) {
         $c = new Coupon();
         //$c->copy($this);
         $c->generateCode($length, $type, $pattern, $separateEvery, $separator);
         $c->module_srl = $this->module_srl;
         $c->parent_srl = $this->srl;
         $c->type = self::TYPE_CHILD;
         //save will throw ShopException if code is not unique
         try {
             $c->save();
         } catch (ShopException $e) {
             continue;
         }
         $i++;
         $bulk[] = $c;
     }
     return $bulk;
 }
Exemplo n.º 2
0
 public function calculate(Invoice $invoiceBill)
 {
     $this->coupon = $invoiceBill->getCoupon();
     $this->user = $invoiceBill->getUser();
     $isFirstPayment = $invoiceBill->isFirstPayment();
     foreach ($invoiceBill->getItems() as $item) {
         $item->first_discount = $item->second_discount = 0;
         $item->_calculateTotal();
     }
     if (!$this->coupon) {
         return;
     }
     if ($this->coupon->getBatch()->discount_type == Coupon::DISCOUNT_PERCENT) {
         foreach ($invoiceBill->getItems() as $item) {
             if ($this->coupon->isApplicable($item->item_type, $item->item_id, $isFirstPayment)) {
                 $item->first_discount = moneyRound($item->first_total * $this->coupon->getBatch()->discount / 100);
             }
             if ($this->coupon->isApplicable($item->item_type, $item->item_id, false)) {
                 $item->second_discount = moneyRound($item->second_total * $this->coupon->getBatch()->discount / 100);
             }
         }
     } else {
         // absolute discount
         $discountFirst = $this->coupon->getBatch()->discount;
         $discountSecond = $this->coupon->getBatch()->discount;
         $first_discountable = $second_discountable = array();
         $first_total = $second_total = 0;
         $second_total = array_reduce($second_discountable, create_function('$s,$item', 'return $s+=$item->second_total;'), 0);
         foreach ($invoiceBill->getItems() as $item) {
             if ($this->coupon->isApplicable($item->item_type, $item->item_id, $isFirstPayment)) {
                 $first_total += $item->first_total;
                 $first_discountable[] = $item;
             }
             if ($this->coupon->isApplicable($item->item_type, $item->item_id, false)) {
                 $second_total += $item->second_total;
                 $second_discountable[] = $item;
             }
         }
         if ($first_total) {
             $k = max(0, min($discountFirst / $first_total, 1));
             // between 0 and 1!
             foreach ($first_discountable as $item) {
                 $item->first_discount = moneyRound($item->first_total * $k);
             }
         }
         if ($second_total) {
             $k = max(0, min($discountSecond / $second_total, 1));
             // between 0 and 1!
             foreach ($second_discountable as $item) {
                 $item->second_discount = moneyRound($item->second_total * $k);
             }
         }
     }
     foreach ($invoiceBill->getItems() as $item) {
         $item->_calculateTotal();
     }
 }
 public function loadModel($id)
 {
     if (($model = Coupon::model()->findByPk($id)) === null) {
         throw new CHttpException(404, 'Страница не найдена');
     }
     return $model;
 }
Exemplo n.º 4
0
 public function deleteOldItems($model, $itemsPk)
 {
     $criteria = new CDbCriteria();
     $criteria->addNotInCondition('coupon_id', $itemsPk);
     $criteria->addCondition("listing_id= {$model->primaryKey}");
     Coupon::model()->deleteAll($criteria);
 }
Exemplo n.º 5
0
 public function loadModel($id)
 {
     $model = Coupon::model()->findByPk($id);
     if ($model === null) {
         throw new CHttpException(404, 'The requested page does not exist.');
     }
     return $model;
 }
Exemplo n.º 6
0
 public function loadModel($id)
 {
     $model = Coupon::model()->findByPk($id);
     if ($model === null) {
         throw new CHttpException(404, Yii::t('CouponModule.coupon', 'Page not found!'));
     }
     return $model;
 }
Exemplo n.º 7
0
 public function displayMain()
 {
     global $smarty;
     $result = Coupon::loadData();
     if ($result) {
         $smarty->assign(array('coupons' => $result));
     }
     return $smarty->fetch('cart.tpl');
 }
 function registerCoupon($code)
 {
     $coupon = Coupon::model()->findByPk($code);
     if (!$coupon) {
         return false;
     }
     echo "Coupon registered. {$coupon->description}";
     return $coupon->delete();
 }
 /**
  * Display a listing of the resource.
  *
  * @return Response
  */
 public function coupon()
 {
     if (ACL::checkUserPermission('reports.redeem') == false) {
         return Redirect::action('dashboard');
     }
     $coupon = Coupon::with('playerdetails', 'redeemer')->get();
     $title = 'Points Redeemed Report';
     $data = array('acl' => ACL::buildACL(), 'coupon' => $coupon, 'title' => $title);
     return View::make('reports/redeem', $data);
 }
Exemplo n.º 10
0
 private static function genCode($length = 4)
 {
     $count = 0;
     while ($count < COUPON_CODE_TRIES) {
         $code = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyz"), 0, $length);
         if (!Coupon::try_get_coupon_by_code($code)) {
             return $code;
         }
     }
     return null;
 }
Exemplo n.º 11
0
 public function getTotal()
 {
     $netto = 0;
     $brutto = 0;
     $taxes = array();
     foreach ($this->entries as $entry) {
         $netto += $entry->getTotalPrice();
         $brutto += $entry->getTotalPriceWithTax();
         foreach ($entry->getTax() as $tax) {
             $taxes[$tax->getName()] = $tax->getValue();
         }
     }
     return array('netto' => $netto, 'brutto' => $brutto, 'amount' => $brutto - ($this->coupon ? $this->coupon->getValue() : 0) - $this->paidAmount, 'taxes' => $taxes);
 }
Exemplo n.º 12
0
 public function UpdateListCoupon()
 {
     $input = Input::all();
     $listCouponID = $input['update_list_coupon_id'];
     $listCouponID = explode(",", $listCouponID);
     foreach ($listCouponID as $p) {
         $coupon = Coupon::find($p);
         $coupon->code = $input['code'];
         $coupon->description = $input['description'];
         $coupon->from_date = $input['from_date'];
         $coupon->to_date = $input['to_date'];
         $coupon->save();
     }
 }
Exemplo n.º 13
0
 public function testDeletion()
 {
     self::authorizeFromEnv();
     $id = 'test-coupon-' . self::randomString();
     $coupon = Coupon::create(array('percent_off' => 25, 'duration' => 'repeating', 'duration_in_months' => 5, 'id' => $id));
     $customer = self::createTestCustomer(array('coupon' => $id));
     $this->assertTrue(isset($customer->discount));
     $this->assertTrue(isset($customer->discount->coupon));
     $this->assertSame($id, $customer->discount->coupon->id);
     $customer->deleteDiscount();
     $this->assertFalse(isset($customer->discount));
     $customer = Customer::retrieve($customer->id);
     $this->assertFalse(isset($customer->discount));
 }
Exemplo n.º 14
0
 public function testSave()
 {
     self::authorizeFromEnv();
     $id = 'test_coupon-' . self::randomString();
     $c = Coupon::create(array('percent_off' => 25, 'duration' => 'repeating', 'duration_in_months' => 5, 'id' => $id));
     $this->assertSame($id, $c->id);
     // @codingStandardsIgnoreStart
     $this->assertSame(25, $c->percent_off);
     // @codingStandardsIgnoreEnd
     $c->metadata['foo'] = 'bar';
     $c->save();
     $stripeCoupon = Coupon::retrieve($id);
     $this->assertEquals($c->metadata, $stripeCoupon->metadata);
 }
Exemplo n.º 15
0
 public function check()
 {
     if (Yii::app()->cart->isEmpty()) {
         $this->clear();
         return;
     }
     $price = Yii::app()->cart->getCost();
     foreach ($this->coupons as $code) {
         /* @var $coupon Coupon */
         $coupon = Coupon::model()->getCouponByCode($code);
         if (!$coupon->getIsAvailable($price)) {
             $this->remove($code);
         }
     }
 }
Exemplo n.º 16
0
 /**
  * プレビューを表示する。
  */
 public function getPreviewData($id)
 {
     $data = $this->getData($id);
     // メニューの情報を置換する。
     App::uses('MenuItem', 'Model');
     $menu = new MenuItem();
     $data['menu'] = $menu->mergeMenuInfo($id, $data['menu']);
     // ニュースの情報を置換する。
     App::uses('News', 'Model');
     $news = new News();
     $data['news']['info'] = $news->getPreviewData($id);
     // クーポン情報を取得してマージ
     App::uses('Coupon', 'Model');
     $coupon = new Coupon();
     $data['coupon'] = $coupon->mergeCouponInfo($id, $data['coupon']);
     // 非表示になっているやつを削除。
     $returnList = array();
     foreach ($data as $key => $value) {
         if ($value['del'] != 1) {
             $returnList[$key] = $value;
         }
     }
     return $returnList;
 }
 public function add($order, $value = null)
 {
     //Get valid coupon for this order
     $code = Convert::raw2sql($order->CouponCode);
     $date = date('Y-m-d');
     $coupon = Coupon::get()->where("\"Code\" = '{$code}' AND \"Expiry\" >= '{$date}'")->first();
     if ($coupon && $coupon->exists()) {
         //Generate the Modification
         $mod = new CouponModification();
         $mod->Price = $coupon->Amount($order)->getAmount();
         $mod->Currency = $coupon->Currency;
         $mod->Description = $coupon->Label();
         $mod->OrderID = $order->ID;
         $mod->Value = $coupon->ID;
         $mod->CouponID = $coupon->ID;
         $mod->write();
     }
 }
Exemplo n.º 18
0
 public function actionCoupon($id = '')
 {
     $id = $this->checkCorrectness($id);
     if ($id != 0) {
         $coupon = Coupon::model()->getFrontendCoupon($id);
     } else {
         $coupon = null;
     }
     if ($coupon == null) {
         $this->render('missing_coupon');
         return null;
     }
     Yii::app()->user->setLastCouponId($id);
     ViewsTrack::addCouponView($id);
     $listing = Listing::model()->getFrontendListing($coupon->listing_id);
     // render normal listing
     $this->render('coupon_detail', array('coupon' => $coupon, 'listing' => $listing, 'listingId' => $listing->listing_id));
 }
Exemplo n.º 19
0
 /**
  *
  */
 public function actionIndex()
 {
     $positions = Yii::app()->cart->getPositions();
     $order = new Order(Order::SCENARIO_USER);
     if (Yii::app()->getUser()->isAuthenticated()) {
         $user = Yii::app()->getUser()->getProfile();
         $order->name = $user->getFullName();
         $order->email = $user->email;
         $order->city = $user->location;
     }
     $coupons = [];
     if (Yii::app()->hasModule('coupon')) {
         $couponCodes = Yii::app()->cart->couponManager->coupons;
         foreach ($couponCodes as $code) {
             $coupons[] = Coupon::model()->getCouponByCode($code);
         }
     }
     $deliveryTypes = Delivery::model()->published()->findAll();
     $this->render('index', ['positions' => $positions, 'order' => $order, 'coupons' => $coupons, 'deliveryTypes' => $deliveryTypes]);
 }
Exemplo n.º 20
0
 /**
  * 福袋领取单
  * GET /api/activity/luckybag/rank
  */
 public function actionRestrank()
 {
     $this->checkRestAuth();
     // 活动
     $criteria = new CDbCriteria();
     $criteria->compare('code', '2015ACODEFORGREETINGFROMWEIXIN');
     $criteria->compare('archived', 1);
     $activities = Activity::model()->findAll($criteria);
     if (count($activities) == 0) {
         return $this->sendResponse(400, "no code");
     }
     // 已领的奖品
     $criteria = new CDbCriteria();
     $criteria->compare('activity_id', $activities[0]->id);
     $criteria->compare('archived', 1);
     $criteria->addCondition('open_id IS NOT NULL');
     $criteria->order = 'achieved_time desc';
     $criteria->limit = 100;
     $prizes = Coupon::model()->findAll($criteria);
     $openIds = array();
     foreach ($prizes as $prize) {
         array_push($openIds, $prize->open_id);
     }
     // 获奖人
     $criteria = new CDbCriteria();
     $criteria->addInCondition('open_id', $openIds);
     $result = Luckybag::model()->findAll($criteria);
     $winners = $this->JSONArrayMapper($result);
     /*
             $idx = 0;
             foreach ($winners as $winner) {
                 foreach ($prizes as $prize) {
                     if ($winner['openId'] == $prize->open_id) {
                         $winners[$idx]['prize'] = $prize->code;
                     }
                 }
                 $idx++;
             }*/
     echo CJSON::encode($winners);
 }
 public function repMails($email, $id)
 {
     //получаю шаблон письма
     $sms = Mails::model()->findByPk(1);
     if ($sms) {
         //вставляю  тело
         $html = $sms['body'];
         //тема
         $subject = $sms['theme'];
         //нахожу нужный купон
         $coupon = Coupon::model()->findByPk($id);
         //название купона
         $product = $coupon['title'];
         //скидка
         $sale = $coupon['discount'];
         //цен до скидки
         $before = $coupon['discountPrice'] . " рублей";
         if ($before == 0) {
             $before = "Не ограничена";
             $after = "Не ограничена";
         } else {
             //цена после скидки
             $after = round($before - $sale * $before / 100, 2);
             $after .= " рублей";
         }
         //ссылка на купон
         $link = $_SERVER['HTTP_HOST'] . Yii::app()->createUrl("/coupon", array('id' => $coupon['id'], 'title' => $coupon['title']));
         $link = "<a href='http://" . $link . "'>" . $link . "</a>";
         //подставляю в шаблон
         $html = str_replace('[product]', $product, $html);
         $html = str_replace('[before]', $before, $html);
         $html = str_replace('[after]', $after, $html);
         $html = str_replace('[sale]', $sale, $html);
         $html = str_replace('[link]', $link, $html);
         //отправляем письмо
         $this->sendMail($email, $subject, $html);
     }
 }
 public function post()
 {
     $param = Input::only('player_id', 'points');
     $rules = array('points' => 'required|numeric|min:1,max:1000000', 'player_id' => 'required|exists:acl_users,id');
     //custom error messaging
     $messages = array('points.required' => 'Please fill up the player points redemption.', 'merchant_id.exists' => 'Merchant id is not valid');
     $validator = Validator::make($param, $rules, $messages);
     if ($validator->passes()) {
         $player_points = Points::where('account_id', $param['player_id'])->get()->first();
         $param = array('player_id' => $param['player_id'], 'points' => $param['points'], 'redeem_by' => Auth::user()->id, 'coupon_code' => Utils::generateRandomString(), 'redeemed' => 1);
         try {
             $player_bet = Coupon::create($param);
             $update = $player_points->decrement('credits', $param['points']);
             $message = 'Points has been successfully redeemed.';
             return Redirect::action('points.redeem')->with('success', $message);
         } catch (Exception $e) {
             print $e;
         }
     } else {
         $messages = $validator->messages();
         return Redirect::action('points.redeem')->with('error', $messages->all());
     }
 }
Exemplo n.º 23
0
 /**
  * @param \stdClass $data
  *
  * @return Promotion
  */
 public static function createFromStdClass(\stdClass $data)
 {
     $promotion = new self();
     $promotion->setId($data->id)->setAlias($data->alias)->setName($data->name)->setType($data->type)->setDescription($data->description)->setNeedProof($data->need_proof)->setOrganizationOwnerId($data->organization_owner_id);
     if ($data->coupon !== null) {
         $promotion->setCoupon(Coupon::createFromStdClass($data->coupon));
     }
     if ($data->bonus_program !== null) {
         $promotion->setBonusProgram(Bonus::createFromStdClass($data->bonus_program));
     }
     if ($data->discount !== null) {
         $promotion->setDiscount(Discount::createFromStdClass($data->discount));
     }
     if ($data->currency !== null) {
         $promotion->setCurrency(Currency::createFromStdClass($data->currency));
     }
     if ($data->expires_at !== null) {
         $promotion->setExpiresAt((new \DateTime(null, new \DateTimeZone('UTC')))->setTimestamp($data->expires_at));
     }
     foreach ($data->organizations as $organizationData) {
         $promotion->addOrganization(Organization::createFromStdClass($organizationData));
     }
     return $promotion;
 }
Exemplo n.º 24
0
 /**
  * use coupon before create order
  * @author cangzhou.wu(wucangzhou@gmail.com)
  * @param $event
  */
 public function useCoupon($event)
 {
     /** @var  $order Order */
     $order = $event->sender;
     /** @var  $couponModel  Coupon */
     $couponModel = Coupon::findOne(Yii::$app->getSession()->get(self::SESSION_COUPON_MODEL_KEY));
     if ($couponModel) {
         $couponRuleModel = $couponModel->couponRule;
         $result = Json::decode($couponRuleModel->result);
         if ($result['type']) {
             $order->total_price = $order->total_price * $result['number'];
         } else {
             $order->total_price = $order->total_price - $result['number'];
         }
         switch ($result['shipping']) {
             case 1:
                 $order->shipping_fee = $order->shipping_fee - $result['shippingFee'];
                 break;
             case 2:
                 $order->shipping_fee = 0;
         }
         Event::on(Order::className(), Order::EVENT_AFTER_INSERT, [ShoppingCoupon::className(), 'updateCouponStatus'], ['couponModel' => $couponModel]);
     }
 }
Exemplo n.º 25
0
 public function postSaveorder()
 {
     setcookie('orderdetails', json_encode($_POST), time() + 60 * 60 * 24 * 30, '/');
     $final_total = "";
     $code = $_POST['coupon'];
     $response = array('success' => 'true');
     if ($code != "") {
         $coupon_det = Coupon::where('code', '=', $code)->first()->toArray();
         if (strtotime($coupon_det['expiry']) > time() && $coupon_det['status'] == 'activated') {
             if ($coupon_det['type'] == 'discount') {
                 $final_total = intval($_POST['subtotal']) - intval($_POST['subtotal']) * intval($coupon_det['discount']) / 100;
             } else {
                 $final_total = $_POST['subtotal'] - $coupon_det['discount'];
             }
             if ($coupon_det['batchuniqid'] != "") {
                 Coupon::where('code', '=', $code)->update(array('status' => 'deactivated'));
             }
             $response = array('success' => 'true', 'message' => 'Coupon code added.', 'final_total' => $final_total);
         } else {
             $response = array('success' => 'false', 'message' => 'Coupon code expired.');
         }
     }
     return json_encode($response);
 }
Exemplo n.º 26
0
<body>
	<? if(isset($success)) { ?>
		<div class="alert"> <?php 
echo $success;
?>
 </div>
    <? } ?>    
<div id="blog_overview">
	<ul class="btn">
	  	<li><a href="<?php 
echo $ROOT_URL;
?>
_admin/modules_coupon/view/">Back</a></li>
    </ul>    
</div>    
<? $coupon = Coupon::findCoupon($_REQUEST['id']);?>
  <form id="blog_page" action="<? $PHP_SELF; ?>" method="post">
    <h3>ACM Coupon Code</h3>
    <fieldset style="width:1050px;">
      <legend>Coupon Code Panel</legend>
      <ul>
        <li>
          <label for="title">Coupon Code</label>
           <input type="text" id="title" name="code" value="<?php 
echo stripslashes($coupon->fldCouponCode);
?>
">   
           <? if(isset($code_error)) { ?>      
           		<div style="font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#F00"><b><?php 
echo $code_error;
?>
Exemplo n.º 27
0
						$stateTax = "CA";
				} else {
						$stateTax = "";
				}
				
				if($stateTax == "CA") {
					$tax = $grandtotal * .0925;
				} else {
					$tax =0;
				}
		?>
        
		
           <?
		   	   if($carts->fldCartCoupon != '') {
						  $coupon = Coupon::findCouponByCode($carts->fldCartCoupon);			
							if($coupon->fldCouponPrice != '') {
								$discAmount = $coupon->fldCouponPrice;		
								unset($_SESSION['FreeShipping']);
							} else if($coupon->fldCouponPercent != '') {
								$percent = $coupon->fldCouponPercent / 100;
								$discAmount = $grandtotal * $percent;
								unset($_SESSION['FreeShipping']);
							} else {
								$_SESSION['FreeShipping'] = 1;		
								$discAmount = 0;
							}
							
							$grandtotal = ($grandtotal - $discAmount) + $shippingRate->fldShippingRateAmount; 
				
		   ?>
Exemplo n.º 28
0
    $act["pass"] = 3;
    $act["active"] = 4;
} elseif ($data['act5'] == 0) {
    $act["pass"] = 4;
    $act["active"] = 5;
} elseif ($data['act6'] == 0) {
    $act["pass"] = 5;
    $act["active"] = 6;
} else {
    $act["pass"] = 6;
    $act["active"] = 7;
}
$tpl->act = $act;
$tpl->data = $data;
include_once "../library/Table/Coupon.class.php";
$coupon = new Coupon();
$getcoupon = $coupon->getByRandCoupon();
$tpl->getcoupon = $getcoupon;
include_once "../library/Table/Lottery.class.php";
$lottery = new Lottery();
//以下是計算USER有無領過獎
//  date_default_timezone_set("Asia/Taipei");
// $today = date("Y-m-d");
// $today = (str)$today;
// print_r($today);
$lotteryfail = $lottery->getByLotteryFbId($_SESSION['fbId']);
$tpl->lotteryfail = $lotteryfail;
//以下是計算USER當日有無在被領100次以外
//countLotteryByDate
$todaylotteryfailtimes = $lottery->countLotteryByDate($today);
$tpl->todaylotteryfailtimes = $todaylotteryfailtimes;
Exemplo n.º 29
0
 /**
  * Verify that a coupon with a given ID exists, or create a new one if it
  * does not.
  */
 protected static function retrieveOrCreateCoupon($id)
 {
     self::authorizeFromEnv();
     try {
         $coupon = Coupon::retrieve($id);
     } catch (Error\InvalidRequest $exception) {
         $coupon = Coupon::create(array('id' => $id, 'duration' => 'forever', 'percent_off' => 25));
     }
 }
Exemplo n.º 30
0
<?php

require_once '../common/config/config.inc.php';
require_once $arrConfig['sourceRoot'] . 'classes/class_coupon_bll.php';
require_once SOURCE_ROOT . 'classes/class.paging.php';
require_once SOURCE_ROOT . 'classes/class.sort.php';
//check for user session
$objAdminLogin = new AdminLogin();
$objAdminLogin->isValidAdmin();
$objCoupon = new Coupon();
$objPaging = new Paging();
$varSearchWhr = '';
$varSearchWher .= $objCoupon->getCouponString($_REQUEST);
$varSearchWhere = $varSearchWhr . '' . $varSearchWher;
//code for paging
//ADMIN_PAGE_RECORD_SIZE
$varPageStart = $objPaging->getPageStartLimit($_GET['page'], ADMIN_PAGE_RECORD_SIZE);
$varLimit = $varPageStart . ',' . ADMIN_PAGE_RECORD_SIZE;
$varTableName = coupon;
$varCouponClm = 'pkcoupon_id';
$NumberofRows = $objDatabase->getNumRows($varTableName, $varCouponClm, $varSearchWhere);
$varNumberPages = $objPaging->calculateNumberofPages($NumberofRows, ADMIN_PAGE_RECORD_SIZE);
//end for paging
$arrClm = array('coupon.pkcoupon_id,coupon.coupon_code,coupon.coupon_start_date,coupon.coupon_end_date,coupon.coupon_type,coupon.coupon_date_added');
$arrCouponList = $objCoupon->getCouponList($_REQUEST, $arrClm, $varSearchWhere, $varLimit);
$_SESSION['sessLastCouponPage'] = '';
if ($_SERVER['QUERY_STRING'] != '') {
    $_SESSION['sessLastCouponPage'] = basename($_SERVER['PHP_SELF']) . "?" . $_SERVER['QUERY_STRING'];
} else {
    $_SESSION['sessLastCouponPage'] = basename($_SERVER['PHP_SELF']);
}