model() public static method

Please note that you should have this exact method in all your CActiveRecord descendants!
public static model ( string $className = __CLASS__ ) : Coupon
$className string active record class name.
return Coupon - the static model class
 public function loadModel($id)
 {
     if (($model = Coupon::model()->findByPk($id)) === null) {
         throw new CHttpException(404, 'Страница не найдена');
     }
     return $model;
 }
Example #2
0
 public function deleteOldItems($model, $itemsPk)
 {
     $criteria = new CDbCriteria();
     $criteria->addNotInCondition('coupon_id', $itemsPk);
     $criteria->addCondition("listing_id= {$model->primaryKey}");
     Coupon::model()->deleteAll($criteria);
 }
Example #3
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;
 }
Example #4
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;
 }
 function registerCoupon($code)
 {
     $coupon = Coupon::model()->findByPk($code);
     if (!$coupon) {
         return false;
     }
     echo "Coupon registered. {$coupon->description}";
     return $coupon->delete();
 }
Example #6
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);
         }
     }
 }
Example #7
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));
 }
Example #8
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]);
 }
Example #9
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);
     }
 }
Example #11
0
 /**
  * 保存优惠券信息
  */
 protected function saveOrderCoupon($order_id, $couponInfo)
 {
     if (empty($couponInfo)) {
         return false;
     }
     if ($couponInfo['type'] == 'A') {
         return false;
     }
     //A(固定券码 暂不保存数据)
     $couponInfo = Coupon::model()->findByAttributes(array('coupon_sn' => $couponInfo['coupon_sn']));
     if (empty($couponInfo)) {
         throw new Exception("优惠券不存在!", 1);
     }
     $couponInfo->order_id = $order_id;
     $couponInfo->use_time = time();
     $flag = $couponInfo->save();
     if (empty($flag)) {
         throw new Exception("优惠券保存失败!", 1);
     }
     return true;
 }
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     Yii::app()->clientScript->registerPackage('discount-edit');
     $id = null;
     if (isset($_GET['id'])) {
         $id = (int) $_GET['id'];
     } elseif (isset($_POST['Discount']['id'])) {
         $id = (int) $_POST['Discount']['id'];
     }
     $model = $this->loadModel($id);
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     $coupons = $model->coupons;
     if (isset($_POST['Discount'])) {
         if (!isset($_POST['Coupon'])) {
             $model->addError('status', Yii::t('errors', 'В предложении должен быть хотябы один купон'));
         } else {
             $data = $_POST['Coupon'];
             $coupons = array();
             foreach ($data as $c) {
                 $coupon = null;
                 if (isset($c['id']) && $c['id'] > 0) {
                     $coupon = Coupon::model()->findByPk($c['id']);
                     if (isset($c['delete'])) {
                         $coupon->delete();
                     }
                 }
                 if (!isset($c['delete'])) {
                     if ($coupon === null) {
                         $coupon = new Coupon();
                     }
                     $coupon->attributes = $c;
                     $coupons[] = $coupon;
                 }
             }
         }
         $model->attributes = $_POST['Discount'];
         if (!$model->hasErrors() && $model->save()) {
             $fail = false;
             foreach ($coupons as $coupon) {
                 $coupon->discount_id = $model->id;
                 if (!$coupon->save()) {
                     $fail = true;
                 }
             }
             if (!$fail) {
                 if (isset($_POST['Cats'])) {
                     $cats = array_map('intval', explode(',', $_POST['Cats']));
                     //Normalize
                     $dicats = DiscountCategory::model()->findAllByAttributes(array('discount_id' => $model->id));
                     foreach ($dicats as $i => $d) {
                         if (FALSE !== ($k = array_search($d->category_id, $cats))) {
                             unset($cats[$k]);
                             unset($dicats[$i]);
                         } else {
                             $d->delete();
                         }
                     }
                     if (!empty($cats)) {
                         $cats = Category::model()->findAllByAttributes(array('id' => $cats));
                         foreach ($cats as $c) {
                             $DC = new DiscountCategory();
                             $DC->discount_id = $model->id;
                             $DC->category_id = $c->id;
                             if (!$DC->save()) {
                                 echo CHtml::errorSummary($DC);
                             }
                         }
                     }
                 }
                 if (isset($_POST['Region'])) {
                     $cats = array_map('intval', explode(',', $_POST['Region']));
                     //Normalize
                     $dicats = DiscountRange::model()->findAllByAttributes(array('discount_id' => $model->id));
                     foreach ($dicats as $i => $d) {
                         if (FALSE !== ($k = array_search($d->category_id, $cats))) {
                             unset($cats[$k]);
                             unset($dicats[$i]);
                         } else {
                             $d->delete();
                         }
                     }
                     if (!empty($cats)) {
                         $cats = City::model()->findAllByAttributes(array('id' => $cats));
                         foreach ($cats as $c) {
                             $DC = new DiscountRange();
                             $DC->discount_id = $model->id;
                             $DC->city_id = $c->id;
                             if (!$DC->save()) {
                                 echo CHtml::errorSummary($DC);
                             }
                         }
                     }
                 }
                 $this->redirect('/business/discount');
             }
         }
     }
     $this->render('create', array('model' => $model, 'coupons' => $coupons));
 }
Example #13
0
 public function isActiveCouponsExists()
 {
     return Coupon::model()->active()->count() > 0 ? true : false;
 }
Example #14
0
                <th>наименование программы</th>
                <th width="100">Стоимость</th>
            </tr>
            </thead>

            <tfoot>
            <tr>
                <td colspan="2" class="cart-table__td-promo">
                    <div class="cart-table__promo" 
                         data-add-url="<?php 
echo Yii::app()->createUrl("/subscription/order/addCoupon", array('subscriptionId' => $subscription->id));
?>
">
                        
                        <?php 
if (Coupon::model()->isActiveCouponsExists()) {
    ?>
                        <span class="form-control-input form-control-input_type_2">
                            <input id="coupon" placeholder="Введите промо-код (если есть)" type="text" value="<?php 
    if (!empty($subscription->coupon)) {
        echo $subscription->coupon->code;
    }
    ?>
" class="coupon" maxlength="10" />
                        </span>
                        <button class="btn_ok" id="coupon-apply"></button>
                        <i class="icn icn_checkbox"></i>  
                        <div class="promo-error"></div>
                        <?php 
}
?>
Example #15
0
 /**
  * Фильтрует переданные коды купонов и возвращает объекты купонов
  * @param $codes - массив кодов купонов
  * @return Coupon[] - массив объектов-купонов
  */
 public function getValidCoupons($codes)
 {
     if ($this->_validCoupons !== null) {
         return $this->_validCoupons;
     }
     $productsTotalPrice = $this->getProductsCost();
     $validCoupons = [];
     /* @var $coupon Coupon */
     /* проверим купоны на валидность */
     foreach ($codes as $code) {
         $coupon = Coupon::model()->getCouponByCode($code);
         if (null !== $coupon && $coupon->getIsAvailable($productsTotalPrice)) {
             $validCoupons[] = $coupon;
         }
     }
     return $validCoupons;
 }
Example #16
0
 public function actionEdit()
 {
     if (empty($_POST)) {
         $info = Coupon::model()->findByPk($_REQUEST['id']);
         $viewData = array();
         $viewData['info'] = $info;
         $this->render('edit', $viewData);
         exit;
     }
     $res = array('statusCode' => 200, 'message' => '修改成功!');
     try {
         $m = Coupon::model()->findByPk($_REQUEST['id']);
         $m->coupon_amount = $_REQUEST['coupon_amount'];
         $m->satisfied_amount = $_REQUEST['satisfied_amount'];
         $m->start_time = strtotime($_REQUEST['start_time']);
         $m->end_time = strtotime($_REQUEST['end_time']);
         $flag = $m->save();
         if (!$flag) {
             throw new exception('修改失败');
         }
     } catch (Exception $e) {
         $res['statusCode'] = 300;
         $res['message'] = '修改失败【' . $e->getMessage() . '】';
     }
     $res['navTabId'] = 'couponList';
     $res['callbackType'] = 'closeCurrent';
     $res['forwardUrl'] = '/manage/coupon/index';
     $this->ajaxDwzReturn($res);
 }
Example #17
0
 public function actionIndex()
 {
     $coupons = Coupon::model()->findAll();
     $this->render('index', array('coupons' => $coupons));
 }
Example #18
0
 /**
  * 使用优惠券时 (绑定优惠券、计算优惠券金额)【ckeckout页面绑定优惠券、并检查优惠券的使用】
  */
 public function actionCheckCoupon()
 {
     $res = array('status' => 1, 'msg' => '');
     $sn = addslashes(trim($_REQUEST['sn']));
     $userId = $this->user_id;
     try {
         if (empty($userId)) {
             throw new Exception("用户还没有登陆,请登录!", 2);
         }
         $map = array();
         $map['coupon_sn'] = $sn;
         $info = Coupon::model()->findByAttributes($map);
         $type = 'B';
         if (empty($info)) {
             $map = array();
             $map['coupon_sn'] = $sn;
             $info = CouponType::model()->findByAttributes($map);
             $type = 'A';
             if (empty($info)) {
                 throw new Exception("优惠券错误,该券号不存在!", 0);
             }
         } else {
             if ($info['end_time'] < time()) {
                 throw new Exception("优惠券已过期!", 0);
             } elseif (empty($info['user_id']) && empty($info['order_id'])) {
                 $info->user_id = $userId;
                 $info->band_time = time();
                 $flag = $info->save();
                 if (empty($flag)) {
                     throw new Exception("优惠券绑定失败,请重试!", 0);
                 }
             } elseif ($info['user_id'] != $userId || !empty($info['order_id'])) {
                 throw new Exception("优惠券已使用或者异常!", 0);
             } elseif ($info['start_time'] > time()) {
                 throw new Exception("优惠券还未到使用日期!", 0);
             }
         }
         $list = Cart::model()->getCartList($userId);
         if (empty($list['list'])) {
             throw new Exception("购物车不能为空!", 0);
         }
         $productAmount = $list['total']['product_amount'];
         if (!empty($productAmount) && $productAmount >= $info['satisfied_amount'] || empty($info['satisfied_amount'])) {
             $finialAmount = $list['total']['product_amount'] + $list['total']['shipping_fee'] - $info['coupon_amount'];
             $res['couponsn'] = $info['coupon_sn'];
             $res['couponAmount'] = $info['coupon_amount'];
             $res['shipingFee'] = $list['total']['shipping_fee'];
             $res['finalAmount'] = $finialAmount < 0 ? 0 : $finialAmount;
         } elseif ($productAmount < $info['satisfied_amount']) {
             throw new Exception("优惠券不满足使用条件!", 0);
         }
         $couponlist = Coupon::model()->getUserUsingCouponList($userId);
         if ($type == 'A') {
             array_push($couponlist, $info->getAttributes());
         }
         $res['couponlist'] = $couponlist;
     } catch (exception $e) {
         $res['status'] = $e->getCode();
         $res['msg'] = $e->getMessage();
     }
     exit(json_encode($res));
 }
Example #19
0
 /**
  * 【用户中心】优惠券绑定
  */
 public function actionCouponBand()
 {
     $res = array('status' => 1, 'msg' => '');
     $userId = $this->user_id;
     $coupon_sn = trim($_REQUEST['sn']);
     try {
         if (empty($userId)) {
             throw new exception('用户未登录', 2);
         }
         if (empty($coupon_sn)) {
             throw new exception('券号不能为空');
         }
         Coupon::model()->couponBand($userId, $coupon_sn);
     } catch (exception $e) {
         $res['status'] = $e->getCode();
         $res['msg'] = $e->getMessage();
     }
     exit(json_encode($res));
 }
Example #20
0
 private function processNewEndingFavs($couponsType)
 {
     $this->layout = "listing_layout";
     $coupons = Coupon::model()->getCouponsByType($couponsType);
     $this->render('new_ending', array('coupons' => $coupons, 'couponsType' => $couponsType));
 }
Example #21
0
 /**
  * 【用户中心】优惠券绑定.
  * @param $userId
  * @param $coupon_sn
  */
 public function couponBand($userId, $coupon_sn)
 {
     $map = array();
     $map['coupon_sn'] = $coupon_sn;
     $couponInfo = Coupon::model()->findByAttributes($map);
     if (empty($couponInfo)) {
         throw new exception('该优惠券不存在!');
     }
     if ($couponInfo->user_id) {
         if ($userId != $couponInfo->user_id) {
             throw new exception('该优惠券已经是别人的了!');
         } else {
             return true;
         }
     } elseif (!empty($couponInfo['order_id']) || !empty($couponInfo['use_time'])) {
         throw new exception('该优惠券已经使用过!');
     } elseif ($couponInfo['end_time'] < time()) {
         throw new exception('该优惠券已经过期!');
     }
     $couponInfo->user_id = $userId;
     $couponInfo->band_time = time();
     $flag = $couponInfo->save();
     if (empty($flag)) {
         throw new exception('优惠券绑定失败!');
     }
     return true;
 }
Example #22
0
 public function actionSubmitpaypal()
 {
     $paypal = new GetExpressCheckoutDetails();
     $details = $paypal->getResponse();
     //$totalPrice = urldecode($details['AMT']);
     $what = urldecode($details['CUSTOM']);
     $desc = urldecode($details["DESC"]);
     $cst = $details["CUSTOM"];
     $cst = explode("_", $cst);
     $type = $cst[2];
     $cst = $cst[1];
     $discount = $cst[3];
     if ($type == "basic") {
         $totalPrice = "19.95";
     } else {
         if ($type == "basicplus") {
             $totalPrice = "24.95";
         } else {
             if ($type == "pro") {
                 $totalPrice = "29.95";
             }
         }
     }
     $prorate = round($totalPrice * (((double) date('t') - (double) date('j')) / (double) date('t')), 2);
     $initAmt = $prorate + 0;
     // switch ($_SESSION["discount"]) {
     //     case 'MFVideoMgr-100':
     //         $prorate = $initAmt = 0;
     //         break;
     //     case 'MFVM-50A':
     //         $prorate = round((float)$prorate * 0.50, 2);
     //         $initAmt = round((float)$initAmt * 0.50, 2);
     //         break;
     //     case 'MFVM25':
     //         $prorate = round((float)$prorate * 0.25, 2);
     //         $initAmt = round((float)$initAmt * 0.25, 2);
     //         break;
     // }
     if (isset($_SESSION["discount"])) {
         Yii::import('admin.models.*');
         $coupon = Coupon::model()->findByAttributes(array('name' => $_SESSION["discount"]));
         if ($coupon) {
             if ($coupon->discount >= 100) {
                 //$initAmt = $initAmt - (2*$initAmt);
                 $prorate = 0.01;
                 $initAmt = 0.01;
             } else {
                 $prorate = $prorate - round((double) $prorate * ($coupon->discount / 100), 2);
                 $initAmt = $initAmt - round((double) $initAmt * ($coupon->discount / 100), 2);
             }
         }
     }
     $payment = new DoExpressCheckoutPayment($initAmt);
     $payment_response1 = $payment->getResponse();
     $recur = new CreateRecurringPaymentsProfile(ucfirst($type) . " Subscription for VidMgr, {$totalPrice} /mo", $totalPrice);
     // \n $0 One Time Setup Fee
     $recur->setNVP("SUBSCRIBERNAME", user()->Name);
     $recur->setNVP("PROFILEREFERENCE", "userid_" . uid() . "_" . $cst);
     $recur->setNVP("PROFILESTARTDATE", date("Y-m-d\\TH:i:s\\Z", mktime(0, 0, 0, date("m") + 1, 1, date("y"))));
     $recur->setNVP("MAXFAILEDPAYMENTS", "1");
     $recur->setNVP("BILLINGPERIOD", "Month");
     $recur->setNVP("BILLINGFREQUENCY", "1");
     $recur->setNVP("CURRENCYCODE", "USD");
     $recur->setNVP('L_PAYMENTREQUEST_0_NAME0', "Video Subscription - Basic 40MB");
     $recur->setNVP('L_PAYMENTREQUEST_0_ITEMCATEGORY0', 'Digital');
     $recur->setNVP('L_PAYMENTREQUEST_0_AMT0', $totalPrice);
     $recur->setNVP('L_PAYMENTREQUEST_0_QTY0', "1");
     $recur->setNVP("INITAMT", $initAmt);
     $payment_response = $recur->getResponse();
     Ytrace($payment_response);
     Ytrace($details);
     if ($payment_response["ACK"] == "Success" && $payment_response1["ACK"] == "Success") {
         Video::model()->updateByPk($cst, array("active" => "1", "lastPayment" => sqlDate(), "payModel" => $type));
         User::model()->updateByPk(uid(), array("payModel" => $type, "coupon" => ""));
         $this->process($cst, $type);
     } else {
         $this->renderText("There was some problem in processing your request. Please try again. If you repeatedly face this error please use the contact page, we would love to help you.");
     }
 }
Example #23
0
 function beforeDelete()
 {
     $criteria = new CDbCriteria();
     $criteria->condition = 'listing_id=:listing_id';
     $criteria->params = array(':listing_id' => $this->listing_id);
     ListingCategory::model()->deleteAll($criteria);
     ListingLocation::model()->deleteAll($criteria);
     Coupon::model()->deleteAll($criteria);
     // delete logo file
     if ($this->logo != '') {
         $imageFile = Yii::app()->user->getFullPathToImages(Yii::app()->params['listingLogo']) . $this->logo;
         @unlink($imageFile);
     }
     return parent::beforeDelete();
 }
Example #24
0
 /**
  * 删除活动信息
  * DELETE /api/activity/{activityId}
  */
 public function actionRestremove()
 {
     $this->checkRestAuth();
     $activity = Activity::model()->findByPk($_GET['activityId']);
     if ($activity == null || $activity->archived == 0) {
         return $this->sendResponse(404, 'activity is not found');
     }
     $activity->archived = 0;
     $activity->code = $activity->code . '-removed-' . $activity->id;
     // 删除以后 编码需要释放
     $criteria = new CDbCriteria();
     $criteria->compare('archived', 1);
     $criteria->addCondition('achieved_time IS NULL');
     $criteria->addCondition('open_id IS NULL');
     $criteria->compare('activity_id', $activity->id);
     $criteria->order = 'achieved_time desc';
     $coupns = Coupon::model()->findAll($criteria);
     foreach ($coupns as $coupon) {
         $coupon->archived = 0;
         if (!$coupon->save()) {
             return $this->sendResponse(200, 'failed to update coupon.');
         }
     }
     if ($activity->save()) {
         $this->sendResponse(200, 'removed.');
     } else {
         $this->sendResponse(500, 'failed to remove.');
     }
 }
Example #25
0
 /**
  * Добавление купона к подписке
  * 
  * @param $code - Код купона
  * @return bool|array - true - в случае успешного добавления, array - список ошибок
  */
 public function addCoupon($code)
 {
     if (!empty($this->coupon)) {
         return;
     }
     $code = strtoupper($code);
     /* @var $coupon Coupon */
     $coupon = Coupon::model()->getCouponByCode($code);
     if ($coupon) {
         $errors = $coupon->getCouponErrors();
         if (!$errors) {
             $this->coupon_id = $coupon->id;
             $this->coupon = $coupon;
             $this->total_cost -= (int) $this->total_cost * $coupon->value / 100;
             $this->save();
             return true;
         } else {
             return $errors;
         }
     } else {
         return array('Купон не найден');
     }
 }
Example #26
0
 /**
  * @param $code
  *
  * @return mixed
  */
 public function findCouponByCode($code)
 {
     return Coupon::model()->getCouponByCode(mb_strtoupper(trim($code)));
 }
Example #27
0
 public function actionDiscount()
 {
     $p = $_POST["code"];
     $res = array("success" => true);
     $_SESSION["discount"] = $p;
     sess("discount", $p);
     $now = new CDbExpression('NOW()');
     Yii::import('admin.models.*');
     // $coupon= Coupon::model()->findByAttributes(
     //         array('name'=>$p,'status'=>1),
     //        'end_date<='. $now);
     // echo print_r($date);
     //die();
     $coupon = Coupon::model()->findAll(array('condition' => 'status=:status AND name=:name AND end_date < :date', 'params' => array(':status' => 1, ':name' => $p, ':date' => $now)));
     if ($coupon) {
         //print_r($coupon);
         $res = array("success" => true);
         $res["discount"] = (int) $coupon[0]->discount;
         echo json_encode($res);
     } else {
         $res = array("success" => false);
         unset($_SESSION["discount"]);
         echo json_encode($res);
     }
     // die();
     //   switch ($p) {
     //       case 'MFVideoMgr-100':
     //           $res["discount"] = 100;
     //           break;
     //       case 'MFVM-50A':
     //           $res["discount"] = 50;
     //           break;
     //       case 'MFVM25':
     //           $res["discount"] = 25;
     //           break;
     //       default:
     //           $res = array("success" => false);
     //           unset($_SESSION["discount"]);
     //           break;
     //   }
     //   echo json_encode($res);
 }
Example #28
0
 /**
  * 通过活动编码和OpenId获得优惠券
  * GET /api/coupon/achieve
  */
 public function actionRestachieve()
 {
     $this->checkRestAuth();
     // 检查参数
     if (!isset($_GET['code']) || !isset($_GET['openId'])) {
         return $this->sendResponse(400, 'missed parameters');
     }
     $openId = $_GET['openId'];
     // 结果对象
     $result = array('activities' => array(), 'coupons' => array());
     // 判断活动当前状态
     $criteria = new CDbCriteria();
     $criteria->compare('code', $_GET['code']);
     $criteria->compare('archived', 1);
     $criteria->limit = 1;
     $criteria->order = 'created_time desc';
     $activities = Activity::model()->findAll($criteria);
     $activity;
     // 找不到
     if (count($activities) != 1) {
         echo CJSON::encode($result);
         return;
     } else {
         $result['activities'] = $activities;
         $activity = $activities[0];
         // 暂停状态
         if ($activity->enabled == 0) {
             echo CJSON::encode($result);
             return;
         }
     }
     // 先判断是否已领取
     $criteria = new CDbCriteria();
     $criteria->compare('archived', 1);
     $criteria->compare('open_id', $openId);
     $criteria->order = 'achieved_time desc';
     $criteria->limit = 1;
     $achieves = array();
     $isRestricted = false;
     if (intval($activity->restrict_days) > 0) {
         // 如果已经领过优惠券,且不符合该活动有N天限制,不可以领取
         $achieves = Coupon::model()->findAll($criteria);
         if (count($achieves) > 0) {
             if (time() - strtotime($achieves[0]->achieved_time) < intval($activity->restrict_days) * 60 * 60 * 24) {
                 $isRestricted = true;
             }
         }
     }
     $criteria->compare('activity_id', $activity->id);
     $achieves = Coupon::model()->findAll($criteria);
     $result['coupons'] = $achieves;
     // 判断是否还可以继续领取
     if ($isRestricted || count($achieves) > 0) {
         echo CJSON::encode($result);
         return;
     }
     // 再判断有没有优惠券
     $criteria = new CDbCriteria();
     $criteria->compare('archived', 1);
     $criteria->addCondition('achieved_time IS NULL');
     $criteria->addCondition('open_id IS NULL');
     $criteria->compare('activity_id', $activity->id);
     $criteria->limit = 10;
     $coupons = Coupon::model()->findAll($criteria);
     if (count($coupons) == 0) {
         echo CJSON::encode($result);
         return;
     }
     // 随机获得优惠券
     $total = count($coupons);
     $offset = 0;
     if ($total > 1) {
         $offset = (int) ($total * rand(0, 1));
         if ($offset != 0) {
             $offset -= 1;
         }
         if ($offset >= $total) {
             $offset = 0;
         }
     }
     // 写入领取记录
     $coupon = $coupons[$offset];
     // 再次判断记录是否被领
     $checkCoupon = Coupon::model()->findByPk($coupon->id);
     if ($checkCoupon->open_id != null || $coupon->achieved_time != null) {
         echo CJSON::encode($result);
         return;
     }
     $coupon->open_id = $openId;
     $coupon->achieved_time = new CDbExpression('NOW()');
     if ($coupon->save()) {
         array_push($result['coupons'], $coupon);
         echo CJSON::encode($result);
     } else {
         echo CJSON::encode($result);
     }
 }