Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class Deals extends CFormModel {
- //api result
- public $response;
- //pagination
- public $pageCount;
- public $pageOffset;
- //identity
- public $user;
- public $userId;
- public $communityId;
- public $thisObj;
- public $community;
- //General
- public $dealId;
- public $deal;
- //deal attributes
- public $type;
- public $owner;
- public $title;
- public $description;
- public $start_date;
- public $end_date;
- public $days;
- public $country;
- public $city;
- public $visibility;
- public $credit_type;
- public $tags;
- public $price;
- public $limits;
- public $rewardinfo;
- public $auto;
- public $status;
- public $location;
- public $cost_per_view;
- public $module;
- public $view_range_km;
- public $probability;
- public $level;
- public $total_available;
- public $group;
- public $share_for_reward;
- public $category;
- //Roles
- public $roles;
- public $take;
- public $assign;
- public $redeem;
- //rewards
- public $rewardtype;
- public $amount;
- public $auto_redeem;
- public $self_redeem;
- public $deal_id;
- public $role_id;
- public $other_reward;
- //affiliate
- public $affiliate_fee;
- //PayPerTake
- public $pay_per_take;
- public $sharer;
- //Food Type
- public $food_type;
- //types of deals
- public $dealinfo;
- public $take_action;
- // food
- public $menu;
- //For ticket
- public $ticket_type;
- public $tickets;
- public $visitor_details;
- public $venue;
- public $event_date;
- public $event_type;
- public $start_event_date;
- public $end_event_date;
- public $payment_method;
- public $wallet_id;
- public $paid;
- //for stamp
- public $notes;
- //prize draw
- public $prize_info;
- public $prize;
- public $terms_and_condition;
- public $period;
- public $winner;
- public $draw_date;
- public $prize_redeemed;
- public $prize_taken;
- public $time;
- //survey
- public $deal_type;
- public $poll_question;
- public $poll_choices;
- public $survey_type;
- public $survey_question;
- public $survey_choices;
- //competition
- public $competition_answer;
- public $competition_question;
- public $competition_choices;
- //For stamp type deal
- public $total_stamps;
- public $starting_stamps;
- public $limit_per_day;
- public $code;
- //For the limits
- public $max_limit_per_user;
- public $max_global_limit;
- public $max_limit_per_day;
- //For Promo
- public $promoCodes;
- public $promoCodeType;
- public $emailSubject;
- public $emailMessage;
- public $methodofpayment;
- public $guestlist;
- public $guestListColors;
- public $walletId = 534;
- public function rules() {
- return array(
- // username and password are required
- array('type, owner, title, visibility, start_date, limits, country', 'required', 'except' => 'dataview', 'message' => '{attribute}_required'),
- //array('total_stamps, starting_stamps, limit_per_day', 'required', 'on'=>'stamp'),
- array('total_stamps', 'required', 'on' => 'stamp'),
- array('total_stamps, limit_per_day', 'numerical', 'min' => 1, 'on' => 'stamp'),
- //array('days, country, price, total_stamps, starting_stamps, limit_per_day, max_limit_per_user, max_global_limit', 'numerical','integerOnly'=>true,),
- array('days, country, total_stamps, limit_per_day, max_limit_per_user, max_global_limit', 'numerical', 'integerOnly' => true,),
- array('take', 'validateRole', 'type' => 'member'),
- array('assign, redeem', 'validateRole', 'type' => 'staff'),
- array('start_date, end_date', 'type', 'type' => 'date', 'dateFormat' => 'yyyy-MM-dd', 'message' => 'invalid_{attribute}_format'),
- array('start_date', 'validateDate'),
- array('type', 'in', 'range' => array('stamp', 'coupon', 'ticket', 'promo', 'inventory', 'game', 'catalog', 'bus_reservation', 'food', 'book_spa', 'sticker', 'jobs', 'resume', 'datapage', 'load', 'bonus'), 'allowEmpty' => false, 'message' => 'invalid_{attribute}'),
- array('dealinfo', 'validateDealInfo'),
- );
- }
- /**
- * @return array customized attribute labels (name=>label)
- */
- public function attributeLabels() {
- return array(
- 'title' => 'title',
- 'food_type' => 'food_type',
- 'type' => 'type',
- 'description' => 'description',
- 'visibility' => 'visibility',
- 'country' => 'country',
- 'city' => 'city',
- 'start_date' => 'start_date',
- 'end_date' => 'start_date',
- 'days' => 'days',
- );
- }
- /*
- * * Input and Output
- seeErrors
- formatOwner
- formatStatus
- formatDeal
- */
- public function internalError($message, $model = NULL, $action = NULL) {
- if (!$action) {
- $action = 'general';
- }
- if (!$model)
- $model = $this;
- //Common::pre($this->getErrors()); exit($message);
- Yii::trace($message . ';' . $model->getErrors(), 'system.deal.' . $action);
- Yii::log($message, 'error', 'system.deal.' . $action);
- throw new CHttpException(403, "internal_error");
- }
- public function seeErrors() {
- $result = array();
- $errors = $this->getErrors();
- $errorsStr = implode(',', array_keys($errors));
- Yii::trace('errors=' . $errorsStr, 'system.deal.create');
- foreach ($errors as $key => $value) {
- $result = array_merge($result, $value);
- }
- return $result;
- }
- public static function formatOwner($owner) {
- //For formatting the owner info in deals
- $object = new stdClass;
- $object->id = intval($owner['id']);
- $community = Communities::model()->findByPk($owner['id']);
- $object->name = $community->community_name;
- $object->type = $owner['type'];
- $object->verified = ($owner['verified']) ? "verified" : "unverified";
- $object->mobile = $community['community_mobile'];
- return $object;
- }
- //search for a value and returns the key in an n dimensional array.
- public static function search_in_array($srchvalue, $array) {
- if (is_array($array) && count($array) > 0) {
- $foundkey = array_search($srchvalue, $array);
- if ($foundkey === FALSE) {
- foreach ($array as $key => $value) {
- if (is_array($value) && count($value) > 0) {
- $foundkey = Deals::search_in_array($srchvalue, $value);
- if ($foundkey != FALSE)
- return $foundkey;
- }
- }
- } else
- return $foundkey;
- }
- }
- public static function formatStatus($status) {
- //For formatting the status type in deals
- if ($status == 1) {
- return "active";
- } elseif ($status == 2) {
- return "expired";
- } elseif ($status == 3) {
- return "complete";
- } elseif ($status == 4) {
- return "deactivated";
- } elseif ($status == 5) {
- return "pending";
- } elseif ($status == 6) {
- return "archived";
- } elseif ($status == 7) {
- return "bookmarked";
- } elseif ($status == 8) {
- return "in use";
- } elseif ($status == 9) {
- return "ordered";
- } else {
- return "blocked";
- }
- }
- public static function formatDeal($deal, $isStaff = false, $communityId = null, $userId = null) {
- //For formatting the deal details
- $object = new stdClass();
- $object->id = $deal['_id']->__toString();
- $object->type = $deal['type'];
- if ($deal['food_type']) {
- $object->food_type = $deal['food_type'];
- }
- $object->owner = self::formatOwner($deal['owner']);
- $object->status = self::formatStatus($deal['status']);
- $object->visibility = $deal['visibility'];
- $object->title = $deal['title'];
- $object->description = $deal['description'];
- $object->category = $deal['category'];
- $object->start_date = $deal['start_date'];
- $object->end_date = $deal['end_date'];
- $object->country = $deal['country'];
- $object->location = $deal['location'];
- $object->city = $deal['city'];
- $object->price = $deal['price'];
- $object->credit_type = $deal['credit_type'];
- $object->tags = $deal['tags'];
- $object->rewardinfo = $deal['rewardinfo'];
- $object->auto = $deal['auto'];
- $object->pay_per_take = $deal['pay_per_take'];
- $object->pay_per_click = $deal['pay_per_click'];
- $object->view_range_km = $deal['view_range_km'];
- $object->probability = $deal['probability'];
- $object->level = $deal['level'];
- $object->total_available = $deal['total_available'];
- $object->limits = $deal['limits'];
- if ($isStaff) {
- $object->dealinfo = $deal['dealinfo'];
- }
- if ($deal['type'] == 'promo') {
- $object->limits = $deal['limits']['max_limit_per_user'];
- }
- if (isset($deal['delivery_options'])) {
- $object->delivery_options = empty($deal['delivery_options']) ? (object) $deal['delivery_options'] : $deal['delivery_options'];
- }
- if ($deal['type'] == 'catalog')
- $object->items = $deal['items'];
- if ($deal['game_slots'])
- $object->game_slots = $deal['game_slots'];
- if ($isStaff) {
- $object->affiliate_fee = $deal['affiliate_fee'];
- $object->roles = $deal['roles'];
- //statistics
- $statistics = new stdClass();
- $statistics->visit_count = $deal['dealinfo']['visitors'] ? sizeof($deal['dealinfo']['visitors']) : 0;
- $statistics->bookmark_count = $deal['sharedBookmarkCount'] ? $deal['sharedBookmarkCount'] : 0;
- $statistics->redeem_count = $deal['sharedRedeemCount'] ? $deal['sharedRedeemCount'] : 0;
- $object->cost_per_view = $deal['cost_per_view'];
- $object->share_for_reward = $deal['share_for_reward'];
- $total = 0;
- if ($deal['cost_per_view']['amount'] > 0) {
- $total = $deal['cost_per_view']['amount'];
- $total = $total * $statistics->visit_count . ' ' . WalletTypes::getWalletName($deal['cost_per_view']['wallet_id'], true);
- }
- $statistics->advertising_spent = $total;
- $object->statistics = $statistics;
- }
- if ($communityId == null && $userId > 0) {
- $object->take = Deals::checkIfUserCanTakeDeal($deal, $userId);
- $object->favorite = FavoriteCatalogs::checkFavourite($userId, $object->id);
- }
- if ($deal['url'])
- $object->url = $deal['url'];
- $object->image = SELF::getAvatar($object->id, true);
- return $object;
- }
- public static function formatPaymentMethod($methodArray) {
- $result = array();
- foreach ($methodArray as $key => $value) {
- switch ($value) {
- case 1:
- $result[$value] = 'Tagcash';
- break;
- case 2:
- $result[$value] = 'Cash on Pickup';
- break;
- case 3:
- $result[$value] = 'Paypal';
- break;
- case 4:
- $result[$value] = 'DragonPay';
- break;
- case 5:
- $result[$value] = 'Credit Card';
- break;
- default:
- $result[$value] = 'Other';
- break;
- }
- }
- return $result;
- }
- public static function formatDealInfo($deal) {
- $object = new stdClass();
- $object->type = $deal['type'];
- $object->dealinfo = (object) $deal['dealinfo'];
- //dbug::p($object->dealinfo, true);
- if ($object->type == "inventory") {
- if ($object->dealinfo->inventoryType) {
- $object->dealinfo->inventory_type = $object->dealinfo->inventoryType;
- unset($object->dealinfo->inventoryType);
- }
- }
- if ($object->type == "game") {
- $gameType = $deal['dealinfo']['gameType'];
- if ($gameType == 1) {
- $object->dealinfo->game_type = "bomb";
- if ($object->dealinfo->cellSize) {
- $object->dealinfo->cell_size = $object->dealinfo->cellSize;
- unset($object->dealinfo->cellSize);
- }
- } else if ($gameType == 2) {
- $object->dealinfo->game_type = "hi_lo";
- } else if ($object->gameType == 3) {
- $object->dealinfo->game_type = "dice";
- } else if ($gameType == 4) {
- $object->dealinfo->game_type = "spin_wheel";
- //wins
- if ($object->dealinfo->winCount) {
- $object->dealinfo->wins = $object->dealinfo->winCount;
- unset($object->dealinfo->winCount);
- }
- //loses
- if ($object->dealinfo->loseCount) {
- $object->dealinfo->loses = $object->dealinfo->loseCount;
- unset($object->dealinfo->loseCount);
- }
- } else if ($gameType == 5) {
- $object->dealinfo->game_type = "rock_paper_scissor";
- }
- unset($object->dealinfo->gameType);
- }
- return $object->dealinfo;
- }
- /*
- * * end of Input and Output
- */
- /*
- * * General
- setIdentity
- */
- public function setIdentity($thisObj) {
- $this->thisObj = $thisObj;
- $this->communityId = $thisObj->_COMMUNITYID;
- $this->userId = $thisObj->_USERID;
- $this->user = $thisObj->_USEROBJ;
- $this->community = $thisObj->_COMMUNITYOBJ;
- return true;
- }
- /*
- * * Validations
- validateRole
- validateDealId
- validateDate
- checkIfDealExists
- isPermission
- */
- public function validateRole($attribute, $params) {
- if ($params['type'] == "member") {
- $criteria = new CDbCriteria();
- $criteria->condition = "role_type != 3";
- $criteria->addInCondition("id", $this->$attribute);
- $result = CommunityRoles::model()->findAll($criteria);
- } else {
- $criteria = new CDbCriteria();
- $criteria->condition = "role_type = 3";
- $criteria->addInCondition("id", $this->$attribute);
- $result = CommunityRoles::model()->findAll($criteria);
- }
- if ($result) {
- //meaning there was a validation error
- $this->addError($attribute, 'Role error');
- }
- }
- public function validateDealId($attribute, $params) {
- $collection = Yii::app()->edmsMongoCollection('deals');
- $deal = $collection->findOne(array("_id" => new MongoID($this->$attribute)));
- if (!$deal) {
- $this->addError($attribute, 'Invalid deal Id');
- } else {
- if ($deal['rewardinfo']['type'] == "deal") {
- $this->addError($attribute, 'Deal chaining not allowed');
- }
- if (strtotime($this->start_date) < strtotime($deal['start_date']) || strtotime($this->start_date) > strtotime($deal['end_date'])) {
- $this->addError("start_date", "Deal start date should be within the reward deal's duration");
- }
- if (strtotime($this->end_date) < strtotime($deal['start_date']) || strtotime($this->end_date) > strtotime($deal['end_date'])) {
- $this->addError("end_date", "Deal end date should be within the reward deal's duration");
- }
- }
- }
- public function validateDate($attribute, $params) {
- //required
- if (!$this->end_date && !$this->days) {
- $this->addError('days', 'days_required');
- }
- //validate
- $currentDateTimestamp = strtotime(date('Y-m-d'));
- $startDateTimestamp = strtotime($this->start_date);
- $endDateTimestamp = strtotime($this->end_date);
- if ($this->start_date && $currentDateTimestamp > $startDateTimestamp) {
- $this->addError('start_date', 'invalid_start_dates');
- }
- if ($this->end_date && $endDateTimestamp <= $startDateTimestamp) {
- $this->addError('end_date', 'invalid_end_date');
- }
- }
- public function checkIfDealExists() {
- if (!$this->deal && $this->validateMongoId()) {
- $collection = Yii::app()->edmsMongoCollection('deals');
- $cond = array("_id" => new MongoID($this->dealId));
- if ($this->communityId) {
- $cond["owner.id"] = intval($communityId);
- $cond["owner.type"] = "community";
- }
- $this->deal = $collection->findOne($cond);
- }
- if (!$this->deal) {
- return false;
- }
- return true;
- }
- public function isPermission($todo, $deal = NULL) {
- //convert object to array
- if (is_object($deal)) {
- $deal = (array) $deal;
- }
- $userId = $this->userId;
- $communityId = $this->communityId;
- if ($communityId) {
- //If the deal is owned by a community
- if (!CommunityUsers::isStaffOf($userId, $communityId)) {
- throw new CHttpException(403, "not_staff");
- }
- $role = CommunityUsers::getRoleOfUser($userId, $communityId);
- if ($todo == 'list') {
- //list
- } else if ($todo == 'history') {
- //history list
- } else if ($todo == 'assign') {
- //check deal
- if (!$deal) {
- throw new CHttpException(403, "invalid_deal");
- }
- //check community
- if ($deal['owner']['type'] != 'community') {
- throw new CHttpException(403, "invalid_deal_community");
- } else {
- if ($communityId != $deal['owner']['id']) {
- throw new CHttpException(403, "invalid_deal_community");
- }
- }
- if ($role->role_type == 1) { //owner
- return true;
- } else {
- if (!$deal['roles']['assign']) {
- throw new CHttpException(403, "permission_denied");
- } else {
- if (!in_array($role->role_id, $deal['roles']['assign'])) {
- throw new CHttpException(403, "permission_denied");
- }
- }
- }
- }
- //edit deal
- else if ($todo == 'edit') {
- //check deal
- if (!$deal) {
- throw new CHttpException(403, "invalid_deal");
- }
- //check community
- if ($deal['owner']['type'] != 'community') {
- throw new CHttpException(403, "invalid_deal_community");
- } else {
- if ($communityId != $deal['owner']['id']) {
- throw new CHttpException(403, "invalid_deal_community");
- }
- }
- if ($role->role_type == 1) { //owner
- return true;
- }
- } else if ($todo == 'redeem') {
- //check deal
- if (!$deal) {
- throw new CHttpException(403, "invalid_deal");
- }
- //check community
- if ($deal['owner']['type'] != 'community') {
- throw new CHttpException(403, "invalid_deal_community");
- } else {
- if ($communityId != $deal['owner']['id']) {
- throw new CHttpException(403, "invalid_deal_community");
- }
- }
- if ($role->role_type == 1) { //owner
- return true;
- } else {
- if (!$deal['roles']['redeem']) {
- throw new CHttpException(403, "permission_denied");
- } else {
- if (!in_array($role->role_id, $deal['roles']['redeem'])) {
- throw new CHttpException(403, "permission_denied");
- }
- }
- }
- } else {
- $this->internalError('checking permissions', NULL, 'permission');
- }
- return true;
- } else {
- //If the deal is owned by a user
- if ($userId == $deal['owner']['id']) {
- return true;
- } else if ($todo == 'redeem') {
- if ($deal['rewardinfo']['self_redeem']) {
- return true;
- }
- throw new CHttpException(403, "not_self_redeem");
- }
- }
- //$this->addError('transaction_type', 'permission_denied');
- return true;
- }
- public function validateDealInfo($attribute, $params) {
- if (in_array($this->type, array('stamp', 'promo', 'inventory', 'game')) && !$this->dealinfo) {
- $this->addError($attribute, 'invalid_dealinfo');
- }
- //dbug::p($this->dealinfo->gameType);
- //inventory
- if ($this->type == 'inventory') {
- if (!$this->dealinfo->inventoryType ||
- !in_array($this->dealinfo->inventoryType, array('inOut', 'fixed', 'resale'))) {
- $this->addError($attribute, 'invalid_inventory_type');
- }
- }
- //game
- else if ($this->type == 'game') {
- if (!$this->dealinfo->gameType) {
- $this->addError($attribute, 'invalid_game_type');
- } else {
- //game general params
- if (!$this->dealinfo->hits) {
- $this->addError($attribute, 'invalid_attempts');
- }
- if (!$this->dealinfo->needed) {
- $this->addError($attribute, 'invalid_needed');
- }
- if ($this->dealinfo->status === NULL) {
- $this->addError($attribute, 'status');
- }
- if ($this->dealinfo->game_status === NULL) {
- $this->addError($attribute, 'game_status');
- }
- //game type
- if ($this->dealinfo->gameType == 1) {
- if (!$this->dealinfo->bombs) {
- $this->addError($attribute, 'invalid_bombs');
- }
- if (!$this->dealinfo->wins) {
- $this->addError($attribute, 'invalid_wins');
- }
- if (!$this->dealinfo->cellSize) {
- $this->addError($attribute, 'invalid_cell_size');
- }
- } else if ($this->dealinfo->gameType == 4) {
- if (!$this->dealinfo->winCount) {
- $this->addError($attribute, 'invalid_wins');
- }
- if (!$this->dealinfo->loseCount) {
- $this->addError($attribute, 'invalid_loses');
- }
- }
- }
- }
- }
- /*
- * * end of Validations
- */
- /*
- * * deals - create and extend
- */
- public function createDeal($data, $id, $type) {
- $this->owner = new stdClass();
- $this->roles = new stdClass();
- $this->dealinfo = new stdClass();
- //Common::pre($data, true);
- //$this->attributes = $data;
- if ($type == "user") {
- //for future
- $userModel = Users::model()->findByPk($id);
- $this->owner->id = intval($id);
- $this->owner->type = "user";
- $this->owner->name = $userModel->user_firstname . " " . $userModel->user_lastname;
- } else {
- //If a community is making the deal
- $communityModel = Communities::model()->findByPk($id);
- $this->communityId = $id;
- $this->owner->id = intval($id);
- $this->owner->type = "community";
- $this->owner->name = $communityModel->community_name;
- $this->owner->mobile = $communityModel->community_mobile;
- $this->owner->verified = intval($communityModel->community_verified);
- $take = array();
- $assign = array();
- $redeem = array();
- $view = array();
- for ($i = 0; $i < count($data['roles']['take']); $i++) {
- //For converting the elements to integer
- $take[$i] = intval($data['roles']['take'][$i]);
- }
- for ($i = 0; $i < count($data['roles']['assign']); $i++) {
- //For converting the elements to integer
- $assign[$i] = intval($data['roles']['assign'][$i]);
- }
- for ($i = 0; $i < count($data['roles']['redeem']); $i++) {
- //For converting the elements to integer
- $redeem[$i] = intval($data['roles']['redeem'][$i]);
- }
- for ($i = 0; $i < count($data['roles']['view']); $i++) {
- //For converting the elements to integer
- $view[$i] = intval($data['roles']['view'][$i]);
- }
- //if no roles specified, add default roles
- if (!isset($data['roles']['take'])) {
- $take[] = CommunityRoles::getDefaultRole($this->owner->id)->id;
- }
- /* if(!isset($data['roles']['view'])){
- $view[] = CommunityRoles::getDefaultRole($this->owner->id)->id;
- } */
- if (empty($assign)) {
- $assign = CommunityRoles::getRoles($id, 'owner');
- }
- if (empty($redeem)) {
- $redeem = CommunityRoles::getRoles($id, 'staff');
- if (is_array($redeem))
- $redeem = array_merge($redeem, $assign);
- else
- $redeem = $assign;
- }
- $this->roles->take = $take;
- $this->roles->assign = $assign;
- $this->roles->redeem = $redeem;
- $this->roles->view = $view;
- $this->take = $take;
- $this->assign = $assign;
- $this->redeem = $redeem;
- $this->credit_type = $data['credit_type'];
- //$this->validatorList->add(CValidator::createValidator('required', $this, 'credit_type'));
- //$this->validatorList->add(CValidator::createValidator('in', $this, 'credit_type', array('range'=>array("open", "closed"), 'allowEmpty' => false)));
- }
- //title
- if ($data['title']) {
- $this->title = $data['title'];
- }
- if ($data['food_type']) {
- $this->food_type = $data['food_type'];
- }
- //rewardinfo
- if ($data['rewardinfo']) {
- $this->rewardinfo = $data['rewardinfo'];
- }
- //game slots - include in slot game rewards
- if (isset($data['game_slots'])) {
- $gameslot = $data['game_slots'];
- $game_slots = new stdClass;
- if ($gameslot['status'] == 1)
- $game_slots->status = intval(1);
- else
- $game_slots->status = intval(0);
- if ($gameslot['limit'] > 0)
- $game_slots->limit = intval($gameslot['limit']);
- else
- $game_slots->limit = intval(0);
- }
- //share_for_reward
- $share_for_reward = new stdClass();
- if ($data['share_for_reward'] && $data['share_for_reward']['amount']) {
- if ((!in_array($data['type'], array('load', 'bonus'))) && $data['share_for_reward']['wallet_id']) {
- $share_for_reward->amount = $data['share_for_reward']['amount'];
- $share_for_reward->type = 'wallet';
- $share_for_reward->wallet_id = $data['share_for_reward']['wallet_id'];
- $this->share_for_reward = $share_for_reward;
- } else {
- $share_for_reward->amount = $data['share_for_reward']['amount'];
- $share_for_reward->type = $data['type'];
- $share_for_reward->owner_id = $this->userId;
- $this->share_for_reward = $share_for_reward;
- }
- }
- //location
- if ($data['location']) {
- $this->location = array(floatval($data['location'][0]), floatval($data['location'][1]));
- if (sizeof($this->location) != 2) {
- $this->addError($attribute, 'Invalid location format(long,lat)');
- } else if ((floatval($data['location'][0]) == 0) || ((floatval($data['location'][1]) == 0))) {
- $this->location = null;
- }
- }
- //country
- if ($data['country']) {
- $this->country = $data['country'];
- } else {
- $this->country = $this;
- }
- //limits
- if ($data['limits']) {
- $this->limits = $data['limits'];
- $this->max_limit_per_user = $data['limits']['max_limit_per_user'];
- $this->max_global_limit = $data['limits']['max_global_limit'];
- $this->max_limit_per_day = $data['limits']['max_limit_per_day'];
- } else {
- $this->limits = array();
- }
- //visibility
- if ($data['visibility']) {
- $this->visibility = $data['visibility'];
- } else {
- $this->visibility = 'public';
- }
- //view range in km
- if ($data['view_range_km'])
- $this->view_range_km = $data['view_range_km'];
- //probability
- if ($data['probability'])
- $this->probability = intval($data['probability']);
- //level
- if ($data['level'])
- $this->level = intval($data['level']);
- //total availabe gifts
- if ($data['total_available'])
- $this->total_available = $data['total_available'];
- //tag group
- if ($data['group'])
- $this->group = $data['group'];
- //price
- $price = new stdClass();
- $price->type = "none";
- if ($data['price'] && $data['price']['amount']) {
- $price->amount = $data['price']['amount'];
- $price->type = 'reward';
- if ($data['price']['type'] == "wallet") {
- $price->type = 'wallet';
- $price->wallet_id = $data['price']['wallet_id'];
- }
- } elseif ($data['price'] && $data['price']['options']) {
- $price->type = ($data['price']['type']) ? $data['price']['type'] : 'wallet';
- $price->wallet_id = ($data['price']['wallet_id']) ? intval($data['price']['wallet_id']) : 0;
- $priceOptions = array();
- foreach ($data['price']['options'] as $options) {
- $option = new stdClass();
- $option->availability = $options['availability'];
- $option->category = $options['category'];
- $option->description = $options['description'];
- $option->limit = $options['limit'];
- $option->price = $options['price'];
- $option->quantity = intval($options['quantity']);
- $priceOptions[] = $option;
- }
- $price->options = (object) $priceOptions;
- }
- $this->price = $price;
- //affiliate fee
- if ($data['affiliate_fee'] && $data['affiliate_fee']['amount']) {
- $fee = new stdClass();
- $fee->amount = $data['affiliate_fee']['amount'];
- $fee->type = 'reward';
- if ($data['affiliate_fee']['type'] == 'wallet') {
- $fee->type = 'wallet';
- $fee->wallet_id = $data['affiliate_fee']['wallet_id'];
- }
- $this->affiliate_fee = $fee;
- }
- //pay per take
- if ($data['pay_per_take']) {
- $ppt = new stdClass();
- $ppt->amount = $data['pay_per_take']['amount'];
- $ppt->type = $data['pay_per_take']['type'];
- $ppt->budget = $data['pay_per_take']['budget'];
- if ($data['pay_per_take']['type'] == "wallet") {
- $ppt->type = 'wallet';
- $ppt->wallet_id = $data['pay_per_take']['wallet_id'];
- }
- $this->pay_per_take = $ppt;
- }
- //pay per click
- if ($data['pay_per_click']) {
- $ppc = new stdClass();
- $ppc->amount = $data['pay_per_click']['amount'];
- $ppc->type = $data['pay_per_click']['type'];
- $ppc->budget = $data['pay_per_click']['budget'];
- if ($data['pay_per_click']['type'] == "wallet") {
- $ppc->type = 'wallet';
- $ppc->wallet_id = $data['pay_per_click']['wallet_id'];
- }
- $this->pay_per_click = $ppc;
- }
- /*
- * * deal types
- */
- $parsedData = new stdClass();
- if ($data['type'] == 'stamp') {
- $this->module = 'loyalty';
- $this->type = 'stamp';
- $this->total_stamps = $data['dealinfo']['total_stamps'];
- $this->starting_stamps = $data['dealinfo']['starting_stamps'];
- $this->limit_per_day = $data['dealinfo']['limit_per_day'];
- $this->take_action = ($data['dealinfo']['take_action']) ? true : false;
- $this->dealinfo->code = rand();
- $this->dealinfo->total_stamps = ($data['dealinfo']['total_stamps']) ? intval($data['dealinfo']['total_stamps']) : NULL;
- $this->dealinfo->starting_stamps = ($data['dealinfo']['starting_stamps']) ? intval($data['dealinfo']['starting_stamps']) : NULL;
- $this->dealinfo->limit_per_day = ($data['dealinfo']['limit_per_day']) ? intval($data['dealinfo']['limit_per_day']) : NULL;
- $this->dealinfo->take_action = ($data['dealinfo']['take_action']) ? true : false;
- $this->validatorList->add(CValidator::createValidator('required', $this, 'dealinfo'));
- $collection = new Collections();
- $collection->setIdentity($this->thisObj);
- $cData = array('collection_type' => $data['loyalty_stamp_collection_type'],
- 'collection_duration' => 1,
- 'payment_type' => 'tagcash',
- 'name' => $data['title'],
- 'created_from' => 'miskio',
- 'image' => $data['loyalty_stamp_images'],
- 'loyalty_stamp_user_view_type' => $data['loyalty_stamp_user_view_type']);
- $parsedData->collection = $collection->createCollection($cData);
- } elseif ($data['type'] == 'coupon') {
- $this->module = 'loyalty';
- $this->type = 'coupon';
- } elseif ($data['type'] == 'catalog') {
- $this->module = 'ecommerce';
- $this->type = 'catalog';
- $details = array();
- if ($data['catalog_items'] && Common::isJson($data['catalog_items'])) {
- $catalog_items = json_decode($data['catalog_items'], true);
- foreach ($catalog_items as $item) {
- //get complete list of items and store inside items details
- $details[$i]['id'] = intval($item);
- $query = Yii::app()->db->createCommand()
- ->select('c.id,c.category_id,cc.category_name,c.catalog_name,c.description,c.price,c.price_wallet,c.weight,c.sizes,c.colors,c.other,wt.currency_code,c.hashtags,c.time_to_ship,c.stock')
- ->from('catalog c')
- ->leftJoin("catalog_category cc", "cc.id = c.category_id")
- ->leftJoin("wallet_types wt", "wt.id = c.price_wallet")
- ->where('c.id = ' . $item . ' AND c.community_id = ' . $id);
- $result = $query->queryAll();
- if (!$result)
- continue;
- $result = $result[0];
- $details[$i]['catalog_name'] = $result['catalog_name'];
- $details[$i]['category'] = $result['category_name'] ? array('id' => $result['category_id'], 'name' => $result['category_name']) : array();
- $details[$i]['description'] = $result['description'];
- $details[$i]['price'] = array('amount' => $result['price'] ? $result['price'] : 0, 'wallet_id' => $result['price_wallet'], 'wallet_name' => $result['currency_code']);
- $details[$i]['weight'] = $result['weight'];
- $size = array();
- $color = array();
- if ($result['sizes']) {
- $size = explode(',', $result['sizes']);
- }
- if ($result['colors']) {
- $color = explode(',', $result['colors']);
- }
- if ($result['other']) {
- $other = explode(',', $result['other']);
- }
- $details[$i]['sizes'] = $size;
- $details[$i]['colors'] = $color;
- $details[$i]['other'] = $other;
- $details[$i]['stock'] = intval($result['stock']);
- $details[$i]['hashtags'] = $result['hashtags'] ? explode(',', $result['hashtags']) : array();
- $details[$i]['time_to_ship'] = $result['time_to_ship'];
- $i++;
- }
- $catalogs = $details;
- }
- //delivery option
- $parsedData->delivery_options = array();
- if (isset($data['delivery_options']) && is_array($data['delivery_options'])) {
- if ($data['delivery_options']['type'] == 'xend')
- $parsedData->delivery_options = $data['delivery_options'];
- else if ($data['delivery_options']['amount'] > 0 && $data['delivery_options']['wallet_id'] > 0) {
- $parsedData->delivery_options = $data['delivery_options'];
- }
- }
- } elseif ($data['type'] == 'ticket') {
- $this->module = 'ecommerce';
- $this->type = 'ticket';
- if ($data['dealinfo']) {
- $this->dealinfo->ticket_type = $data['dealinfo']['ticket_type'];
- $this->dealinfo->event_name = $data['dealinfo']['event_name'];
- $this->dealinfo->event_type = $data['dealinfo']['event_type'];
- if ($data['dealinfo']['event_date']) {
- $this->dealinfo->event_date = $data['dealinfo']['event_date'];
- } else {
- $this->dealinfo->start_event_date = $data['dealinfo']['start_event_date'];
- $this->dealinfo->end_event_date = $data['dealinfo']['end_event_date'];
- }
- $this->dealinfo->venue = $data['dealinfo']['venue'];
- $this->dealinfo->eventAdditionalInfo = $data['dealinfo']['eventAdditionalInfo'];
- $this->dealinfo->eventAdditionalInfoMandatory = $data['dealinfo']['eventAdditionalInfoMandatory'];
- $this->dealinfo->eventOpeningTime = $data['dealinfo']['eventOpeningTime'];
- $this->dealinfo->eventAddress = $data['dealinfo']['eventAddress'];
- $this->dealinfo->scanCount = $data['dealinfo']['scanCount'];
- if ($data['dealinfo']['scanSchedule']) {
- $scanSchedule = new stdClass();
- $scanSchedule->activity = intval($data['dealinfo']['scanSchedule']['activity']);
- $scanSchedule->start_date = $data['dealinfo']['scanSchedule']['start_date'];
- $scanSchedule->start_time = $data['dealinfo']['scanSchedule']['start_time'];
- $scanSchedule->end_date = $data['dealinfo']['scanSchedule']['end_date'];
- $scanSchedule->end_time = $data['dealinfo']['scanSchedule']['end_time'];
- }
- $this->dealinfo->scanSchedule = $scanSchedule;
- }
- if ($data['methodofpayment']) {
- $this->methodofpayment = $data['methodofpayment'];
- }
- if ($data['guestListColors']) {
- $this->guestListColors = $data['guestListColors'];
- }
- if ($data['guestlist']) {
- $this->guestlist = intval($data['guestlist']);
- }
- } elseif ($data['type'] == 'sticker') {
- $this->module = 'ecommerce';
- $this->type = 'sticker';
- } elseif ($data['type'] == 'promo') {
- $this->module = 'loyalty';
- $this->type = 'promo';
- $parsedPromocodes = array();
- if ($data['dealinfo']['promo_codes'] && is_array($data['dealinfo']['promo_codes'])) {
- foreach ($data['dealinfo']['promo_codes'] as $promoCode) {
- $object = new stdClass;
- $object->code = $promoCode;
- $object->status = 0;
- $parsedPromocodes[] = $object;
- }
- }
- $this->dealinfo->promo_codes = $parsedPromocodes;
- $this->dealinfo->type = ($data['dealinfo']['type']) ? $data['dealinfo']['type'] : "none";
- $this->total_available = count($parsedPromocodes);
- } elseif ($data['type'] == 'inventory') {
- $this->type = 'inventory';
- if ($data['dealinfo']['inventory_type']) {
- $this->dealinfo->inventoryType = $data['dealinfo']['inventory_type'];
- }
- if ($data['dealinfo']['cost_price']) {
- $this->dealinfo->costPrice = $data['dealinfo']['cost_price'];
- }
- if ($data['dealinfo']['retail_price']) {
- $this->dealinfo->retailPrice = $data['dealinfo']['retail_price'];
- }
- if ($data['dealinfo']['sku_code']) {
- $this->dealinfo->skuCode = $data['dealinfo']['sku_code'];
- }
- //print_r($this->dealinfo->inventoryType); exit;
- } elseif ($data['type'] == 'game') {
- $this->type = 'game';
- if ($data['dealinfo']['game_type']) {
- //general params
- $this->dealinfo->status = 0;
- $this->dealinfo->game_status = 0;
- if ($data['dealinfo']['attempts']) {
- $this->dealinfo->hits = $data['dealinfo']['attempts'];
- }
- if ($data['dealinfo']['needed']) {
- $this->dealinfo->needed = $data['dealinfo']['needed'];
- }
- if ($data['dealinfo']['free_tries']) {
- $this->dealinfo->freeTries = $data['dealinfo']['free_tries'];
- }
- if ($data['dealinfo']['game_time']) {
- $this->dealinfo->gameTime = $data['dealinfo']['game_time'];
- }
- //game type
- if ($data['dealinfo']['game_type'] == 'bomb' || $data['dealinfo']['game_type'] == '1') {
- $this->dealinfo->gameType = 1;
- if ($data['dealinfo']['bombs']) {
- $this->dealinfo->bombs = $data['dealinfo']['bombs'];
- }
- if ($data['dealinfo']['wins']) {
- $this->dealinfo->wins = $data['dealinfo']['wins'];
- }
- if ($data['dealinfo']['cell_size']) {
- $this->dealinfo->cellSize = $data['dealinfo']['cell_size'];
- }
- } else if ($data['dealinfo']['game_type'] == 'hi_lo' || $data['dealinfo']['game_type'] == '2') {
- $this->dealinfo->gameType = 2;
- } else if ($data['dealinfo']['game_type'] == 'dice' || $data['dealinfo']['game_type'] == '3') {
- $this->dealinfo->gameType = 3;
- } else if ($data['dealinfo']['game_type'] == 'spin_wheel' || $data['dealinfo']['game_type'] == '4') {
- $this->dealinfo->gameType = 4;
- $this->dealinfo->winCount = $data['dealinfo']['wins'];
- $this->dealinfo->loseCount = $data['dealinfo']['loses'];
- } else if ($data['dealinfo']['game_type'] == 'rock_paper_scissor' || $data['dealinfo']['game_type'] == '5') {
- $this->dealinfo->gameType = 5;
- }
- }
- } elseif ($data['type'] == 'bus_reservation') {
- $this->module = 'ecommerce';
- $this->type = 'bus_reservation';
- $this->dealinfo = (object) $data['dealinfo'];
- } elseif ($data['type'] == 'food') {
- $this->module = 'ecommerce';
- $this->type = 'food';
- $this->dealinfo->menu = (object) $data['dealinfo'];
- } elseif ($data['type'] == 'book_spa') {
- $this->module = 'ecommerce';
- $this->type = 'book_spa';
- $this->dealinfo = (object) $data['dealinfo'];
- } elseif ($data['type'] == 'jobs') {
- $this->module = 'ecommerce';
- $this->type = 'jobs';
- $this->dealinfo = (object) $data['dealinfo'];
- } elseif ($data['type'] == 'resume') {
- $this->module = 'ecommerce';
- $this->type = 'resume';
- $this->dealinfo = (object) $data['dealinfo'];
- } elseif ($data['type'] == 'datapage') {
- $this->module = 'loyalty';
- $this->type = 'datapage';
- //$this->limits = array('max_limit_per_user' => null, 'max_global_limit' => null, 'max_limit_per_day' => null);
- $this->scenario = 'dataview';
- } elseif ($data['type'] == 'load') {
- $this->module = 'gift';
- $this->type = 'load';
- } elseif ($data['type'] == 'bonus') {
- $this->module = 'gift';
- $this->type = 'bonus';
- }
- //reward
- $rewardinfo = new stdClass();
- if ($data['rewardinfo']['type'] == "reward") {
- $this->rewardtype = "reward";
- $this->amount = $data['rewardinfo']['amount'];
- //$this->validatorList->add(CValidator::createValidator('required', $this, 'amount'));
- //$this->validatorList->add(CValidator::createValidator('numerical', $this, 'amount', array('integerOnly' => true, 'min' => 1)));
- $rewardinfo->type = $data['rewardinfo']['type'];
- $rewardinfo->amount = intval($data['rewardinfo']['amount']);
- $rewardinfo->wallet_id = intval($data['rewardinfo']['wallet_id']);
- $rewardinfo->auto_redeem = false;
- $rewardinfo->self_redeem = false;
- } elseif ($data['rewardinfo']['type'] == "deal") {
- $this->rewardtype = $data['rewardinfo']['type'];
- $this->deal_id = $data['rewardinfo']['deal_id'];
- $this->validatorList->add(CValidator::createValidator('validateDealId', $this, 'deal_id'));
- $rewardinfo->type = $data['rewardinfo']['type'];
- $rewardinfo->deal_id = $data['rewardinfo']['deal_id'];
- $rewardinfo->auto_redeem = ($data['rewardinfo']['auto_redeem']) ? true : false;
- $rewardinfo->self_redeem = ($data['rewardinfo']['self_redeem']) ? true : false;
- } elseif ($data['rewardinfo']['type'] == "rolechange") {
- $this->rewardtype = $data['rewardinfo']['type'];
- $this->role_id = $data['rewardinfo']['role_id'];
- $rewardinfo->type = $data['rewardinfo']['type'];
- $rewardinfo->role_id = intval($data['rewardinfo']['role_id']);
- $rewardinfo->auto_redeem = ($data['rewardinfo']['auto_redeem']) ? true : false;
- $rewardinfo->self_redeem = ($data['rewardinfo']['self_redeem']) ? true : false;
- } elseif ($data['rewardinfo']['type'] == "other") {
- $this->rewardtype = $data['rewardinfo']['type'];
- $this->other_reward = $data['rewardinfo']['other_reward'];
- $this->validatorList->add(CValidator::createValidator('required', $this, 'other_reward'));
- $rewardinfo->type = $data['rewardinfo']['type'];
- $rewardinfo->other_reward = $data['rewardinfo']['other_reward'];
- $rewardinfo->auto_redeem = ($data['rewardinfo']['auto_redeem']) ? true : false;
- $rewardinfo->self_redeem = ($data['rewardinfo']['self_redeem']) ? true : false;
- } elseif ($data['rewardinfo']['type'] == "coupon") {
- $rewardinfo->type = $data['rewardinfo']['type'];
- $rewardinfo->auto_redeem = ($data['rewardinfo']['auto_redeem']) ? true : false;
- $rewardinfo->self_redeem = ($data['rewardinfo']['self_redeem']) ? true : false;
- } elseif ($data['rewardinfo']['type'] == "promo") {
- $rewardinfo->type = $data['rewardinfo']['type'];
- $rewardinfo->auto_redeem = ($data['rewardinfo']['auto_redeem']) ? true : false;
- $rewardinfo->self_redeem = ($data['rewardinfo']['self_redeem']) ? true : false;
- } else {
- $rewardinfo->type = "none";
- $rewardinfo->auto_redeem = ($data['rewardinfo']['auto_redeem']) ? true : false;
- $rewardinfo->self_redeem = ($data['rewardinfo']['self_redeem']) ? true : false;
- }
- //start date
- if ($data['start_date']) {
- $this->start_date = $data['start_date'];
- } else {
- $this->start_date = date('Y-m-d');
- }
- //end date
- if ($data['end_date']) {
- $this->end_date = $data['end_date'];
- } else if ($data['days']) {
- $this->end_date = date('Y-m-d', strtotime($this->start_date . ' + ' . $data['days'] . ' days'));
- } else {
- $this->end_date = date('Y-m-d', strtotime($this->start_date . ' + 1825 days'));
- }
- if ($this->validate()) {
- if ($type == "community") {
- /* * * commented due to change in credit system
- if(Deals::countAllDealsOfACommunity($id)){
- // amount for posting a deal
- //If the community already has a deal, then this deal is a paid deal
- $dealcharge = $data['days'] * Yii::app()->params['dealPricePerDay'];
- $creditTransfers = new CreditTransfers('system');
- $creditTransfers->transfer_from_id = $id;
- $creditTransfers->transfer_from_type = 2;
- $creditTransfers->transfer_amount = $dealcharge;
- $creditTransfers->transfer_narration = "Payment for creating deal";
- if(!$creditTransfers->transferCredits()){
- throw new CHttpException(403, "payment_failed");
- }
- //comission to reseller
- $modelCommunity = Communities::model()->findByPk($id);
- $fee = floor($dealcharge * Yii::app()->params['resellerFeeForDeals']/100);
- if($modelCommunity && $modelCommunity->community_resellerid && $fee>=1){
- $modelCreditTransfers = new CreditTransfers('system');
- $modelCreditTransfers->transfer_to_id = $modelCommunity->community_resellerid;
- $modelCreditTransfers->transfer_to_type = 1;
- $modelCreditTransfers->transfer_amount = $fee;
- $modelCreditTransfers->transfer_narration = "comission to the reseller for deal";
- if(!$modelCreditTransfers->transferCredits()){
- throw new CHttpException(403, "payment_failed");
- }
- }
- }
- */
- } elseif ($type == "user") {
- /* * * commented due to change in credit system
- if(Deals::countAllDealsOfAUser($id)){
- //If the user already has a deal, then this deal is a paid deal
- $dealcharge = $data['days'] * Yii::app()->params['dealPricePerDay'];
- $creditTransfers = new CreditTransfers('system');
- $creditTransfers->transfer_from_id = $id;
- $creditTransfers->transfer_from_type = 1;
- $creditTransfers->transfer_amount = $dealcharge;
- $creditTransfers->transfer_narration = "Payment for creating deal";
- if(!$creditTransfers->transferCredits()){
- throw new CHttpException(403, "payment_failed");
- }
- }
- */
- }
- //cost per view
- if ($data['cost_per_view']) {
- $cost_per_view = new stdClass();
- $cost_per_view->amount = $data['cost_per_view']['amount'];
- $cost_per_view->type = 'wallet';
- $cost_per_view->wallet_id = $data['cost_per_view']['wallet_id'];
- //save spend_ad_limit in mongo
- //deduct ad_balance whenever cost_per_view is deducted.
- $data['cost_per_view']['limit_spend'] = $data['cost_per_view']['limit_spend'] > 0 ? $data['cost_per_view']['limit_spend'] : 0;
- $cost_per_view->ad_balance = $cost_per_view->limit_spend = $data['cost_per_view']['limit_spend'] > 0 ? $data['cost_per_view']['limit_spend'] : 0;
- if ($cost_per_view->limit_spend > 0) {
- //check for balance
- $bal_type = $this->owner->type == 'user' ? 1 : 2;
- $balance = WalletBalances::getWalletBalance($this->owner->id, $bal_type, $cost_per_view->wallet_id)['amount'];
- if ($balance < $cost_per_view->limit_spend)
- throw new CHttpException(404, 'insufficient_balance_to_spend');
- else {
- //deduct balance
- $transferAd = new WalletTransfers;
- $transferAd->settings = SiteSettings::getSettings();
- $transferAd->transfer_from_id = $this->owner->id;
- $transferAd->transfer_from_type = $bal_type;
- $transferAd->transfer_from_wallet_id = $data['cost_per_view']['wallet_id'];
- $transferAd->transfer_from_amount = $cost_per_view->limit_spend;
- $transferAd->transfer_to_id = 8;
- $transferAd->transfer_to_type = 3;
- $transferAd->transfer_to_wallet_id = $data['cost_per_view']['wallet_id'];
- $transferAd->transfer_narration = 'Payment for cost_per_view';
- if (!$transferAd->transferInternal()) {
- throw new CHttpException(403, 'fund_transfer_failed');
- }
- }
- }
- $this->cost_per_view = $cost_per_view;
- }
- //category
- if ($data['category_id'] > 0) {
- $category = new stdClass();
- $category_name = Categories::getCategoryName($data['category_id']);
- if ($category_name) {
- $category->id = $data['category_id'];
- $category->name = $category_name;
- }
- }
- $parsedData->category = $category;
- $parsedData->owner = $this->owner;
- $parsedData->roles = $this->roles;
- $parsedData->credit_type = $this->credit_type;
- $parsedData->cost_per_view = $this->cost_per_view;
- $parsedData->view_range_km = $this->view_range_km;
- if ($this->probability)
- $parsedData->probability = $this->probability;
- if ($this->level)
- $parsedData->level = $this->level;
- if ($this->total_available)
- $parsedData->total_available = $this->total_available;
- if ($this->group)
- $parsedData->group = $this->group;
- /* if ($this->created_via)
- $parsedData->created_via = $this->created_via; */
- $parsedData->share_for_reward = $this->share_for_reward;
- $parsedData->affiliate_fee = $fee;
- $parsedData->pay_per_take = $ppt;
- $parsedData->pay_per_click = $ppc;
- $parsedData->price = $this->price;
- $parsedData->tracker = uniqid() . rand(10 * 45, 100 * 98);
- //Common::pre($parsedData, true);
- $limits = new stdClass();
- $limits->max_limit_per_user = ($data['limits']['max_limit_per_user']) ? intval($data['limits']['max_limit_per_user']) : NULL;
- $limits->max_global_limit = ($data['limits']['max_global_limit']) ? intval($data['limits']['max_global_limit']) : NULL;
- $limits->max_limit_per_day = ($data['limits']['max_limit_per_day']) ? intval($data['limits']['max_limit_per_day']) : NULL;
- $parsedData->title = $data['title'];
- $parsedData->description = $data['description'];
- if ($data['food_type']) {
- $parsedData->food_type = $data['food_type'];
- }
- $parsedData->start_date = $this->start_date;
- $parsedData->end_date = $this->end_date;
- if ($data['country']) {
- $countryModel = Countries::model()->findByPk($data['country']);
- $country = new stdClass();
- $country->id = intval($countryModel->id);
- $country->name = $countryModel->country_name;
- }
- $parsedData->module = $this->module;
- $parsedData->country = $country;
- $parsedData->location = $this->location;
- $parsedData->city = $data['city'];
- $parsedData->auto = $data['auto'];
- $parsedData->visibility = $this->visibility;
- $parsedData->tags = (is_array($data['tags'])) ? $data['tags'] : array();
- $parsedData->rewardinfo = $rewardinfo;
- $parsedData->limits = $limits;
- $parsedData->url = $data['url'];
- $parsedData->type = $this->type;
- if ($this->dealinfo) {
- $parsedData->dealinfo = $this->dealinfo;
- }
- if ($this->guestListColors) {
- $parsedData->guestListColors = $this->guestListColors;
- }
- if ($this->guestlist) {
- $parsedData->guestlist = $this->guestlist;
- }
- if ($this->methodofpayment) {
- $parsedData->methodofpayment = $this->methodofpayment;
- }
- $parsedData->game_slots = $game_slots;
- if ($catalogs)
- $parsedData->items = $catalogs;
- $parsedData->status = 1;
- $collection = Yii::app()->edmsMongoCollection('deals');
- $collection->insert($parsedData);
- $dealId = (string) $parsedData->_id;
- if ($dealId && $data['image'])
- $this->avatarUpload($dealId, $data['image']);
- return $dealId;
- }
- else {
- return false;
- }
- }
- // end of createDeal
- //update deal
- public function editDeal($dealId, $data, $ownerId = null, $type = null) {
- if (!TagMongo::isValidId($dealId)) {
- throw new CHttpException(404, invalid_deal_id);
- }
- $collection = Yii::app()->edmsMongoCollection('deals');
- $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
- $update = new stdClass;
- $deal = $collection->findOne(array(
- "_id" => new MongoID($dealId),
- "owner.id" => intval($this->communityId),
- "owner.type" => "community"
- ));
- if (!$deal) {
- throw new CHttpException(404, 'invalid_deal');
- }
- //check permissions
- if (!$this->isPermission('edit', $deal)) {
- return false;
- }
- if ($data['roles']) {
- if ($data['roles']['take']) {
- $take = array();
- for ($i = 0; $i < count($data['roles']['take']); $i++) {
- //For converting the elements to integer
- $take[$i] = intval($data['roles']['take'][$i]);
- }
- } else
- $take = $deal['roles']['take'];
- if ($data['roles']['assign']) {
- $assign = array();
- for ($i = 0; $i < count($data['roles']['assign']); $i++) {
- //For converting the elements to integer
- $assign[$i] = intval($data['roles']['assign'][$i]);
- }
- } else
- $assign = $deal['roles']['assign'];
- if ($data['roles']['redeem']) {
- $redeem = array();
- for ($i = 0; $i < count($data['roles']['redeem']); $i++) {
- //For converting the elements to integer
- $redeem[$i] = intval($data['roles']['redeem'][$i]);
- }
- } else
- $redeem = $deal['roles']['redeem'];
- if ($data['roles']['view']) {
- $view = array();
- for ($i = 0; $i < count($data['roles']['view']); $i++) {
- //For converting the elements to integer
- $view[$i] = intval($data['roles']['view'][$i]);
- }
- } else
- $view = $deal['roles']['view'];
- $update->roles['take'] = $take;
- $update->roles['assign'] = $assign;
- $update->roles['redeem'] = $redeem;
- $update->roles['view'] = $view;
- }
- if (isset($data['title'])) {
- $update->title = $data['title'];
- }
- if ($data['visibility']) {
- $update->visibility = $data['visibility'];
- }
- if (isset($data['description'])) {
- $update->description = $data['description'];
- }
- if ($data['food_type']) {
- $update->description = $data['food_type'];
- }
- if ($data['location']) {
- $location = array(floatval($data['location'][0]), floatval($data['location'][1]));
- if (sizeof($location) != 2) {
- $this->addError($attribute, 'Invalid location format(long,lat)');
- } else if ((floatval($data['location'][0]) == 0) || ((floatval($data['location'][1]) == 0))) {
- $location = null;
- }
- $update->location = $location;
- }
- if ($data['group']) {
- $update->group = $data['group'];
- }
- if ($data['view_range_km']) {
- $update->view_range_km = $data['view_range_km'];
- }
- if ($data['probability']) {
- $update->probability = $data['probability'];
- }
- if ($data['level']) {
- $update->level = $data['level'];
- }
- if ($data['total_available']) {
- $update->total_available = $data['total_available'];
- }
- if ($data['country']) {
- $countryModel = Countries::model()->findByPk($data['country']);
- $country = new stdClass();
- $country->id = intval($countryModel->id);
- $country->name = $countryModel->country_name;
- $update->country = $country;
- }
- //game slots - include in slot game rewards
- if (isset($data['game_slots'])) {
- $gameslot = $data['game_slots'];
- $game_slots = new stdClass;
- if ($gameslot['status'] == 1)
- $game_slots->status = intval(1);
- else
- $game_slots->status = intval(0);
- if ($gameslot['limit'] > 0)
- $game_slots->limit = intval($gameslot['limit']);
- else
- $game_slots->limit = intval(0);
- $update->game_slots = $game_slots;
- }
- if ($data['dealinfo']) {
- if ($deal['type'] == 'stamp') {
- $dealinfo = array(
- //dealinfo array
- 'take_action' => $takeAction,
- 'total_stamps' => intval($data['dealinfo']['total_stamps']),
- 'limit_per_day' => intval($data['dealinfo']['limit_per_day']));
- $update->dealinfo = $dealinfo;
- }
- if ($deal['type'] == 'promo') {
- $update->dealinfo = $data['dealinfo'];
- }
- if ($data['dealinfo']) {
- if ($deal['type'] == 'food') {
- $food = new stdClass;
- $food->menu = $data['dealinfo'];
- $update->dealinfo = $food;
- }
- if ($deal['type'] == 'book_spa') {
- $update->dealinfo = $data['dealinfo'];
- }
- }
- }
- if ($data['rewardinfo']) {
- //reward
- $rewardinfo = new stdClass();
- if ($data['rewardinfo']['type'] == "reward") {
- $this->rewardtype = "reward";
- $this->amount = $data['rewardinfo']['amount'];
- $this->validatorList->add(CValidator::createValidator('required', $this, 'amount'));
- $this->validatorList->add(CValidator::createValidator('numerical', $this, 'amount', array('integerOnly' => true, 'min' => 1)));
- $rewardinfo->type = $data['rewardinfo']['type'];
- $rewardinfo->amount = intval($data['rewardinfo']['amount']);
- $rewardinfo->wallet_id = intval($data['rewardinfo']['wallet_id']);
- $rewardinfo->auto_redeem = false;
- $rewardinfo->self_redeem = false;
- } elseif ($data['rewardinfo']['type'] == "deal") {
- $this->rewardtype = $data['rewardinfo']['type'];
- $this->deal_id = $data['rewardinfo']['deal_id'];
- $this->validatorList->add(CValidator::createValidator('validateDealId', $this, 'deal_id'));
- $rewardinfo->type = $data['rewardinfo']['type'];
- $rewardinfo->deal_id = $data['rewardinfo']['deal_id'];
- $rewardinfo->auto_redeem = ($data['rewardinfo']['auto_redeem']) ? true : false;
- $rewardinfo->self_redeem = ($data['rewardinfo']['self_redeem']) ? true : false;
- } elseif ($data['rewardinfo']['type'] == "rolechange") {
- $this->rewardtype = $data['rewardinfo']['type'];
- $this->role_id = $data['rewardinfo']['role_id'];
- $rewardinfo->type = $data['rewardinfo']['type'];
- $rewardinfo->role_id = intval($data['rewardinfo']['role_id']);
- $rewardinfo->auto_redeem = ($data['rewardinfo']['auto_redeem']) ? true : false;
- $rewardinfo->self_redeem = ($data['rewardinfo']['self_redeem']) ? true : false;
- } elseif ($data['rewardinfo']['type'] == "other") {
- $this->rewardtype = $data['rewardinfo']['type'];
- $this->other_reward = $data['rewardinfo']['other_reward'];
- $this->validatorList->add(CValidator::createValidator('required', $this, 'other_reward'));
- $rewardinfo->type = $data['rewardinfo']['type'];
- $rewardinfo->other_reward = $data['rewardinfo']['other_reward'];
- $rewardinfo->auto_redeem = ($data['rewardinfo']['auto_redeem']) ? true : false;
- $rewardinfo->self_redeem = ($data['rewardinfo']['self_redeem']) ? true : false;
- } else {
- $rewardinfo->type = "none";
- $rewardinfo->auto_redeem = ($data['rewardinfo']['auto_redeem']) ? true : false;
- $rewardinfo->self_redeem = ($data['rewardinfo']['self_redeem']) ? true : false;
- }
- $update->rewardinfo = $rewardinfo;
- }
- if ($data['limits']) {
- $limit = array(
- //limits array
- 'max_global_limit' => intval($data['limits']['max_global_limit']),
- 'max_limit_per_day' => intval($data['limits']["max_limit_per_day"]),
- 'max_limit_per_user' => intval($data['limits']['max_limit_per_user']));
- $update->limits = $limit;
- }
- if ($data['share_for_reward']) {
- $share_for_reward = array();
- if ($data['share_for_reward']['amount']) {
- $share_for_reward['amount'] = intval($data['share_for_reward']['amount']);
- } else {
- $share_for_reward['amount'] = intval($deal['share_for_reward']['amount']);
- }
- if ($data['share_for_reward']['type']) {
- $share_for_reward['type'] = $data['share_for_reward']['type'];
- } else {
- $share_for_reward['type'] = $deal['share_for_reward']['type'];
- }
- $update->share_for_reward = $share_for_reward;
- }
- if ($data['cost_per_view']) {
- $cost_per_view = new stdClass();
- $cost_per_view->amount = $data['cost_per_view']['amount'];
- $cost_per_view->type = 'wallet';
- $cost_per_view->wallet_id = $data['cost_per_view']['wallet_id'];
- if (!$deal['cost_per_view']['limit_spend'] || $deal['cost_per_view']['limit_spend'] <= 0) {
- $cost_per_view->limit_spend = $data['cost_per_view']['limit_spend'];
- } else {
- $cost_per_view->limit_spend = $deal['cost_per_view']['limit_spend'];
- }
- $cost_per_view->ad_balance = $deal['cost_per_view']['ad_balance'] > 0 ? $deal['cost_per_view']['ad_balance'] : 0;
- //update spend_ad_limit in mongo
- //now the ad spend cannot be updated
- //$cost_per_view->limit_spend = $data['cost_per_view']['limit_spend'];
- //$cost_per_view->ad_balance = $deal->cost_per_view['ad_balance'] + $cost_per_view->limit_spend;
- $update->cost_per_view = $cost_per_view;
- }
- //category
- if ($data['category_id'] > 0) {
- $category = new stdClass();
- $category_name = Categories::getCategoryName($data['category_id']);
- if ($category_name) {
- $category->id = $data['category_id'];
- $category->name = $category_name;
- $update->category = $category;
- }
- }
- if (isset($data['catalog_items']) && Common::isJson($data['catalog_items'])) {
- $catalog_items = json_decode($data['catalog_items'], true);
- $details = array();
- $i = 0;
- foreach ($catalog_items as $item) {
- //get complete list of items and store inside items details
- $details[$i]['id'] = intval($item);
- $query = Yii::app()->db->createCommand()
- ->select('c.id,c.category_id,cc.category_name,c.catalog_name,c.description,c.price,c.price_wallet,c.weight,c.sizes,c.colors,c.other,wt.currency_code,c.hashtags,c.time_to_ship,c.stock')
- ->from('catalog c')
- ->leftJoin("catalog_category cc", "cc.id = c.category_id")
- ->leftJoin("wallet_types wt", "wt.id = c.price_wallet")
- ->where('c.id = ' . $item . ' AND c.community_id = ' . $this->communityId);
- $result = $query->queryAll();
- if (!$result)
- continue;
- $result = $result[0];
- $details[$i]['catalog_name'] = $result['catalog_name'];
- $details[$i]['category'] = $result['category_name'] ? array('id' => $result['category_id'], 'name' => $result['category_name']) : array();
- $details[$i]['description'] = $result['description'];
- $details[$i]['price'] = array('amount' => $result['price'], 'wallet_id' => $result['price_wallet'], 'wallet_name' => $result['currency_code']);
- $details[$i]['weight'] = $result['weight'];
- $size = array();
- $color = array();
- if ($result['sizes']) {
- $size = explode(',', $result['sizes']);
- }
- if ($result['colors']) {
- $color = explode(',', $result['colors']);
- }
- if ($result['other']) {
- $other = explode(',', $result['other']);
- }
- $details[$i]['sizes'] = $size;
- $details[$i]['colors'] = $color;
- $details[$i]['other'] = $other;
- $details[$i]['hashtags'] = $result['hashtags'] ? explode(',', $result['hashtags']) : array();
- $details[$i]['stock'] = intval($result['stock']);
- $details[$i]['time_to_ship'] = $result['time_to_ship'];
- $i++;
- }
- $update->items = $details;
- }
- //delivery option
- if (isset($data['delivery_options']) && is_array($data['delivery_options'])) {
- if ($data['delivery_options']['type'] == 'xend')
- $update->delivery_options = $data['delivery_options'];
- else if ($data['delivery_options']['amount'] > 0 && $data['delivery_options']['wallet_id'] > 0) {
- $update->delivery_options = $data['delivery_options'];
- } else
- $update->delivery_options = array();
- }
- if (isset($data['url'])) {
- $update->url = $data['url'];
- }
- if(isset($data['status'])){
- $update->status = $data['status'];
- }
- $stat = $collection->update(array(
- "_id" => new MongoID($dealId),
- "owner.id" => intval($this->communityId),
- "owner.type" => "community"
- ), array('$set' => $update));
- $statLive = $liveCollection->update(array(
- "deal_id" => new MongoID($dealId),
- "owner.id" => intval($this->communityId),
- "owner.type" => "community"
- ), array('$set' => $update));
- if ($stat && $statLive)
- return true;
- else
- return false;
- }
- public static function extendDeal($dealId, $days = NULL, $id, $type, $date = NULL) {
- if (!TagMongo::isValidId($dealId)) {
- throw new CHttpException(404, invalid_deal_id);
- }
- $collection = Yii::app()->edmsMongoCollection('deals');
- $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
- $deal = $collection->findOne(array(
- "_id" => new MongoID($dealId)
- ));
- if (!$deal) {
- throw new CHttpException(404, 'invalid_deal');
- }
- if ($days > 0) {
- $endDate = $deal['end_date'];
- $newEndDate = date('Y-m-d', strtotime($endDate . ' + ' . $days . ' days'));
- } else if ($date) {
- $newEndDate = $date;
- } else {
- throw new CHttpException(403, "invalid_extend_period");
- }
- if ($type == "community") {
- $collection->update(array(
- "_id" => new MongoID($dealId),
- "owner.id" => intval($id),
- "owner.type" => "community"
- ), array('$set' => array("end_date" => $newEndDate, 'status' => 1)));
- $liveCollection->update(array(
- "deal_id" => new MongoID($dealId),
- "owner.id" => intval($id),
- "owner.type" => "community"
- ), array('$set' => array("end_date" => $newEndDate, 'status' => 1)));
- return true;
- //to be checked : credit transfers section.
- /* if(Deals::countAllDealsOfACommunity($id) > 1){
- //If the community already has a deal, then this deal is a paid deal
- $dealcharge = $days * Yii::app()->params['dealPricePerDay'];
- $creditTransfers = new CreditTransfers('system');
- $creditTransfers->transfer_from_id = $id;
- $creditTransfers->transfer_from_type = 2;
- $creditTransfers->transfer_amount = $dealcharge;
- $creditTransfers->transfer_narration = "Payment for extending deal : #".$dealId;
- if($creditTransfers->transferCredits()){
- $collection->update(array(
- "_id" => new MongoID($dealId),
- "owner.id" => intval($id),
- "owner.type" => "community"
- ), array('$set' => array("end_date" => $newEndDate, 'status'=>1)));
- $liveCollection->update(array(
- "deal_id" => new MongoID($dealId),
- "owner.id" => intval($id),
- "owner.type" => "community"
- ), array('$set' => array("end_date" => $newEndDate, 'status'=>1)));
- return true;
- }
- else{
- return false;
- }
- // comission to reseller
- $modelCommunity = Communities::model()->findByPk($id);
- $fee = floor($dealcharge * Yii::app()->params['resellerFeeForDeals']/100);
- if($modelCommunity && $modelCommunity->community_resellerid && $fee>=1){
- $modelCreditTransfers = new CreditTransfers('system');
- $modelCreditTransfers->transfer_to_id = $modelCommunity->community_resellerid;
- $modelCreditTransfers->transfer_to_type = 1;
- $modelCreditTransfers->transfer_amount = $fee;
- $modelCreditTransfers->transfer_narration = "comission to the reseller for deal";
- if(!$modelCreditTransfers->transferCredits()){
- throw new CHttpException(403, "payment_failed");
- }
- }
- }
- else{
- $collection->update(array(
- "_id" => new MongoID($dealId),
- "owner.id" => intval($id),
- "owner.type" => "community"
- ), array('$set' => array("end_date" => $newEndDate, 'status'=>1)));
- $liveCollection->update(array(
- "deal_id" => new MongoID($dealId),
- "owner.id" => intval($id),
- "owner.type" => "community"
- ), array('$set' => array("end_date" => $newEndDate, 'status'=>1)));
- } */
- } elseif ($type == "user") { //disabled for the time being
- if (Deals::countAllDealsOfAUser($id) > 1) {
- //If the user already has a deal, then this deal is a paid deal
- $dealcharge = $days * Yii::app()->params['dealPricePerDay'];
- $creditTransfers = new CreditTransfers('system');
- $creditTransfers->transfer_from_id = $id;
- $creditTransfers->transfer_from_type = 1;
- $creditTransfers->transfer_amount = $dealcharge;
- $creditTransfers->transfer_narration = "Payment for extending deal : #" . $dealId;
- if ($creditTransfers->transferCredits()) {
- $collection->update(array(
- "_id" => new MongoID($dealId),
- "owner.id" => intval($id),
- "owner.type" => "user"
- ), array('$set' => array("end_date" => $newEndDate, 'status' => 1)));
- $liveCollection->update(array(
- "deal_id" => new MongoID($dealId),
- "owner.id" => intval($id),
- "owner.type" => "user"
- ), array('$set' => array("end_date" => $newEndDate, 'status' => 1)));
- return true;
- } else {
- return false;
- }
- } else {
- $collection->update(array(
- "_id" => new MongoID($dealId),
- "owner.id" => intval($id),
- "owner.type" => "user"
- ), array('$set' => array("end_date" => $newEndDate, 'status' => 1)));
- $liveCollection->update(array(
- "deal_id" => new MongoID($dealId),
- "owner.id" => intval($id),
- "owner.type" => "user"
- ), array('$set' => array("end_date" => $newEndDate, 'status' => 1)));
- return true;
- }
- }
- }
- // end of extendDeal
- /*
- * * end of Create and Extend
- */
- /*
- * * deals - remove, expired and history
- */
- public function removeDeal() {
- //dealId, $userId, (if community perspective) $communityId, $role
- if ($this->communityId) {
- $collection = Yii::app()->edmsMongoCollection('deals');
- $deal = $collection->findOne(array(
- "_id" => new MongoID($this->dealId),
- "owner.id" => intval($this->communityId),
- "status" => array('$ne' => 1)
- ));
- if ($deal) {
- $collection->update(
- array("_id" => new MongoID($this->dealId)), array('$set' => array("status" => 2,
- "end_date" => ''))
- );
- return true;
- }
- } else {
- $collection = Yii::app()->edmsMongoCollection('deals_live');
- $deal = $collection->findOne(array(
- "deal_id" => new MongoID($this->dealId),
- "user_id" => intval($this->userId)
- ));
- if ($deal) {
- $this->updatePromised($deal, true);
- $this->moveLiveDealToHistory($deal);
- return true;
- }
- }
- return false;
- }
- public function moveLiveDealToHistory($deal, $redeem = null) {
- $historyDeal = new stdClass();
- $historyDeal->deal_id = $deal['deal_id'];
- //$historyDeal->deal_id = new MongoID($dealId);
- $historyDeal->taken_date = date("Y-m-d H:i:s", $deal['_id']->getTimestamp());
- $historyDeal->type = $deal['type'];
- $historyDeal->owner = $deal['owner'];
- $historyDeal->title = $deal['title'];
- $historyDeal->description = $deal['description'];
- $historyDeal->start_date = $deal['start_date'];
- $historyDeal->end_date = $deal['end_date'];
- $historyDeal->price = $deal['price'];
- $historyDeal->city = $deal['city'];
- $historyDeal->country = $deal['country'];
- $historyDeal->visibility = $deal['visibility'];
- $historyDeal->tags = $deal['tags'];
- $historyDeal->dealinfo = $deal['dealinfo'];
- $historyDeal->roles = $deal['roles'];
- $historyDeal->rewardinfo = $deal['rewardinfo'];
- $historyDeal->limits = $deal['limits'];
- $historyDeal->status = 3;
- $historyDeal->user_id = $deal['user_id'];
- $historyDeal->assigner_id = $deal['assigner_id'];
- $historyDeal->redeemer_id = intval($this->userId);
- $historyDeal->userinfo = $deal['userinfo'];
- $historyDeal->pay_per_take = $deal['pay_per_take'];
- $historyDeal->pay_per_click = $deal['pay_per_click'];
- if ($redeem == true) {
- $historyDeal->date_redeemed = date('Y-m-d');
- $redeemer_info = array();
- $redeemer_info['user_id'] = intval($this->userId);
- $user = Users::model()->findByPk($this->userId);
- $redeemer_info['user_firstname'] = $user->user_firstname;
- $redeemer_info['user_lastname'] = $user->user_lastname;
- $historyDeal->redeemer_info = $redeemer_info;
- }
- //Insert into the history collection
- $historyCollection = Yii::app()->edmsMongoCollection('deals_history');
- $historyCollection->insert($historyDeal);
- //Remove document from the live deals collection
- $collection = Yii::app()->edmsMongoCollection('deals_live');
- $collection->remove(array(
- "_id" => $deal['_id']
- ));
- }
- public function moveDealToHistory($deal) {
- $historyDeal = (object) $deal;
- //Insert into the history collection
- $historyCollection = Yii::app()->edmsMongoCollection('deals_history');
- $historyCollection->insert($historyDeal);
- //Remove document from the live deals collection
- $collection = Yii::app()->edmsMongoCollection('deals');
- $collection->remove(array(
- "_id" => $deal['_id']
- ));
- }
- public static function getHistoryDeals($userId, $communityId = NULL) {
- $collection = Yii::app()->edmsMongoCollection('deals_history');
- if ($communityId) {
- $deals = $collection->find(array(
- "user_id" => intval($userId),
- "owner.id" => intval($communityId),
- "owner.type" => "community"
- ));
- } else {
- $deals = $collection->find(array("user_id" => intval($userId)));
- }
- $parsedDeals = array();
- if ($deals) {
- foreach ($deals as $deal) {
- $object = new stdClass;
- $object->id = $deal['_id']->__toString();
- $object->deal_id = $deal['deal_id']->__toString();
- $object->taken_date = $deal['taken_date'];
- $object->redeem_date = date("Y-m-d H:i:s", $deal['_id']->getTimestamp());
- $object->title = $deal['title'];
- $object->type = $deal['type'];
- $object->dealinfo = $deal['dealinfo'];
- $object->userinfo = $deal['userinfo'];
- $object->owner = self::formatOwner($deal['owner']);
- $object->status = self::formatStatus($deal['status']);
- $parsedDeals[] = $object;
- }
- }
- return $parsedDeals;
- }
- public static function getHistoryDealsOfACommunity($communityId, $params = array()) {
- // pagination
- if (isset($params['pageOffset']) && !is_numeric($params['pageOffset'])) {
- $params['pageOffset'] = 0;
- }
- if (isset($params['pageCount']) && !is_numeric($params['pageCount'])) {
- $params['pageCount'] = 100;
- }
- $collection = Yii::app()->edmsMongoCollection('deals_history');
- $deals = $collection->find(array(
- "owner.id" => intval($communityId),
- "owner.type" => "community"
- ))->skip($params['pageOffset'])
- ->limit($params['pageCount']);
- $parsedDeals = array();
- if ($deals) {
- foreach ($deals as $deal) {
- $object = new stdClass;
- $object->id = $deal['_id']->__toString();
- $object->deal_id = $deal['deal_id']->__toString();
- $object->taken_date = $deal['taken_date'];
- $object->redeem_date = date("Y-m-d H:i:s", $deal['_id']->getTimestamp());
- $object->title = $deal['title'];
- $object->type = $deal['type'];
- $object->dealinfo = $deal['dealinfo'];
- $object->userinfo = $deal['userinfo'];
- $object->status = self::formatStatus($deal['status']);
- $parsedDeals[] = $object;
- }
- }
- return $parsedDeals;
- }
- public static function getDealsHistoryOfATemplate($dealId, $userId = NULL) {
- $query['deal_id'] = new MongoID($dealId);
- if ($userId) {
- //Get the history of a specific user if the user id is supplied
- $query['user_id'] = intval($userId);
- }
- $collection = Yii::app()->edmsMongoCollection('deals_history');
- $deals = $collection->find($query);
- $parsedDeals = array();
- if ($deals) {
- foreach ($deals as $deal) {
- $object = new stdClass;
- $object->id = $deal['_id']->__toString();
- $object->deal_id = $deal['deal_id']->__toString();
- $object->taken_date = $deal['taken_date'];
- $object->redeem_date = date("Y-m-d H:i:s", $deal['_id']->getTimestamp());
- $object->title = $deal['title'];
- $object->type = $deal['type'];
- $object->dealinfo = $deal['dealinfo'];
- $object->userinfo = $deal['userinfo'];
- $object->status = self::formatStatus($deal['status']);
- $parsedDeals[] = $object;
- }
- }
- return $parsedDeals;
- }
- /*
- * * deals - enof of remove, expired and history
- */
- /*
- * * deals - take and assign
- */
- public function assignDeal($dealId, $assigneeId) {
- if (!TagMongo::isValidId($dealId)) {
- throw new CHttpException(404, "invalid_deal_id");
- }
- $userId = $this->userId;
- $collection = Yii::app()->edmsMongoCollection('deals');
- $deal = (object) $collection->findOne(array("_id" => new MongoID($dealId)));
- //check deal validity
- if (!$deal) {
- throw new CHttpException(404, "invalid_deal");
- } else if ($deal->status != 1) {
- throw new CHttpException(403, "deal_unavailable");
- }
- $checkMember = CommunityUsers::model()->findByAttributes(array("user_id" => $assigneeId, "community_id" => $deal->owner['id']));
- //if not member; automatically adds
- if (!$checkMember) {
- $role = CommunityRoles::model()->findByAttributes(array('community_id' => $deal->owner['id'], 'role_default' => '1'));
- $roleId = $role->id;
- $modelUsers = new CommunityUsers;
- $modelUsers->user_id = $assigneeId;
- $modelUsers->community_id = $deal->owner['id'];
- $modelUsers->role_id = $roleId;
- $modelUsers->communityuser_status = 1;
- $modelUsers->communityuser_relation = 1;
- $modelUsers->save();
- }
- //check deal taken
- if (self::checkIfUserHasTakenDealBefore($assigneeId, $dealId)) {
- //If the user has taken the deal before. He should not be able to take it again
- throw new CHttpException(403, "already_taken");
- }
- //check permissions
- if (!$this->isPermission('assign', $deal)) {
- return false;
- }
- $liveDeal = new stdClass();
- $liveDeal->deal_id = new MongoID($dealId);
- $liveDeal->type = $deal->type;
- $liveDeal->owner = $deal->owner;
- $liveDeal->title = $deal->title;
- $liveDeal->description = $deal->description;
- $liveDeal->hiddenDescription = $deal->hiddenDescription;
- $liveDeal->start_date = $deal->start_date;
- $liveDeal->end_date = $deal->end_date;
- $liveDeal->city = $deal->city;
- $liveDeal->town = $deal->town;
- $liveDeal->zipCode = $deal->zipCode;
- $liveDeal->date_taken = date('Y-m-d');
- $liveDeal->date_redeemed = "";
- $liveDeal->auto = $deal->auto;
- $liveDeal->country = $deal->country;
- $liveDeal->visibility = $deal->visibility;
- $liveDeal->tags = $deal->tags;
- $liveDeal->dealinfo = $deal->dealinfo;
- $liveDeal->roles = $deal->roles;
- $liveDeal->limits = $deal->limits;
- $liveDeal->total_value = $deal->total_value;
- $liveDeal->credit_type = $deal->credit_type;
- if ($deal->methodOfPayment) {
- $liveDeal->methodOfPayment = $deal->methodOfPayment;
- }
- if ($deal->digitalDelivery) {
- $liveDeal->digitalDelivery = $deal->digitalDelivery;
- }
- if ($deal->pickUpAddress) {
- $liveDeal->pickUpAddress = $deal->pickUpAddress;
- }
- if ($deal->price) {
- $liveDeal->price = $deal->price;
- }
- if ($deal->affiliate_fee) {
- $liveDeal->affiliate_fee = $deal->affiliate_fee;
- }
- if ($deal->rewardinfo) {
- $liveDeal->rewardinfo = $deal->rewardinfo;
- }
- if ($deal->pay_per_take)
- $liveDeal->pay_per_take = $deal->pay_per_take;
- if ($deal->pay_per_click)
- $liveDeal->pay_per_click = $deal->pay_per_click;
- if ($deal->collection)
- $liveDeal->collection = $deal->collection;
- $liveDeal->module = $deal->module;
- if ($deal->module == "ecommerce") {
- $liveDeal->status = 9;
- } else {
- $liveDeal->status = 8;
- }
- $liveDeal->user_id = intval($assigneeId);
- $liveDeal->assigner_id = intval($userId);
- $user = Users::model()->findByPk($assigneeId);
- if (!$user) {
- throw new CHttpException(403, "user_doesnt_exist");
- }
- if ($deal->type == "stamp") {
- $userinfo = new stdClass;
- $userinfo->id = intval($user->id);
- $userinfo->user_firstname = $user->user_firstname;
- $userinfo->user_lastname = $user->user_lastname;
- $liveDeal->stamp_log = array();
- $liveDeal->stamp_notes = array();
- } else {
- $userinfo = new stdClass;
- $userinfo->id = intval($user->id);
- $userinfo->user_firstname = $user->user_firstname;
- $userinfo->user_lastname = $user->user_lastname;
- }
- //ticket
- if ($deal->type == "ticket" && $deal->module == "ecommerce") {
- $purchasedTickets = array('history' => array(), 'tickets' => array());
- $liveDeal->purchasedTickets = $purchasedTickets;
- } elseif ($deal->type == "promo") {
- //Need to update the template also
- //Find an available coupon from the deal
- $parsedPromocodes = array();
- if ($deal->dealinfo['promo_codes']) {
- foreach ($deal->dealinfo['promo_codes'] as $promoCode) {
- if ($promoCode['status'] == 0) {
- //If an available promo code is found
- $availableCode = $promoCode['code'];
- $promoCode['status'] = 1;
- $promoCode['userId'] = intval($user->id);
- $parsedPromocodes[] = $promoCode;
- } else {
- $parsedPromocodes[] = $promoCode;
- }
- }
- }
- $total_available = intval($deal->total_available);
- $total_available--;
- $update['total_available'] = intval($total_available);
- $update['dealinfo.promo_codes'] = $parsedPromocodes;
- $stat = $collection->update(array('_id' => new MongoID($dealId)), array('$set' => $update));
- if ($stat['ok'])
- $liveDeal->dealinfo['promo_codes'] = $availableCode;
- }elseif ($deal->type == "coupon") {
- $total_available = intval($deal->total_available);
- $total_available--;
- $update['total_available'] = intval($total_available);
- $collection->update(array('_id' => new MongoID($dealId)), array('$set' => $update));
- }
- $liveDeal->userinfo = $userinfo;
- $liveDeal->orderedDate = date("Y-m-d H:i:s");
- $liveDeal->paid = "yes";
- $liveDeal->paidUsing = $deal->price['type'];
- $liveDeal->orderItemCount = 1;
- //update promised credits
- if (!$this->updatePromised($liveDeal)) {
- return false;
- }
- $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
- $liveCollection->insert($liveDeal);
- return true;
- }
- // end of assignDeal
- //Deal assign to all
- public function assignDealToAll($dealId, $assignees = NULL) {
- if (!TagMongo::isValidId($dealId)) {
- throw new CHttpException(404, "invalid_deal_id");
- }
- $collection = Yii::app()->edmsMongoCollection('deals');
- $deal = $collection->findOne(array("_id" => new MongoID($dealId)));
- //check deal validity
- if (!$deal) {
- throw new CHttpException(404, "invalid_deal");
- } else if ($deal['status'] != 1) {
- throw new CHttpException(403, "deal_unavailable");
- }
- if (count($assignees) == 0) {
- $query = Yii::app()->db->createCommand()
- ->select('user_id')
- ->from('community_users com_usr')
- ->leftJoin("community_roles comm_roles", "com_usr.role_id = comm_roles.id")
- ->where('com_usr.community_id = :comId AND com_usr.communityuser_status = 1', array(':comId' => $this->communityId))
- ->andWhere("com_usr.communityuser_status = 1
- AND comm_roles.role_type = :roleType", array(':roleType' => 3));
- //->queryScalar(array(':comId'=>$this->communityId));
- $members = $query->queryAll();
- } else {
- foreach ($assignees as $assignee) {
- $members[]['user_id'] = $assignee;
- }
- }
- foreach ($members as $member) {
- $assigneeUserId = $member['user_id'];
- if ($assigneeUserId) {
- $user = Users::model()->findByPk($assigneeUserId);
- if ($user) {
- $userId = $assigneeUserId;
- } else {
- $status_message['invalid_user'][] = $assigneeUserId;
- continue;
- }
- }
- //check whether user can take deal.
- if (!Deals::checkIfUserCanTakeDeal($deal, $userId, $affiliateId)) {
- $status_message['user_cannot_take_deal'][] = $assigneeUserId;
- continue;
- }
- //check already taken and exists
- if (self::checkIfUserHasTakenDealBefore($userId, $dealId)) {
- //If the user has taken the deal before. He should not be able to take it again
- $status_message['already_taken'][] = $assigneeUserId;
- continue;
- }
- //permissions
- if ($deal['owner']['type'] == "community") {
- if (!CommunityUsers::isMemberOf($userId, $deal['owner']['id'])) {
- $status_message['permission_denied'][] = $assigneeUserId;
- continue;
- }
- $roleId = CommunityUsers::getRoleOfUser($userId, $deal['owner']['id'])->role_id;
- if ($deal['roles']['take']) {
- if (!in_array($roleId, $deal['roles']['take'])) {
- $status_message['permission_denied'][] = $assigneeUserId;
- continue;
- }
- } else {
- $status_message['permission_denied'][] = $assigneeUserId;
- continue;
- }
- } else {
- //future
- if (!Contacts::checkIfAlreadyAContact($userId, $deal['owner']['id'])) {
- $status_message['permission_denied'][] = $assigneeUserId;
- continue;
- }
- }
- //price
- if ($deal['price'] && ($deal['price']['amount'] > 0)) {
- //If this is a paid deal
- if ($deal['owner']['type'] == "community") {
- //reward
- if (!$deal['price']['type'] || ($deal['price']['type'] != 'wallet' && $deal['price']['type'] != 'wallets')) {
- $rewardAllowance = RewardAllowances::model()->findByPk(array(
- "user_id" => $userId,
- "community_id" => $deal['owner']['id']
- ));
- if (!$rewardAllowance || !$rewardAllowance->checkCreditBalance($deal['price']['amount'])) {
- $status_message['insufficient_amount'][] = $assigneeUserId;
- continue;
- }
- $transfers = new RewardTransfers();
- }
- //wallet
- else {
- $walletBalance = WalletBalances::model()->findByAttributes(array(
- 'balance_id' => $userId,
- 'balance_type' => 1,
- 'wallet_type_id' => $deal['price']['wallet_id'],
- ));
- if (!$walletBalance || !$walletBalance->checkWalletBalance($deal['price']['amount'])) {
- $status_message['insufficient_amount'][] = $assigneeUserId;
- continue;
- }
- $transfers = new WalletTransfers();
- $transfers->transfer_from_wallet_id = $deal['price']['wallet_id'];
- }
- }
- $transfers->transfer_amount = $deal['price']['amount'];
- $transfers->transfer_from_id = $userId;
- $transfers->transfer_from_type = 1;
- $transfers->transfer_to_id = $deal['owner']['id'];
- $transfers->transfer_to_type = ($deal['owner']['type'] == 'user') ? '1' : '2';
- $transfers->transfer_narration = 'Payment for taking deal #' . $dealId;
- if (!$transfers->transfer()) {
- $status_message['payment_failed'][] = $assigneeUserId;
- continue;
- }
- }
- $liveDeal = new stdClass();
- $liveDeal->deal_id = new MongoID($dealId);
- $liveDeal->type = $deal['type'];
- $liveDeal->owner = $deal['owner'];
- $liveDeal->title = $deal['title'];
- $liveDeal->description = $deal['description'];
- $liveDeal->start_date = $deal['start_date'];
- $liveDeal->end_date = $deal['end_date'];
- $liveDeal->date_taken = date('Y-m-d');
- $liveDeal->price = $deal['price'];
- $liveDeal->city = $deal['city'];
- $liveDeal->town = $deal['town'];
- $liveDeal->zipCode = $deal['zipCode'];
- $liveDeal->country = $deal['country'];
- $liveDeal->visibility = $deal['visibility'];
- $liveDeal->tags = $deal['tags'];
- $liveDeal->dealinfo = $deal['dealinfo'];
- $liveDeal->roles = $deal['roles'];
- $liveDeal->rewardinfo = $deal['rewardinfo'];
- $liveDeal->limits = $deal['limits'];
- $liveDeal->total_value = $deal['total_value'];
- $liveDeal->pay_per_take = $deal['pay_per_take'];
- $liveDeal->pay_per_click = $deal['pay_per_click'];
- if ($deal['type'] == "coupon") {
- $liveDeal->status = 3;
- } else {
- $liveDeal->status = 1;
- }
- $liveDeal->user_id = intval($userId);
- $liveDeal->assigner_id = NULL;
- //affiliate
- if ($deal['affiliate_fee'] && is_array($deal['affiliate_fee']) && $affiliateId && ($affiliateId != $userId)) {
- $liveDeal->affiliate_fee = $deal['affiliate_fee'];
- $liveDeal->affiliate_id = intval($affiliateId);
- }
- $userinfo = new stdClass;
- $userinfo->id = intval($user->id);
- $userinfo->user_firstname = $user->user_firstname;
- $userinfo->user_lastname = $user->user_lastname;
- if ($deal['type'] == "stamp") {
- $userinfo->current_stamps = intval($deal['dealinfo']['starting_stamps']);
- $stamp_log = array();
- for ($i = 0; $i < $deal['dealinfo']['starting_stamps']; $i++) {
- $object = new stdClass;
- $object->timestamp = time();
- $stamp_log[] = $object;
- }
- }
- $liveDeal->userinfo = $userinfo;
- if ($deal['type'] == "stamp") {
- $liveDeal->stamp_log = $stamp_log;
- }
- //update promised credits
- if (!$this->updatePromised($deal)) {
- return false;
- }
- //commit
- $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
- $liveCollection->insert($liveDeal);
- //PPT transaction for sharer and tagbond
- if ($this->sharer) {
- $sitesettings = SiteSettings::model()->find(array("select" => "ppt_percentage,admin_id"));
- $ppt_valid = Deals::checkPPTValidity($dealId);
- if ($ppt_valid) {
- $user_ppt_amount = ($ppt_valid['amount'] * $sitesettings['ppt_percentage']) / 100;
- $tagbond_ppt_amount = $ppt_valid['amount'] - $user_ppt_amount;
- $transfer_sharer = new WalletTransfers;
- $transfer_sharer->transfer_from_id = $ppt_valid['community_id'];
- $transfer_sharer->transfer_from_type = 2;
- $transfer_sharer->transfer_from_wallet_id = $ppt_valid['wallet_id'];
- $transfer_sharer->transfer_from_amount = $user_ppt_amount;
- $transfer_sharer->transfer_to_id = $this->sharer;
- $transfer_sharer->transfer_to_type = 1;
- $transfer_sharer->transfer_to_wallet_id = $ppt_valid['wallet_id'];
- $transfer_sharer->transfer_narration = 'Payment for PayPerShare deal #' . $dealId;
- if (!$transfer_sharer->transfer()) {
- throw new CHttpException(403, 'reward_transfer_failed');
- }
- $transfer_tagbond = new WalletTransfers;
- $transfer_tagbond->scenario = 'system';
- $transfer_tagbond->transfer_from_id = $ppt_valid['community_id'];
- $transfer_tagbond->transfer_from_type = 2;
- $transfer_tagbond->transfer_from_wallet_id = $ppt_valid['wallet_id'];
- $transfer_tagbond->transfer_from_amount = $tagbond_ppt_amount;
- $transfer_tagbond->transfer_to_id = $sitesettings['admin_id'];
- $transfer_tagbond->transfer_to_type = 3;
- $transfer_tagbond->transfer_to_wallet_id = $ppt_valid['wallet_id'];
- $transfer_tagbond->transfer_narration = 'Commission for PayPerShare deal #' . $dealId;
- if (!$transfer_tagbond->transfer()) {
- throw new CHttpException(403, 'reward_transfer_failed');
- }
- }
- }
- }
- if (count($status_message) == 0)
- return "success";
- else
- return $status_message;
- }
- public function takeDeal($dealId, $affiliateId = NULL, $assigneeUserId = NULL, $data = NULL) {
- if ($assigneeUserId) {
- $user = Users::model()->findByPk($assigneeUserId);
- if ($user) {
- $userId = $assigneeUserId;
- } else {
- throw new CHttpException(404, "invalid_deal_id");
- }
- }
- $userId = $this->userId;
- if (!TagMongo::isValidId($dealId)) {
- throw new CHttpException(404, "invalid_deal_id");
- }
- $collection = Yii::app()->edmsMongoCollection('deals');
- $deal = $collection->findOne(array("_id" => new MongoID($dealId)));
- if (!$deal) {
- throw new CHttpException(403, "invalid_deal_id");
- } else if ($deal['type'] == 'ticket') {
- throw new CHttpException(403, "please_purchase_ticket");
- }
- if ($deal['status'] != 1) {
- throw new CHttpException(403, "deal_unavailable");
- }
- if ($deal['type'] != 'catalog') {
- $can_take = Deals::checkIfUserCanTakeDeal($deal, $userId, $affiliateId);
- if (!$can_take || $can_take->can_take == false) {
- throw new CHttpException(403, "user_cannot_take_deal");
- }
- //check already taken and exists
- if (self::checkIfUserHasTakenDealBefore($userId, $dealId)) {
- //If the user has taken the deal before. He should not be able to take it again
- throw new CHttpException(403, "already_taken");
- }
- //permissions
- if ($deal['owner']['type'] == "community") {
- if (!CommunityUsers::isMemberOf($userId, $deal['owner']['id'])) {
- throw new CHttpException(403, "not_member");
- }
- $roleId = CommunityUsers::getRoleOfUser($userId, $deal['owner']['id'])->role_id;
- if ($deal['roles']['take']) {
- if (!in_array($roleId, $deal['roles']['take'])) {
- throw new CHttpException(403, "permission_denied");
- }
- } else {
- throw new CHttpException(403, "permission_denied");
- }
- } else {
- //future
- if (!Contacts::checkIfAlreadyAContact($userId, $deal['owner']['id'])) {
- throw new CHttpException(403, "not_contact");
- }
- }
- //price
- if ($deal['price'] && ($deal['price']['amount'] > 0)) {
- //If this is a paid deal
- if ($deal['owner']['type'] == "community") {
- //reward
- if (!$deal['price']['type'] || ($deal['price']['type'] != 'wallet' && $deal['price']['type'] != 'wallets')) {
- $rewardAllowance = RewardAllowances::model()->findByPk(array(
- "user_id" => $userId,
- "community_id" => $deal['owner']['id']
- ));
- if (!$rewardAllowance || !$rewardAllowance->checkCreditBalance($deal['price']['amount'])) {
- throw new CHttpException(403, "insufficient_amount");
- }
- $transfers = new RewardTransfers();
- }
- //wallet
- else {
- $walletBalance = WalletBalances::model()->findByAttributes(array(
- 'balance_id' => $userId,
- 'balance_type' => 1,
- 'wallet_type_id' => $deal['price']['wallet_id'],
- ));
- if (!$walletBalance || !$walletBalance->checkWalletBalance($deal['price']['amount'])) {
- throw new CHttpException(403, "insufficient_amount");
- }
- $transfers = new WalletTransfers();
- $transfers->transfer_from_wallet_id = $deal['price']['wallet_id'];
- $transfers->transfer_to_wallet_id = $deal['price']['wallet_id'];
- }
- }
- $transfers->settings = SiteSettings::getSettings();
- $transfers->userId = $userId;
- $transfers->user = $this->user;
- $transfers->transfer_amount = $deal['price']['amount'];
- $transfers->transfer_from_amount = $deal['price']['amount'];
- $transfers->transfer_from_id = $userId;
- $transfers->transfer_from_type = 1;
- $transfers->transfer_to_id = $deal['owner']['id'];
- $transfers->transfer_to_type = ($deal['owner']['type'] == 'user') ? '1' : '2';
- $transfers->transfer_narration = 'Payment for taking deal #' . $dealId;
- if (!$transfers->transfer()) {
- throw new CHttpException(403, "payment_failed");
- }
- /* //update promised community credits
- if(is_array($deal['rewardinfo']) && $deal['rewardinfo']['type'] == 'credits'){
- $communtiy = new Communities();
- if(!$community->updatePromisedCredits($deal['owner']['id'],$deal['rewardinfo']['amount'])){
- throw new CHttpException(403, "update_promised_failed");
- }
- } */
- }
- }
- $liveDeal = new stdClass();
- $liveDeal->deal_id = new MongoID($dealId);
- $liveDeal->type = $deal['type'];
- $liveDeal->owner = $deal['owner'];
- $liveDeal->title = $deal['title'];
- $liveDeal->description = $deal['description'];
- $liveDeal->start_date = $deal['start_date'];
- $liveDeal->end_date = $deal['end_date'];
- $liveDeal->date_taken = date('Y-m-d H:i:s');
- $liveDeal->price = $deal['price'];
- $liveDeal->city = $deal['city'];
- $liveDeal->town = $deal['town'];
- $liveDeal->zipCode = $deal['zipCode'];
- $liveDeal->country = $deal['country'];
- $liveDeal->visibility = $deal['visibility'];
- $liveDeal->tags = $deal['tags'];
- $liveDeal->dealinfo = $deal['dealinfo'];
- $liveDeal->roles = $deal['roles'];
- $liveDeal->rewardinfo = $deal['rewardinfo'];
- $liveDeal->limits = $deal['limits'];
- $liveDeal->total_value = $deal['total_value'];
- $liveDeal->pay_per_take = $deal['pay_per_take'];
- $liveDeal->pay_per_click = $deal['pay_per_click'];
- if ($deal['type'] == "coupon") {
- $liveDeal->status = 3;
- } else {
- $liveDeal->status = 1;
- }
- $liveDeal->user_id = intval($userId);
- $liveDeal->assigner_id = NULL;
- $user = Users::model()->findByPk($userId);
- if (!$user) {
- throw new CHttpException(403, "user_doesnt_exist");
- }
- //affiliate
- if ($deal['affiliate_fee'] && is_array($deal['affiliate_fee']) && $affiliateId && ($affiliateId != $userId)) {
- $liveDeal->affiliate_fee = $deal['affiliate_fee'];
- $liveDeal->affiliate_id = intval($affiliateId);
- }
- $userinfo = new stdClass;
- $userinfo->id = intval($user->id);
- $userinfo->user_firstname = $user->user_firstname;
- $userinfo->user_lastname = $user->user_lastname;
- if ($deal['type'] == "stamp") {
- $userinfo->current_stamps = intval($deal['dealinfo']['starting_stamps']);
- $stamp_log = array();
- for ($i = 0; $i < $deal['dealinfo']['starting_stamps']; $i++) {
- $object = new stdClass;
- $object->timestamp = time();
- $stamp_log[] = $object;
- }
- }
- if ($deal['type'] == "catalog") {
- $liveDeal->priority = 0;
- $liveDeal->delivery_options = $deal['delivery_options'];
- if ($data != NULL) {
- $i = 0;
- foreach ($data['purchased_items'] as $pitem) {
- foreach ($deal['items'] as $item) {
- if ($item['id'] == $pitem->item) {
- $count = $pitem->count;
- if ($pitem->size)
- $size = $pitem->size;
- if ($pitem->color)
- $color = $pitem->color;
- if ($pitem->other)
- $other = $pitem->other;
- $item_list[$i] = $item;
- $item_list[$i]['count'] = $count;
- if ($size)
- $item_list[$i]['sizes'] = $size;
- if ($color)
- $item_list[$i]['colors'] = $color;
- if ($other)
- $item_list[$i]['other'] = $other;
- $i++;
- }
- }
- }
- $liveDeal->purchase_details['order_id'] = $data['order_id'];
- $liveDeal->purchase_details['items'] = $item_list;
- $liveDeal->purchase_details['delivery_address'] = $data['delivery_address'];
- $liveDeal->purchase_details['order_date'] = date('Y-m-d H:i:s');
- $liveDeal->purchase_details['delivery_method'] = array();
- if ($data['delivery_method']) {
- $liveDeal->purchase_details['delivery_method']['method'] = $data['delivery_method'];
- }
- $liveDeal->purchase_details['payment_details']['total_amount'] = $data['amount'];
- $liveDeal->purchase_details['payment_details']['wallet_id'] = $data['wallet_id'];
- $liveDeal->purchase_details['payment_details']['paid_using'] = $data['payment_method'];
- $liveDeal->purchase_details['payment_details']['transaction_id'] = $data['transaction_id'];
- }
- }
- if ($deal['type'] == "bus_reservation") {
- $liveDeal->dealinfo['passengers'] = $data;
- }
- if ($deal['type'] == "promo") {
- //Need to update the template also
- //Find an available coupon from the deal
- $parsedPromocodes = array();
- if ($deal['dealinfo']['promo_codes']) {
- foreach ($deal['dealinfo']['promo_codes'] as $promoCode) {
- if ($promoCode['status'] == 0) {
- //If an available promo code is found
- $availableCode = $promoCode['code'];
- $promoCode['status'] = 1;
- $promoCode['userId'] = intval($user->id);
- $parsedPromocodes[] = $promoCode;
- } else {
- $parsedPromocodes[] = $promoCode;
- }
- }
- }
- $total_available = intval($deal['total_available']);
- $total_available--;
- $update['total_available'] = intval($total_available);
- $update['dealinfo.promo_codes'] = $parsedPromocodes;
- $stat = $collection->update(array('_id' => new MongoID($dealId)), array('$set' => $update));
- if ($stat['ok'])
- $liveDeal->dealinfo['promo_codes'] = $availableCode;
- }
- if ($deal['type'] == "coupon") {
- $total_available = intval($deal['total_available']);
- $total_available--;
- $update['total_available'] = intval($total_available);
- $collection->update(array('_id' => new MongoID($dealId)), array('$set' => $update));
- }
- $liveDeal->userinfo = $userinfo;
- if ($deal['type'] == "stamp") {
- $liveDeal->stamp_log = $stamp_log;
- }
- //update promised credits
- if (!$this->updatePromised($deal)) {
- return false;
- }
- //commit
- $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
- $liveCollection->insert($liveDeal);
- //PPT transaction for sharer and tagbond
- if ($this->sharer) {
- $sitesettings = SiteSettings::model()->find(array("select" => "ppt_percentage,admin_id"));
- $ppt_valid = Deals::checkPPTValidity($dealId);
- if ($ppt_valid) {
- $user_ppt_amount = ($ppt_valid['amount'] * $sitesettings['ppt_percentage']) / 100;
- $tagbond_ppt_amount = $ppt_valid['amount'] - $user_ppt_amount;
- $transfer_sharer = new WalletTransfers;
- $transfer_sharer->transfer_from_id = $ppt_valid['community_id'];
- $transfer_sharer->transfer_from_type = 2;
- $transfer_sharer->transfer_from_wallet_id = $ppt_valid['wallet_id'];
- $transfer_sharer->transfer_from_amount = $user_ppt_amount;
- $transfer_sharer->transfer_to_id = $this->sharer;
- $transfer_sharer->transfer_to_type = 1;
- $transfer_sharer->transfer_to_wallet_id = $ppt_valid['wallet_id'];
- $transfer_sharer->transfer_narration = 'Payment for PayPerTake deal #' . $dealId;
- if (!$transfer_sharer->transfer()) {
- throw new CHttpException(403, 'reward_transfer_failed');
- }
- $transfer_tagbond = new WalletTransfers;
- $transfer_tagbond->scenario = 'system';
- $transfer_tagbond->transfer_from_id = $ppt_valid['community_id'];
- $transfer_tagbond->transfer_from_type = 2;
- $transfer_tagbond->transfer_from_wallet_id = $ppt_valid['wallet_id'];
- $transfer_tagbond->transfer_from_amount = $tagbond_ppt_amount;
- $transfer_tagbond->transfer_to_id = $sitesettings['admin_id'];
- $transfer_tagbond->transfer_to_type = 3;
- $transfer_tagbond->transfer_to_wallet_id = $ppt_valid['wallet_id'];
- $transfer_tagbond->transfer_narration = 'Commission for PayPerTake deal #' . $dealId;
- if (!$transfer_tagbond->transfer()) {
- throw new CHttpException(403, 'reward_transfer_failed');
- }
- }
- }
- return true;
- }
- // end of takeDeal
- public static function getAssignableDeals($communityId, $userId, $params) {
- if (!is_numeric($params['count']) || $params['count'] > 100) {
- $params['count'] = 100;
- }
- if (!is_numeric($params['offset'])) {
- $params['offset'] = 0;
- }
- $role = CommunityUsers::model()->with('role')->findByAttributes(array('user_id' => $userId, 'community_id' => $communityId));
- if ($role) {
- $collection = Yii::app()->edmsMongoCollection('deals');
- if ($role->role->role_type == 1) {
- //If Owner, show all deals in the community
- $deals = $collection->find(array(
- "owner.id" => intval($communityId),
- "owner.type" => "community",
- "status" => 1))
- ->skip($params['offset'])
- ->limit($params['count']);
- } elseif ($role->role->role_type == 2) {
- //Staff
- $deals = $collection->find(array(
- "owner.id" => intval($communityId),
- "owner.type" => "community",
- "roles.assign" => $roleId,
- "status" => 1))
- ->skip($params['offset'])
- ->limit($params['count']);
- } else {
- //If member
- throw new CHttpException(403, "permission_denied");
- }
- $parsedDeals = array();
- if ($deals) {
- foreach ($deals as $deal) {
- $parsedDeals[] = self::formatDeal($deal);
- }
- }
- return $parsedDeals;
- } else {
- throw new CHttpException(403, "permission_denied");
- }
- }
- public static function checkIfUserHasTakenDealBefore($userId, $dealId) {
- if (self::countTimesTaken($dealId, false, $userId)) {
- return true;
- } else {
- return false;
- }
- }
- /* Intelligent :) function to check whether the user can take deal */
- public static function checkIfUserCanTakeDeal($deal, $userId, $affiliateId = NULL) {
- //userId = takerId
- $object = new stdClass;
- $object->can_take = true;
- $object->errors = array();
- $modelUsers = Users::model()->findByPk($userId);
- $modelCommunity = Communities::model()->findByPk($deal['owner']['id']);
- if (!$modelUsers || !$modelCommunity)
- return false;
- $role = CommunityUsers::getRoleOfUser($userId, $deal['owner']['id']);
- if ($deal['owner']['type'] == "community") {
- $dealId = $deal['_id'];
- //limits - Per User, Per Day and Global Limit
- if ($deal['limits']['max_global_limit']) {
- if (Deals::countTimesTaken($dealId, true) >= $deal['limits']['max_global_limit']) {
- $object->errors[] = 'limit_exceeded';
- }
- } else {
- if ($deal['limits']['max_limit_per_day']) {
- if (Deals::countTimesTakenPerDay($dealId) >= $deal['limits']['max_limit_per_day']) {
- $object->errors[] = 'limit_per_day_exceeded';
- }
- } else {
- if ($deal['limits']['max_limit_per_user']) {
- if (Deals::countTimesTaken($dealId, true, $userId) >= $deal['limits']['max_limit_per_user']) {
- $object->errors[] = 'limit_per_user_exceeded';
- }
- }
- }
- }
- $object->community_roles = CommunityRoles::getNameOfRoles($deal['roles']['take']);
- if ($role) {
- if ($role->communityuser_status == 1) {
- $object->communityuser_status = true;
- //If the user is a part of the community
- if ($role->role_type == 3) {
- //If he is a member
- $object->community_relation = "member";
- //checking roles
- if (!in_array($role->role_id, $deal['roles']['take'])) {
- //Means this user doesnt have the permission to take this deal
- $object->errors[] = 'invalid_community_role';
- }
- } else {
- $object->community_relation = "staff";
- $object->errors[] = 'invalid_community_role_type';
- }
- } else {
- $object->communityuser_status = false;
- $object->errors[] = 'pending_community_request';
- }
- } else {
- $object->can_join = true;
- $object->community_relation = "non_member";
- //checking community type, autojoin, join
- if ($modelCommunity->community_type == 1) { //private
- $object->community_type = "private";
- $object->can_join = false;
- $object->errors[] = 'private_community';
- } else {
- //check if user eligible to join
- $eligibility = Communities::checkIfUserIsEligibleToJoin($modelUsers, $modelCommunity);
- if (!$eligibility->eligible) {
- $object->can_join = false;
- $object->errors[] = array('community_eligibility' => $eligibility->errors);
- } else {
- if ($modelCommunity->community_type == 0) { //public
- $object->community_type = "public";
- if ($modelCommunity->community_autojoin) {
- $object->community_autojoin = true;
- } else {
- $object->community_autojoin = false;
- $object->errors[] = 'invalid_community_autojoin';
- }
- } else if ($modelCommunity->community_type == 2) { //paid
- $object->community_type = "paid";
- $object->community_fee = intval($modelCommunity->community_fee);
- }
- }
- //checking roles
- $defaultRole = CommunityRoles::getDefaultRole($deal['owner']['id']);
- if (!in_array($defaultRole->id, $deal['roles']['take'])) {
- //Means this user doesnt have the role permission to take this deal if joined
- $object->errors[] = 'invalid_community_role';
- }
- }
- }
- }
- //credits needed for taking the deal
- $total_credits = 0;
- //check credit balance over community price
- if (!$role && $modelCommunity->community_type == 2) {
- $object->can_join = true;
- // need to do community fee
- }
- // check deal price
- if ($deal['price'] && ($deal['price']['amount'] > 0)) {
- // check allowance balance over deal price
- if (!$deal['price']['type'] || ($deal['price']['type'] != 'wallet' && $deal['price']['type'] != 'wallets')) {
- $rewardAllowance = RewardAllowances::model()->findByPk(array(
- 'user_id' => $userId,
- 'community_id' => $deal['owner']['id']
- ));
- if (!$rewardAllowance || !$rewardAllowance->checkCreditBalance($deal['price']['amount'])) {
- $object->errors[] = 'insufficient_amount';
- }
- } else {
- $walletBalance = WalletBalances::model()->findByAttributes(array(
- 'balance_id' => $userId,
- 'balance_type' => 1,
- 'wallet_type_id' => $deal['price']['wallet_id'],
- ));
- if (!$walletBalance || !$walletBalance->checkWalletBalance($deal['price']['amount'])) {
- $object->errors[] = 'insufficient_amount';
- }
- }
- }
- //need to update and fix
- //promised credits
- $promisedCredits = 0;
- //check promised credits - reward
- if (is_array($deal['rewardinfo']) && $deal['rewardinfo']['type'] == 'reward') {
- if ($modelCommunity->community_credits < ($modelCommunity->community_promised_credits + $deal['rewardinfo']['amount'])) {
- $object->errors[] = 'insufficient_community_credits_for_deal_reward';
- }
- }
- //check promised credits - total_value
- if (($deal['owner']['type'] == "community") && $deal['total_value']) {
- $promisedCredits += $deal['total_value'];
- }
- //check promised credits - affiliate fee
- if ($deal['affiliate_fee']) {
- $object->affiliate_fee = $deal['affiliate_fee'];
- if ($affiliateId && ($affiliateId != $userId)) {
- $promisedCredits += $deal['affiliate_fee'];
- }
- }
- /*
- if($promisedCredits){
- if(!$modelCommunity->checkIfEnoughPromisedCreditsAreThere($promisedCredits)){
- $object->errors[] = 'insufficient_community_credits_to_promise';
- }
- } */
- if (count($object->errors)) {
- $object->can_take = false;
- }
- return $object;
- }
- //checkIfUserCanTakeDeal
- /*
- * * deals - end of take and assign
- */
- /*
- * * deals - take action
- */
- public function takeAction($dealId, $userId, $staffId = NULL, $communityId = NULL) {
- if (!TagMongo::isValidId($dealId)) {
- throw new CHttpException(404, "invalid_deal_id");
- }
- $collection = Yii::app()->edmsMongoCollection('deals_live');
- $deal = $collection->findOne(array(
- "deal_id" => new MongoID($dealId),
- "user_id" => intval($userId)
- ));
- if ($deal) {
- if ($deal['owner']['type'] == "community") {
- //If the owner of the deal is a community
- if ($staffId) {
- //If a staff member is trying to take action
- $roleDetails = CommunityUsers::getRoleOfUser($staffId, $deal['owner']['id']);
- if ($roleDetails->role_type != 1) {
- if (!in_array($roleDetails->role_id, $deal['roles']['redeem'])) {
- throw new CHttpException(403, "permission_denied");
- }
- }
- } else {
- if ($userId != $deal['user_id'] || ($communityId == NULL && !$deal['dealinfo']['take_action'])) {
- throw new CHttpException(403, "permission_denied");
- }
- }
- } else {
- //If the owner of the deal is a user
- //the staffId will mean the user who created the deal
- if ($staffId) {
- if ($staffId != $deal['owner']['id']) {
- throw new CHttpException(403, "permission_denied");
- }
- } else {
- if ($userId != $deal['user_id'] || !$deal['take_action']) {
- throw new CHttpException(403, "permission_denied");
- }
- }
- }
- if ($deal['type'] == "stamp") {
- if ($deal['dealinfo']['total_stamps'] == $deal['userinfo']['current_stamps']) {
- return "no_more_stamps_to_add";
- }
- $userinfo = $this->addStamp($deal);
- $collection->update(array(
- "_id" => $deal['_id']
- ), array('$set' => array("userinfo" => $userinfo)));
- $dealinfo['current_stamps'] = $deal['userinfo']['current_stamps'] + 1;
- $dealinfo['total_stamps'] = $deal['dealinfo']['total_stamps'];
- return $dealinfo;
- } else {
- throw new CHttpException(403, "no_action_for_this_deal");
- }
- if (Deals::checkIfComplete($deal)) {
- if ($deal['rewardinfo']['auto_redeem']) {
- $transaction = Yii::app()->db->beginTransaction();
- try {
- //If this deal can be auto redeemed
- $this->updatePromised($deal, true);
- $this->rewardUser($deal);
- $this->payAffiliate($deal);
- $this->moveLiveDealToHistory($deal);
- //committing
- $transaction->commit();
- } catch (Exception $e) {
- $transaction->rollback();
- $this->response['error'] = $e->getMessage();
- $this->response['status'] = 'falied';
- Rest::sendResponse(403, json_encode($this->response, JSON_NUMERIC_CHECK));
- }
- return true;
- } else {
- //If the deal cannot be auto redeemed, set it's status as complete
- //so that the staff can redeem it later
- $collection->update(array(
- "_id" => $deal['_id']
- ), array('$set' => array("status" => 3)));
- }
- }
- return true;
- } else {
- throw new CHttpException(403, "invalid_dealid");
- }
- }
- private function addStamp($deal) {
- $stamp_log = $deal['userinfo']['stamp_log'];
- if ($deal['dealinfo']['limit_per_day']) {
- $timestampLastday = time() - (60 * 60 * 24);
- if ($stamp_log) {
- $count = 0;
- foreach ($stamp_log as $stamp) {
- if ($stamp['timestamp'] > $timestampLastday) {
- $count++;
- }
- if ($count >= $deal['dealinfo']['limit_per_day']) {
- $f = 1;
- break;
- }
- }
- if ($f) {
- throw new CHttpException(403, "stamp_limit_reached");
- }
- }
- }
- $object = new stdClass;
- $object->timestamp = time();
- if ($this->notes)
- $object->notes = $this->notes;
- $stamp_log[] = $object;
- $deal['userinfo']['current_stamps'] = intval($deal['userinfo']['current_stamps'] + 1);
- $deal['userinfo']['stamp_log'] = $stamp_log;
- return $deal['userinfo'];
- }
- /*
- * * deals - end of take action
- */
- /*
- * * deals - redeem
- */
- public function redeemDeal($dealId, $dealUserId = NULL) {
- if (!$dealUserId) {
- $dealUserId = $this->userId;
- }
- $collection = Yii::app()->edmsMongoCollection('deals_live');
- $deal = $collection->findOne(array(
- "deal_id" => new MongoID($dealId),
- "user_id" => intval($dealUserId)
- ));
- //check permissions
- if (!$this->isPermission('redeem', $deal)) {
- return false;
- }
- //check deal complete
- if (!Deals::checkIfComplete($deal)) {
- throw new CHttpException(403, "deal_incomplete");
- }
- $dealRedeemed = true;
- $transaction = Yii::app()->db->beginTransaction();
- try {
- $this->updatePromised($deal, true);
- $this->payAffiliate($deal);
- if ($this->rewardUser($deal))
- $this->moveLiveDealToHistory($deal, $redeem = true);
- else
- $dealRedeemed = false;
- //committing
- $transaction->commit();
- } catch (Exception $e) {
- $transaction->rollback();
- $this->response['error'] = $e->getMessage();
- $this->response['status'] = 'falied';
- Rest::sendResponse(403, json_encode($this->response, JSON_NUMERIC_CHECK));
- }
- if ($dealRedeemed) {
- if (($deal['type'] == 'promo') && ($deal['dealinfo']['promo_codes'])) {
- $redeemer = Users::model()->findByPk($dealUserId);
- //send promocode via email
- $mail = new YiiMailer();
- $mail->IsSMTP();
- $mail->Host = 'smtp.gmail.com';
- $mail->Port = 465;
- $mail->SMTPAuth = true;
- $mail->SMTPSecure = 'ssl';
- $mail->Username = Yii::app()->params['adminEmail'];
- $mail->Password = Yii::app()->params['adminEmailPassword'];
- $mail->setView('promocodeactivate');
- $mail->setData(array(
- 'dealTitle' => $deal['title'],
- 'description' => $deal['description']
- ));
- $mail->render();
- $mail->From = Yii::app()->params['adminEmail'];
- $mail->FromName = Yii::app()->name;
- $mail->Subject = Yii::t('labels', Yii::t("labels", "Tagwild gift coupon received"));
- $mail->AddAddress($redeemer->user_email);
- $mail->Send();
- return array('status' => 'success', 'type' => $deal['type'], 'title' => $deal['title'], 'description' => $deal['description'], 'promo_code' => $deal['dealinfo']['promo_codes']);
- } elseif (($deal['type'] == 'load') && ($deal['share_for_reward']['amount'])) {
- $dealowner = array('owner_type' => 1, 'owner_id' => $deal['share_for_reward']['owner_id']);
- return array('status' => 'success', 'type' => $deal['type'], 'title' => $deal['title'], 'description' => $deal['description'], 'load_amount' => $deal['share_for_reward']['amount'], 'owner' => $dealowner);
- }
- return array('status' => 'success', 'type' => $deal['type'], 'title' => $deal['title'], 'description' => $deal['description']);
- } else
- return array('status' => 'falied');
- }
- public function rewardUser($deal) {
- if ($deal['rewardinfo']['type'] == "reward" || $deal['rewardinfo']['type'] == "points") {
- $rewardPoints = new RewardTransfers();
- $rewardPoints->transfer_from_id = $deal['owner']['id'];
- $rewardPoints->transfer_from_type = ($deal['owner']['type'] == "community") ? "2" : "1";
- $rewardPoints->transfer_to_id = $deal['user_id'];
- $rewardPoints->transfer_to_type = 1;
- $rewardPoints->transfer_narration = 'Reward for the deal : #' . $deal['deal_id'];
- $rewardPoints->transfer_amount = $deal['rewardinfo']['amount'];
- if (!$rewardPoints->transfer()) {
- //Common::pre($rewardPoints->getErrors(), true);
- throw new CHttpException(403, 'reward_transfer_failed');
- }
- } else if ($deal['rewardinfo']['type'] == "wallet") {
- $rewardWallet = new WalletTransfers;
- $rewardWallet->transfer_from_id = $deal['owner']['id'];
- $rewardWallet->transfer_from_type = $deal['owner']['type'];
- $rewardWallet->transfer_from_wallet_id = $deal['rewardinfo']['wallet_id'];
- $rewardWallet->transfer_from_amount = $deal['rewardinfo']['amount'];
- $rewardWallet->transfer_to_id = $deal['user_id'];
- $rewardWallet->transfer_to_type = 1;
- $rewardWallet->transfer_to_wallet_id = $deal['rewardinfo']['wallet_id'];
- $rewardWallet->transfer_narration = "Reward for the deal : #" . $deal['deal_id'];
- if (!$rewardWallet->transfer()) {
- //Common::pre($rewardWallet->getErrors(), true);
- throw new CHttpException(403, 'reward_transfer_failed');
- }
- } elseif ($deal['rewardinfo']['type'] == "rolechange") {
- $userRole = CommunityUsers::model()->findByAttributes(array(
- "user_id" => $deal['user_id'],
- "community_id" => $deal['owner']['id']
- ));
- $userRole->role_id = $deal['rewardinfo']['role_id'];
- $userRole->save();
- } elseif ($deal['rewardinfo']['type'] == "deal") {
- //If a deal is the reward
- $collection = Yii::app()->edmsMongoCollection('deals');
- $newDeal = $collection->findOne(array("_id" => $deal['rewardinfo']['dealId']));
- $liveDeal = new stdClass();
- $liveDeal->deal_id = $newDeal['_id'];
- $liveDeal->type = $newDeal['type'];
- $liveDeal->owner = $newDeal['owner'];
- $liveDeal->title = $newDeal['title'];
- $liveDeal->description = $newDeal['description'];
- $liveDeal->start_date = $newDeal['start_date'];
- $liveDeal->end_date = $newDeal['end_date'];
- $liveDeal->price = $newDeal['price'];
- $liveDeal->city = $newDeal['city'];
- $liveDeal->country = $newDeal['country'];
- $liveDeal->visibility = $newDeal['visibility'];
- $liveDeal->tags = $newDeal['tags'];
- $liveDeal->dealinfo = $newDeal['dealinfo'];
- $liveDeal->roles = $newDeal['roles'];
- $liveDeal->rewardinfo = $newDeal['rewardinfo'];
- $liveDeal->limits = $newDeal['limits'];
- $liveDeal->total_value = $newDeal['total_value'];
- $liveDeal->status = 1;
- $liveDeal->user_id = intval($deal['user_id']);
- $liveDeal->assigner_id = intval($deal['assigner_id']);
- $user = Users::model()->findByPk($deal['user_id']);
- if ($newDeal['type'] == "stamp") {
- $userinfo = new stdClass;
- $userinfo->id = intval($user->id);
- $userinfo->user_firstname = $user->user_firstname;
- $userinfo->user_lastname = $user->user_lastname;
- $userinfo->current_stamps = intval($newDeal['dealinfo']['starting_stamps']);
- $userinfo->stamp_log = array();
- } else {
- $userinfo = new stdClass;
- $userinfo->id = intval($user->id);
- $userinfo->user_firstname = $user->user_firstname;
- $userinfo->user_lastname = $user->user_lastname;
- }
- $liveDeal->userinfo = $userinfo;
- $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
- $liveCollection->insert($liveDeal);
- } elseif ($deal['share_for_reward']['type'] == "bonus") {
- $fromUser = $deal['share_for_reward']['owner_id'];
- $toUser = $deal['user_id'];
- $amount = $deal['share_for_reward']['amount'];
- $walletBalance = WalletBalances::model()->findByAttributes(array(
- 'balance_id' => $fromUser,
- 'balance_type' => 1,
- 'wallet_type_id' => $this->walletId,
- ));
- if (!$walletBalance->checkWalletBalance($amount)) {
- $subject = "Insufficient TEP balance";
- $settings = array(
- 'view' => 'insufficientBalance',
- 'subject' => $subject
- );
- $data = array(
- 'name' => $user->user_firstname . ' ' . $user->user_lastname,
- 'user_email' => $user->user_email,
- 'walletName' => 'TEP'
- );
- $mail = new TagbondMail();
- $mail->sendTagbondMail($settings, $data, $response);
- return false;
- }
- $TagEnergyPoints = new TagEnergyPoints();
- $chargeBonus = $TagEnergyPoints->walletTransfer(intval($fromUser), 1, $deal['share_for_reward']['amount'], 'charging', $this->thisObj, 'Charged for giving gift bonus points');
- if ($chargeBonus['status'] == 'success') {
- $transfer = $TagEnergyPoints->walletTransfer(intval($toUser), 1, $deal['share_for_reward']['amount'], 'debit', $this->thisObj, 'Gift bonus points');
- if ($transfer['status'] == 'success') {
- return true;
- } else {
- return false;
- }
- } else {
- return false;
- }
- }
- return true;
- }
- public function payAffiliate($deal) {
- if ($deal['affiliate_id'] && $deal['affiliate_fee']) {
- $modelCreditTransfers = new CreditTransfers();
- $modelCreditTransfers->transfer_from_id = $deal['owner']['id'];
- $modelCreditTransfers->transfer_from_type = ($deal['owner']['type'] == "community") ? "2" : "1";
- $modelCreditTransfers->transfer_to_id = $deal['affiliate_id'];
- $modelCreditTransfers->transfer_to_type = 1;
- $modelCreditTransfers->transfer_amount = $deal['affiliate_fee'];
- $modelCreditTransfers->transfer_narration = "Affiliate Fee";
- //Common::pre($deal, true);
- $modelCreditTransfers->transferCredits();
- }
- }
- public static function checkIfComplete($dealData) {
- if ($dealData['type'] == "stamp") {
- if ($dealData['userinfo']['current_stamps'] == $dealData['dealinfo']['total_stamps']) {
- //Means the deal has finished and can be redeemed
- return true;
- } else {
- return false;
- }
- } else {
- return true;
- }
- }
- /*
- * * deals - end of redeem
- */
- /*
- * * deals - list
- */
- public function searchDeals($filter = array(), $params = array()) {
- $parsedDeals = array();
- $query = array();
- $query1 = array();
- $deal_type_master_list = array();
- //sorting ( by cost_per_view) descending order
- $sort = array("status" => 1, "cost_per_view.amount" => -1, "end_date" => 1);
- if ($filter['loc']) {
- $location['long'] = $filter['loc']['long'];
- $location['lat'] = $filter['loc']['lat'];
- }
- if ($this->communityId) {
- $deal_type_master_list = array('coupon', 'digital', 'pointsale', 'promo', 'ticket', 'stamp', 'passport', 'catalog', 'sticker', 'food', 'jobs', 'book_spa', 'bus_reservation', 'load', 'bonus');
- } else {
- $deal_type_master_list = array('coupon', 'stamp', 'catalog', 'jobs', 'ticket', 'load', 'bonus');
- if ($filter['type'] != 'jobs') {
- //this is a custom code for :
- // discard showing tagverts if, the owner have insufficient balance for cost_per_view
- $query['$or'] = array(
- 0 => array(
- '$and' => array(
- 0 => array(
- 'cost_per_view.amount' => array(
- '$gt' => 0
- )
- ),
- 1 => array(
- '$where' => "this.cost_per_view.amount <= this.cost_per_view.ad_balance"
- )
- )
- ),
- 1 => array(
- 'cost_per_view' => null
- ),
- 2 => array(
- 'cost_per_view' => array(
- '$exists' => false
- )
- )
- );
- }
- }
- //searching deal templates
- //copied from getAllDealsOfACommunity()
- $collection = Yii::app()->edmsMongoCollection('deals');
- // pagination
- if (isset($this->pageOffset) && (!is_numeric($this->pageOffset) || $this->pageOffset < 0)) {
- $this->pageOffset = 0;
- }
- if (isset($this->pageCount) && (!is_numeric($this->pageCount) || $this->pageCount < 0)) {
- $this->pageCount = 100;
- }
- if ($filter['type']) {
- if (is_array($filter['type'])) {
- //add book_spa if specified in filter explicitely
- if (in_array('book_spa', $filter['type']))
- $deal_type_master_list[] = 'book_spa';
- //add sticker if specified in filter explicitely
- if (in_array('sticker', $filter['type']))
- $deal_type_master_list[] = 'sticker';
- //datapage exception
- if (in_array('datapage', $filter['type'])) {
- $deal_type_master_list[] = 'datapage';
- }
- //skip empty catalog tagverts
- //if(in_array('catalog', $filter['type']))
- //$query['items'] = array('$exists'=>true, '$ne'=>null, '$not'=>array('$size'=> 0));
- foreach ($filter['type'] as $type) {
- if (!in_array($type, $deal_type_master_list)) {
- continue;
- }
- $types[] = $type;
- }
- if ($types)
- $query['type'] = array('$in' => $types);
- else
- return $parsedDeals;
- }
- else {
- //add book_spa if specified in filter explicitely
- if ($filter['type'] == 'book_spa')
- $deal_type_master_list[] = 'book_spa';
- //sticker exception
- if ($filter['type'] == 'sticker') {
- $deal_type_master_list[] = 'sticker';
- }
- //datapage exception
- if ($filter['type'] == 'datapage') {
- $deal_type_master_list[] = 'datapage';
- }
- //skip empty catalog tagverts
- if ($filter['type'] == 'catalog')
- $query['items'] = array('$exists' => true, '$ne' => null, '$not' => array('$size' => 0));
- if (!in_array($filter['type'], $deal_type_master_list)) {
- //no displayable deals
- return $parsedDeals;
- } else
- $query['type'] = $filter['type'];
- }
- }
- if ($filter['status']) {
- if ($filter['status'] == 'active') {
- $query['status'] = 1;
- $query["end_date"] = array('$gte' => date('Y-m-d'));
- } else if ($filter['status'] == 'expired') {
- $query['status'] = 2;
- } else if ($filter['status'] == 'disabled') {
- $query['status'] = 4;
- } else {
- $query['status'] = intval($filter['status']);
- }
- }
- if ($filter['credit_type']) {
- $query['credit_type'] = $filter['credit_type'];
- }
- if ($filter['food_type']) {
- $query['food_type'] = $filter['food_type'];
- }
- if ($filter['title']) {
- $query['title'] = array('$regex' => $filter['title'], '$options' => 'i');
- }
- if ($filter['city']) {
- $query['city'] = array('$regex' => $filter['city'], '$options' => 'i');
- }
- if ($filter['country_id']) {
- $query['country.id'] = intval($filter['country_id']);
- }
- if (is_array($filter['tags'])) {
- $query['tags'] = array('$all' => $filter['tags']);
- }
- if (is_array($filter['hashtags'])) {
- $query['items.hashtags'] = array('$all' => $filter['hashtags']);
- }
- //filter by owner
- if ($filter['community_id']) {
- $query['owner.id'] = intval($filter['community_id']);
- $query['owner.type'] = 'community';
- if ($filter['community_id'] == $this->communityId ||
- CommunityUsers::isMemberOf($this->userId, $filter['community_id'])) {
- $sort = array("status" => 1, "start_date" => -1);
- if ($filter['visibility']) {
- $query['visibility'] = $filter['visibility'];
- }
- } else {
- $query['visibility'] = 'public';
- }
- } else if ($filter['role_type']) {
- $filterCommunities = array(
- 'role_type' => $filter['role_type'],
- );
- $modelCommunities = new Communities;
- $modelCommunities->setIdentity($this);
- $communities = $modelCommunities->searchCommunities($filterCommunities);
- $communityIds = array();
- if ($communities) {
- foreach ($communities as $community) {
- $communityIds[] = intval($community->id);
- }
- }
- $query['owner.id'] = array('$in' => $communityIds);
- $query['owner.type'] = 'community';
- }
- //no filter by owner
- else {
- $query['visibility'] = 'public';
- }
- $query['switch'] = array('$ne' => intval(0));
- if (!$this->communityId) {
- if ($location['long'] && $location['lat']) {
- $long = $location['long'];
- $lat = $location['lat'];
- if ($filter['distance'])
- $distance = $filter['distance'];
- else
- $distance = 2; // default 2km
- $query["location"] = array('$near' => array(floatval($long), floatval($lat)), '$maxDistance' => floatval($distance / 111.12));
- unset($query['$or']); // or wont work with $near geospacial
- $sort = array(); //no need of sort- automatically sorting via distance
- $this->pageOffset = 0; //no pagination
- $this->pageCount = 100;
- }
- }
- // search for price type = none
- if ($filter['price'] == 'none') {
- $query['price.type'] = 'none';
- }
- //filter by category
- if ($filter['category']) {
- $query['category.id'] = $filter['category'];
- }
- //filter by catalog item category
- if ($filter['item_category'] > 0) {
- $query['type'] = 'catalog';
- $query['items.category.id'] = $filter['item_category'];
- }
- //$query['owner']['verified'] == 1;
- // executing query
- $deals = $collection->find($query)
- ->skip($this->pageOffset)
- ->limit($this->pageCount)
- ->sort($sort);
- // parsing the result
- if ($deals) {
- foreach ($deals as $deal) {
- if ($deal['type']) {
- if ($query["location"] && !in_array($deal['type'], $deal_type_master_list))
- continue;
- }
- if ($filter['status'] == 'active' && $deal['type'] == 'ticket') {
- if ($deal['dealinfo']['end_event_date'] && $deal['dealinfo']['end_event_date'] < date('Y-m-d'))
- continue;
- if ($deal['dealinfo']['event_date'] != NULL && $deal['dealinfo']['event_date'] < date('Y-m-d'))
- continue;
- }
- $items = array();
- $image = array();
- $catalogImages = new CatalogImages;
- if (is_array($deal['items'])) {
- foreach ($deal['items'] as $item) {
- if ($filter['item_category'] > 0) {
- if ($item['category']['id'] != $filter['item_category'])
- continue;
- }
- if ($filter['hashtags'] && is_array($filter['hashtags'])) {
- if (empty(array_intersect($item['hashtags'], $filter['hashtags'])))
- continue;
- }
- $item['image'] = $catalogImages->getCatalogImages($item['id']) ? $catalogImages->getCatalogImages($item['id']) : $image;
- $items[] = $item;
- }
- $deal['items'] = $items;
- }
- $parsedDeals[] = self::formatDeal($deal, NULL, $this->communityId, $this->userId);
- }
- }
- return $parsedDeals;
- }
- public static function getAllDealsOfAUser($userId, $status = NULL, $publicOnly = false) {
- $collection = Yii::app()->edmsMongoCollection('deals_live');
- if ($publicOnly) {
- $query = array("user_id" => intval($userId), "owner.type" => "community", "visibility" => "public");
- } else {
- $query = array("user_id" => intval($userId), "owner.type" => "community");
- }
- if ($status) {
- $query['status'] = $status;
- }
- $deals = $collection->find($query);
- $parsedDeals = array();
- if ($deals) {
- foreach ($deals as $deal) {
- $object = new stdClass();
- $object->id = $deal['_id']->__toString();
- $object->title = $deal['title'];
- $object->description = $deal['description'];
- $object->start_date = $deal['start_date'];
- $object->end_date = $deal['end_date'];
- $object->country = $deal['country'];
- $object->city = $deal['city'];
- $object->visibility = $deal['visibility'];
- $object->status = self::formatStatus($deal['status']);
- $parsedDeals[] = $object;
- }
- }
- return $parsedDeals;
- }
- public function getLiveDeals($userId = NULL, $communityId = NULL, $filter = array()) {
- // pagination
- if (!is_numeric($this->pageCount) || $this->pageCount > 100) {
- $this->pageCount = 100;
- }
- if (!is_numeric($this->pageOffset)) {
- $this->pageOffset = 0;
- }
- $params = array();
- $sort = array();
- //$sort['priority'] = 1;
- $filter['type'] = json_decode($filter['type'], true);
- if (is_array($filter['type'])) {
- if (in_array('catalog', $filter['type'])) {
- $sort['purchase_details.order_date'] = -1;
- }
- $params['type'] = array('$in' => $filter['type']);
- } else {
- $sort['purchase_details.order_date'] = -1;
- $sort['date_taken'] = -1;
- $sort['taken_date'] = -1;
- }
- if ($communityId) {
- $params["owner.id"] = intval($communityId);
- $params["owner.type"] = "community";
- if ($filter["priority"] == 'urgent') {
- $params["priority"] = 0;
- }
- if ($filter["priority"] == 'noturgent') {
- $params["priority"] = array('$ne' => 0);
- }
- }
- if ($userId) {
- $params['user_id'] = intval($userId);
- }
- if ($this->title) {
- $params['title'] = array('$regex' => $this->title, '$options' => 'i');
- }
- //inuse and inbox
- if ($this->status == 'inuse') {
- $params['status'] = intval(8);
- }
- if ($this->status == 'inbox') {
- $params['status'] = intval(9);
- }
- if ($this->type)
- $params['type'] = $this->type;
- //$params["end_date"] = array('$gte' => date('Y-m-d'));
- $collection = Yii::app()->edmsMongoCollection('deals_live');
- $deals = $collection->find($params)
- ->skip($this->pageOffset)->limit($this->pageCount)
- ->sort($sort);
- $parsedDeals = array();
- if ($deals) {
- $i = 0;
- foreach ($deals as $deal) {
- echo $deal['purchase_details']['order_date'];
- if ($deal['type'] == 'ticket') { //skip showing deprecated mongo format tickets
- if (is_array($deal['purchasedTickets']['tickets']) == false)
- continue;
- }
- //non bookmarked tagverts
- if ($option == "non_bookmarked" && $deal['status'] == 7) {
- continue;
- }
- $i++;
- $object = new stdClass;
- $object->live_id = $deal['_id']->__toString();
- $object->id = $deal['deal_id']->__toString();
- $object->taken_date = date("Y-m-d H:i:s", $deal['_id']->getTimestamp());
- $object->title = $deal['title'];
- $object->description = $deal['description'];
- $object->type = $deal['type'];
- $object->start_date = $deal['start_date'];
- $object->end_date = $deal['end_date'];
- $object->userinfo = $deal['userinfo'];
- $object->dealinfo = $deal['dealinfo'];
- if ($deal['method']) {
- $object->method = $deal['method'];
- } else {
- switch ($deal['paidUsing']) {
- case 'gameslotaward':
- $object->method = 'won game slot';
- break;
- case 'none':
- $object->method = 'assign';
- break;
- default:
- $object->method = 'purchase';
- break;
- }
- }
- if ($deal['price'])
- $object->price = $deal['price'];
- $member_details = Communities::getMemberRoleType($communityId, $deal['userinfo']['id']);
- if (count($member_details) > 0 && count($object->userinfo) > 0) {
- $object->userinfo = array_merge($object->userinfo, $member_details);
- }
- $object->visibility = $deal['visibility'];
- if (strtotime(date('Y-m-d')) > strtotime($deal['end_date']))
- $object->status = self::formatStatus(2);
- else
- $object->status = self::formatStatus($deal['status']);
- // ticket details
- if ($deal['type'] == 'ticket') {
- if ($deal['price']) {
- $total_category = count($deal['price']['options']);
- }
- if ($deal['purchasedTickets']) {
- $price_type = $deal['price']['type'];
- if ($deal['price']['type'] == 'tPoints') {
- $price_type = 'TAG Points';
- } else {
- $price_type = WalletTypes::getWalletName($deal['price']['wallet_id'], true);
- }
- if ($deal['purchasedTickets']['tickets']) {
- $i = 0;
- foreach ($deal['purchasedTickets']['tickets'] as $ticket) {
- $index = $deal['purchasedTickets']['tickets'][$i]['index'];
- $deal['purchasedTickets']['tickets'][$i]['price'] = $deal['price']['options'][$index]['price'] . " " . $price_type;
- unset($deal['purchasedTickets']['tickets'][$i]['index']);
- $i++;
- }
- }
- $object->tickets = $deal['purchasedTickets'];
- }
- }
- if ($deal['type'] == 'catalog') {
- $catImg = new CatalogImages;
- $i = 0;
- if ($deal['purchase_details']) {
- foreach ($deal['purchase_details'] as $purchaseditems) {
- if (isset($purchaseditems['id']))
- $deal['purchase_details']['items']['image'] = $catImg->getCatalogImages($purchaseditems['id']);
- $i++;
- }
- }
- $object->purchase_details = $deal['purchase_details'];
- if ($deal['delivery_options'])
- $object->delivery_options = $deal['delivery_options'];
- }
- if ($deal['owner']['type'] == "community") {
- $community = Communities::model()->findByPk($deal['owner']['id']);
- if ($community) {
- $owner = new stdClass;
- $owner->id = $community->id;
- $owner->name = $community->community_name;
- $owner->type = "community";
- }
- } else {
- $user = Users::model()->findByPk($deal['owner']['id']);
- if ($user) {
- $owner = new stdClass;
- $owner->id = $user->id;
- $owner->name = $user->user_firstname . " " . $user->user_lastname;
- $owner->type = "user";
- }
- }
- $object->owner = $owner;
- $object->image = SELF::getAvatar($object->id, true);
- $parsedDeals[] = $object;
- }
- }
- return $parsedDeals;
- }
- public static function getAvatar($dealId, $thumbnail = false) {
- if ($thumbnail == true) {
- $filePath = 'uploads/tagverts/thumbnail_1';
- $baseUrl = '.s3.amazonaws.com/uploads/tagverts/thumbnail_1/';
- } else {
- $filePath = 'uploads/tagverts';
- $baseUrl = '.s3.amazonaws.com/uploads/tagverts/';
- }
- $fileName = 'd_' . $dealId . '.png';
- $resultS3 = Yii::app()->tamazon->isObjectExist($filePath, $fileName);
- if (!$resultS3) {
- $fileName = 'd_' . $dealId . '.jpg';
- $resultS3 = Yii::app()->tamazon->isObjectExist($filePath, $fileName);
- if (!$resultS3)
- $image = sprintf('https://%s%s%s', Yii::app()->tamazon->bucketRoot, $baseUrl, 'default.png');
- else
- $image = sprintf('https://%s%s%s', Yii::app()->tamazon->bucketRoot, $baseUrl, $fileName);
- } else
- $image = sprintf('https://%s%s%s', Yii::app()->tamazon->bucketRoot, $baseUrl, $fileName);
- return $image;
- }
- public static function searchLiveDeals($params) {
- if (!is_numeric($params['count']) || $params['count'] > 100) {
- $params['count'] = 100;
- }
- if (!is_numeric($params['offset'])) {
- $params['offset'] = 0;
- }
- if ($params['deal_id']) {
- $query['deal_id'] = new MongoID($params['deal_id']);
- }
- $collection = Yii::app()->edmsMongoCollection('deals_live');
- if ($params['count'] && $params['offset']) {
- $liveDeals = $collection->find($query)->skip($params['offset'])->limit($params['count']);
- } else {
- $deals = $collection->find($query);
- //print_r($deals); exit;
- }
- $parsedDeals = array();
- if ($deals) {
- foreach ($deals as $deal) {
- $object = new stdClass;
- $object->live_id = $deal['_id']->__toString();
- $object->id = $deal['deal_id']->__toString();
- $object->type = $deal['type'];
- $object->title = $deal['title'];
- $object->description = $deal['description'];
- $object->start_date = $deal['start_date'];
- $object->end_date = $deal['end_date'];
- $object->visibility = $deal['visibility'];
- $object->status = self::formatStatus($deal['status']);
- if ($deal['owner']['type'] == "community") {
- $community = Communities::model()->findByPk($deal['owner']['id']);
- if ($community) {
- $owner = new stdClass;
- $owner->id = $community->id;
- $owner->name = $community->community_name;
- $owner->type = "community";
- }
- } else {
- $user = Users::model()->findByPk($deal['owner']['id']);
- if ($user) {
- $owner = new stdClass;
- $owner->id = $user->id;
- $owner->name = $user->user_firstname . " " . $user->user_lastname;
- $owner->type = "user";
- }
- }
- $object->owner = $owner;
- $object->userinfo = $deal['userinfo'];
- $object->dealinfo = $deal['dealinfo'];
- $member_details = Communities::getMemberRoleType($deal['owner']['id'], $deal['userinfo']['id']);
- if (count($member_details) > 0 && count($object->userinfo) > 0) {
- $object->userinfo = array_merge($object->userinfo, $member_details);
- }
- $object->taken_date = date("Y-m-d H:i:s", $deal['_id']->getTimestamp());
- $parsedDeals[] = $object;
- }
- }
- return $parsedDeals;
- }
- public static function searchInLiveDeals($params) {
- if (!is_numeric($params['count']) || $params['count'] > 100) {
- $params['count'] = 100;
- }
- if (!is_numeric($params['offset'])) {
- $params['offset'] = 0;
- }
- if ($params['id']) {
- $query['_id'] = new MongoID($params['id']);
- }
- if ($params['user_id']) {
- $query['user_id'] = intval($params['user_id']);
- }
- if ($params['owner_id']) {
- $query['owner.id'] = intval($params['owner_id']);
- }
- $collection = Yii::app()->edmsMongoCollection('deals_live');
- if ($params['count'] && $params['offset']) {
- $liveDeals = $collection->find($query)->skip($params['offset'])->limit($params['count']);
- } else {
- $deals = $collection->find($query);
- //print_r($deals); exit;
- }
- $parsedDeals = array();
- if ($deals) {
- foreach ($deals as $deal) {
- $object = new stdClass;
- $object->live_id = $deal['_id']->__toString();
- $object->id = $deal['deal_id']->__toString();
- $object->type = $deal['type'];
- $object->title = $deal['title'];
- $object->description = $deal['description'];
- $object->start_date = $deal['start_date'];
- $object->end_date = $deal['end_date'];
- $object->visibility = $deal['visibility'];
- $object->status = self::formatStatus($deal['status']);
- // ticket details
- if ($deal['type'] == 'ticket') {
- if ($deal['price']) {
- $total_category = count($deal['price']['options']);
- }
- if ($deal['purchasedTickets']) {
- $price_type = $deal['price']['type'];
- if ($deal['price']['type'] == 'tPoints') {
- $price_type = 'TAG Points';
- } else {
- $price_type = WalletTypes::getWalletName($deal['price']['wallet_id'], true);
- }
- if ($deal['purchasedTickets']['tickets']) {
- $i = 0;
- foreach ($deal['purchasedTickets']['tickets'] as $ticket) {
- $index = $deal['purchasedTickets']['tickets'][$i]['index'];
- $deal['purchasedTickets']['tickets'][$i]['price'] = $deal['price']['options'][$index]['price'] . " " . $price_type;
- unset($deal['purchasedTickets']['tickets'][$i]['index']);
- $i++;
- }
- }
- $object->tickets = $deal['purchasedTickets'];
- }
- }
- if ($deal['owner']['type'] == "community") {
- $community = Communities::model()->findByPk($deal['owner']['id']);
- if ($community) {
- $owner = new stdClass;
- $owner->id = $community->id;
- $owner->name = $community->community_name;
- $owner->type = "community";
- }
- } else {
- $user = Users::model()->findByPk($deal['owner']['id']);
- if ($user) {
- $owner = new stdClass;
- $owner->id = $user->id;
- $owner->name = $user->user_firstname . " " . $user->user_lastname;
- $owner->type = "user";
- }
- }
- $object->owner = $owner;
- $object->userinfo = $deal['userinfo'];
- $object->dealinfo = $deal['dealinfo'];
- $object->rewardinfo = $deal['rewardinfo'];
- $member_details = Communities::getMemberRoleType($deal['owner']['id'], $deal['userinfo']['id']);
- if (count($member_details) > 0 && count($object->userinfo) > 0) {
- $object->userinfo = array_merge($object->userinfo, $member_details);
- }
- $object->taken_date = date("Y-m-d H:i:s", $deal['_id']->getTimestamp());
- $parsedDeals[] = $object;
- }
- }
- return $parsedDeals;
- }
- public static function getDealsOfAllCommunities($params) {
- $communities = $params['userObj']->getCommunitiesUserIsMemberOf();
- $communityIds = array();
- if ($communities) {
- foreach ($communities as $community) {
- $communityIds[] = intval($community['community_id']);
- }
- }
- if (!is_numeric($params['count']) || $params['count'] > 100) {
- $params['count'] = 100;
- }
- if (!is_numeric($params['offset'])) {
- $params['offset'] = 0;
- }
- $query['owner.id'] = array('$in' => $communityIds);
- $query['owner.type'] = "community";
- $query['status'] = 1;
- //search
- if ($params['title']) {
- $query['title'] = array('$regex' => $params['title'], '$options' => 'i');
- }
- $collection = Yii::app()->edmsMongoCollection('deals');
- $deals = $collection->find($query)->skip($params['offset'])->limit($params['count']);
- $parsedDeals = array();
- if ($deals) {
- foreach ($deals as $deal) {
- $parsedDeals[] = self::formatDeal($deal);
- }
- }
- return $parsedDeals;
- }
- /*
- * * deals - end of list
- */
- /*
- * * deals - details
- */
- public function getDealDetails($dealId, $isStaff = false, $affiliateId = NULL) {
- $collection = Yii::app()->edmsMongoCollection('deals');
- $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
- $update = false;
- if ($isStaff) {
- if ($this->communityId) {
- $deal = $collection->findOne(array(
- "_id" => new MongoID($dealId),
- "owner.id" => intval($this->communityId),
- "owner.type" => "community"
- ));
- $role = CommunityUsers::getRoleOfUser($this->userId, $this->communityId);
- } else {
- //future development
- $deal = $collection->findOne(array(
- "_id" => new MongoID($dealId),
- "owner.id" => intval($this->userId),
- "owner.type" => "community"
- ));
- }
- } else {
- $deal = $collection->findOne(array(
- "_id" => new MongoID($dealId),
- ));
- //check whether the user is permitted view the details
- $views = array();
- if ($views = $deal['roles']['view']) {
- if (sizeof($views) > 0) {
- $role_id = CommunityUsers::getRoleOfUser($this->userId, $deal['owner']['id'])->role_id;
- if (!in_array($role_id, $views)) {
- throw new CHttpException(403, "permission_denied");
- }
- }
- }
- }
- if ($deal) {
- if (CommunityUsers::isStaffOf($this->userId, $deal['owner']['id']))
- $isStaff = true;
- $object = self::formatDeal($deal, $isStaff);
- if ($isStaff) {
- $object->can_assign = false;
- if ($deal['status'] == 1 &&
- ( ($role->role_type == 1) ||
- (in_array($role->role_id, $deal['roles']['assign'])) )) {
- $object->can_assign = true;
- }
- $object->live_deals_count = $liveCollection->find(array(
- "deal_id" => new MongoID($dealId)
- ))->count();
- } else {
- //check for cost_per_view. if exists, and if user not visited
- //earlier then deduct cost_per_view from merchants account and add user_id in deal_info
- $liveDeal = $liveCollection->findOne(array(
- "deal_id" => new MongoID($dealId),
- "user_id" => intval($this->userId)
- ));
- if ($deal['cost_per_view']['amount'] > 0) {
- if (!is_array($deal['dealinfo']['visitors'])) {
- $deal['dealinfo']['visitors'] = array();
- }
- if (!in_array($this->userId, $deal['dealinfo']['visitors']) && !$liveDeal) {
- if ($deal['cost_per_view']['amount'] > 0 && $deal['cost_per_view']['ad_balance'] < $deal['cost_per_view']['amount'])
- throw new CHttpException(403, "tagvert_no_longer_valid");
- //deduct cost_per_view from ad_balance
- $update = true;
- $ad_balance = $deal['cost_per_view']['ad_balance'] - $deal['cost_per_view']['amount'];
- $ad_balance = $ad_balance > 0 ? $ad_balance : 0;
- $updateArray = array("cost_per_view.ad_balance" => $ad_balance);
- //add switch to 0 if balance becomes 0
- if ($ad_balance == 0 || $ad_balance < $deal['cost_per_view']['amount']) {
- $updateArray['switch'] = 0;
- }
- }
- }
- if ($liveDeal) {
- $object->userinfo = $liveDeal['userinfo'];
- $object->userinfo['status'] = self::formatStatus($liveDeal['status']);
- $object->userinfo['taken_date'] = date("Y-m-d H:i:s", $liveDeal['_id']->getTimestamp());
- //can take_action (add stamp)
- if ($liveDeal['type'] == "stamp") {
- $object->can_take_action = false;
- if (($liveDeal['status'] == 1) && ($liveDeal['dealinfo']['take_action'])) {
- $object->can_take_action = true;
- }
- }
- //can redeem
- $object->can_redeem = false;
- if (($liveDeal['status'] == 3) && ($liveDeal['rewardinfo']['self_redeem'])) {
- $object->can_redeem = true;
- }
- if ($liveDeal['type'] == "ticket") {
- if ($liveDeal['purchasedTickets'])
- $object->purchasedTickets = $liveDeal['purchasedTickets'];
- }
- }
- else {
- $object->take = Deals::checkIfUserCanTakeDeal($deal, $this->userId, $affiliateId);
- }
- }
- $object->user_deal_details = $this->getCurrentDealStatus($dealId, $affiliateId);
- //update ad balance if any (cost_per_view)
- if ($update) {
- $deal['dealinfo']['visitors'][] = $this->userId;
- $updateArray['dealinfo']['visitors'] = $deal['dealinfo']['visitors'];
- $collection->update(
- array("_id" => new MongoID($dealId)), array('$set' => $updateArray)
- );
- }
- return $object;
- } else {
- throw new CHttpException(403, "invalid_dealid");
- }
- }
- public function getLiveDealDetails($dealId = NULL, $dealUserId = NULL) {
- if (!$dealId) {
- $dealId = $this->dealId;
- }
- if (!$dealUserId) {
- $dealUserId = $this->userId;
- }
- $roleDetails = CommunityUsers::getRoleOfUser($dealUserId, $this->communityId);
- $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
- $liveDeal = $liveCollection->findOne(array(
- "deal_id" => new MongoID($dealId),
- "user_id" => intval($dealUserId)
- ));
- if ($liveDeal) {
- $object = new stdClass;
- $object->deal_id = $liveDeal['deal_id']->__toString();
- $object->userinfo = $liveDeal['userinfo'];
- $object->dealinfo = $liveDeal['dealinfo'];
- $object->roles = $liveDeal['roles'];
- if (strtotime(date('Y-m-d')) > strtotime($liveDeal['end_date']))
- $object->status = self::formatStatus(2);
- else
- $object->status = self::formatStatus($liveDeal['status']);
- $object->userinfo['status'] = self::formatStatus($liveDeal['status']);
- $object->userinfo['taken_date'] = date("Y-m-d H:i:s", $liveDeal['_id']->getTimestamp());
- //can take action (add stamp)
- if ($liveDeal['type'] == "stamp") {
- $object->can_take_action = false;
- if ($liveDeal['status'] == 1) {
- if ($roleDetails->role_type == 1) {
- //if owner
- $object->can_take_action = true;
- } else if ($roleDetails->role_type == 2) {
- //If a staff member is trying to take action
- if (in_array($roleDetails->role_id, $liveDeal['roles']['redeem'])) {
- $object->can_take_action = true;
- }
- } else {
- //if member
- if ($liveDeal['dealinfo']['take_action']) {
- $object->can_take_action = true;
- }
- }
- }
- }
- //show ticket and transaction details
- if ($liveDeal['type'] == "ticket") {
- if ($liveDeal['price']) {
- $object->price = $liveDeal['price'];
- }
- if ($liveDeal['purchasedTickets']) {
- $object->purchasedTickets = $liveDeal['purchasedTickets'];
- }
- if ($liveDeal['scanCount']) {
- $object->scanCount = $liveDeal['scanCount'];
- }
- if ($liveDeal['scanSchedule']) {
- $object->scanSchedule = $liveDeal['scanSchedule'];
- }
- }
- if ($liveDeal['price']) {
- $object->price = $liveDeal['price'];
- }
- $object->owner = $liveDeal['owner'];
- //can redeem
- $object->can_redeem = false;
- if ($liveDeal['status'] == 3) {
- if ($roleDetails->role_type == 1) {
- //if owner
- $object->can_redeem = true;
- } else if ($roleDetails->role_type == 2) {
- //if staff
- if (in_array($roleDetails->role_id, $liveDeal['roles']['redeem'])) {
- $object->can_redeem = true;
- }
- } else {
- //if member
- if ($liveDeal['rewardinfo']['self_redeem']) {
- $object->can_redeem = true;
- }
- }
- }
- return $object;
- } else {
- return false;
- }
- }
- /*
- * * deals - end of details
- */
- /*
- * * deals - sub functions
- */
- //live deal info of a user: for updates
- public static function liveDealInfo($dealId, $userId) {
- $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
- $dealDetails = $liveCollection->findOne(array("deal_id" => new MongoID($dealId), "user_id" => intval($userId)));
- if ($dealDetails) {
- $object = new stdClass;
- $object->_id = $dealDetails['_id'];
- $object->deal_id = $dealDetails['deal_id'];
- $object->type = $dealDetails['type'];
- $object->status = $dealDetails['status'];
- $object->title = $dealDetails['title'];
- $object->description = $dealDetails['description'];
- $object->hiddenDescription = $dealDetails['hiddenDescription'];
- $object->town = $dealDetails['town'];
- $object->city = $dealDetails['city'];
- $object->zipCode = $dealDetails['zipCode'];
- $object->country = $dealDetails['country'];
- $object->tags = $dealDetails['tags'];
- $object->auto = $dealDetails['auto'];
- $object->visibility = $dealDetails['visibility'];
- $object->dealinfo = $dealDetails['dealinfo'];
- $object->owner = $dealDetails['owner'];
- $object->start_date = $dealDetails['start_date'];
- $object->end_date = $dealDetails['end_date'];
- $object->total_value = $dealDetails['total_value'];
- $object->credit_type = $dealDetails['credit_type'];
- $object->date_taken = $dealDetails['date_taken'];
- $object->date_redeemed = $dealDetails['date_redeemed'];
- $object->module = $dealDetails['module'];
- $object->limits = $dealDetails['limits'];
- $object->roles = $dealDetails['roles'];
- $object->user_id = $dealDetails['user_id'];
- $object->userinfo = $dealDetails['userinfo'];
- if ($dealDetails['scanCount']) {
- $object->scanCount = $dealDetails['scanCount'];
- }
- if ($dealDetails['scanSchedule']) {
- $object->scanSchedule = $dealDetails['scanSchedule'];
- }
- if ($dealDetails['pickupAddress']) {
- $object->pickUpAddress = $dealDetails['pickupAddress'];
- }
- if ($dealDetails['methodOfPayment']) {
- $object->methodOfPayment = $dealDetails['methodOfPayment'];
- }
- if ($dealDetails['assigner_id']) {
- $object->assigner_id = $dealDetails['assigner_id'];
- }
- if ($dealDetails['price']) {
- $object->price = $dealDetails['price'];
- }
- if ($dealDetails['affiliate_fee']) {
- $object->affiliate_fee = $dealDetails['affiliate_fee'];
- }
- if ($dealDetails['rewardinfo']) {
- $object->rewardinfo = $dealDetails['rewardinfo'];
- }
- if ($dealDetails['purchasedTickets']) {
- $object->purchasedTickets = $dealDetails['purchasedTickets'];
- }
- if ($dealDetails['affiliate_info']) {
- $object->affiliate_info = $dealDetails['affiliate_info'];
- }
- if ($dealDetails['type'] == "ticket" && $dealDetails['dealinfo']['ticket_type'] == 2) {
- $object->rsvp = $dealDetails['rsvp'];
- }
- return $object;
- }
- }
- //deal info: for various updates
- public static function dealInfo($dealId) {
- $collection = Yii::app()->edmsMongoCollection('deals');
- $dealDetails = $collection->findOne(array("_id" => new MongoID($dealId)));
- if ($dealDetails) {
- if ($dealDetails['dealinfo']['event_type']) {
- //expired deals
- if ($dealDetails['status'] != 4 && $dealDetails['status'] != 5 && $dealDetails['status'] != 6) {
- $event_date = ($dealDetails['dealinfo']['event_type'] == 1) ? $dealDetails['dealinfo']['event_date'] : $dealDetails['dealinfo']['end_event_date'];
- if (strtotime($event_date) < strtotime(date('Y-m-d'))) {
- $collection->update(
- array("_id" => new MongoID($dealId)), array('$set' => array("status" => 2))
- );
- }
- }
- }
- $dealDetails = $collection->findOne(array("_id" => new MongoID($dealId)));
- $object = new stdClass;
- $object->id = $dealId;
- $object->status = $dealDetails['status'];
- $object->type = $dealDetails['type'];
- $object->title = $dealDetails['title'];
- $object->description = $dealDetails['description'];
- $object->hiddenDescription = $dealDetails['hiddenDescription'];
- $object->town = $dealDetails['town'];
- $object->city = $dealDetails['city'];
- $object->zipCode = $dealDetails['zipCode'];
- $object->country = $dealDetails['country'];
- $object->tags = $dealDetails['tags'];
- $object->auto = $dealDetails['auto'];
- $object->visibility = $dealDetails['visibility'];
- $object->dealinfo = $dealDetails['dealinfo'];
- $object->owner = $dealDetails['owner'];
- $object->start_date = $dealDetails['start_date'];
- $object->end_date = $dealDetails['end_date'];
- $object->total_value = $dealDetails['total_value'];
- $object->credit_type = $dealDetails['credit_type'];
- $object->module = $dealDetails['module'];
- $object->limits = $dealDetails['limits'];
- $object->roles = $dealDetails['roles'];
- $tracker = ($dealDetails['tracker']) ? $dealDetails['tracker'] : uniqid() . rand(10 * 45, 100 * 98);
- if (!$dealDetails['tracker']) {
- $collection->update(
- array("_id" => new MongoID($dealId),), array('$set' => array("tracker" => $tracker))
- );
- }
- $object->tracker = $tracker;
- if ($dealDetails['reportDeactivated'])
- $object->reportDeactivated = $dealDetails['reportDeactivated'];
- if ($dealDetails['methodOfPayment'])
- $object->methodOfPayment = $dealDetails['methodOfPayment'];
- if ($dealDetails['digitalDelivery'])
- $object->digitalDelivery = $dealDetails['digitalDelivery'];
- if ($dealDetails['pickUpAddress'])
- $object->pickUpAddress = $dealDetails['pickUpAddress'];
- if ($dealDetails['price'])
- $object->price = $dealDetails['price'];
- if ($dealDetails['multiDelivery'])
- $object->multiDelivery = $dealDetails['multiDelivery'];
- if ($dealDetails['referralTypeOption'])
- $object->referralTypeOption = $dealDetails['referralTypeOption'];
- if ($dealDetails['affiliate_fee'])
- $object->affiliate_fee = $dealDetails['affiliate_fee'];
- if ($dealDetails['rewardinfo'])
- $object->rewardinfo = $dealDetails['rewardinfo'];
- if ($dealDetails['gallery'])
- $object->gallery = $dealDetails['gallery'];
- if ($dealDetails['sharedVisitCount'])
- $object->sharedVisitCount = $dealDetails['sharedVisitCount'];
- if ($dealDetails['sharedBookmarkCount'])
- $object->sharedBookmarkCount = $dealDetails['sharedBookmarkCount'];
- if ($dealDetails['sharedDiscardCount'])
- $object->sharedDiscardCount = $dealDetails['sharedDiscardCount'];
- if ($dealDetails['sharedTakeCount'])
- $object->sharedTakeCount = $dealDetails['sharedTakeCount'];
- if ($dealDetails['sharedRedeemCount'])
- $object->sharedRedeemCount = $dealDetails['sharedRedeemCount'];
- if ($dealDetails['sharedReferral'])
- $object->sharedReferral = $dealDetails['sharedReferral'];
- if ($dealDetails['bankDeposit'])
- $object->bankDeposit = $dealDetails['bankDeposit'];
- if ($dealDetails['sharedSales'])
- $object->sharedSales = $dealDetails['sharedSales'];
- if ($dealDetails['scanCount'])
- $object->scanCount = $dealDetails['scanCount'];
- if ($dealDetails['scanSchedule'])
- $object->scanSchedule = $dealDetails['scanSchedule'];
- return $object;
- }
- }
- public static function getValueOfDeal($dealId = NULL, $deal = NULL) {
- $collection = Yii::app()->edmsMongoCollection('deals');
- if (!$deal) {
- $deal = $collection->findOne(array("_id" => new MongoID($dealId)));
- }
- if (!$deal) {
- return false;
- } else {
- $result = array(
- 'amount' => 0.00,
- 'type' => '',
- );
- if ($deal['rewardinfo']['type'] == 'reward' || $deal['rewardinfo']['type'] == 'points') {
- $result['type'] = 'reward';
- $result['amount'] = $data['rewardinfo']['amount'];
- } else if ($deal['rewardinfo']['type'] == 'wallet') {
- $result['type'] = 'wallet';
- $result['amount'] = $data['rewardinfo']['amount'];
- }
- $result;
- }
- }
- public static function countAllDealsOfACommunity($communityId) {
- $collection = Yii::app()->edmsMongoCollection('deals');
- $dealCount = $collection->find(array("owner.id" => intval($communityId), "owner.type" => "community", "status" => intval(1)))->count();
- return $dealCount;
- }
- public static function countAllDealsOfAUser($userId) {
- $collection = Yii::app()->edmsMongoCollection('deals');
- $dealCount = $collection->find(array("owner.id" => intval($userId), "owner.type" => "user"))->count();
- return $dealCount;
- }
- public static function countTimesTaken($dealId, $includeHistory = false, $userId = NULL) {
- $collection = Yii::app()->edmsMongoCollection('deals_live');
- $historyCollection = Yii::app()->edmsMongoCollection('deals_history');
- if ($userId) {
- $dealCount = $collection->find(array('deal_id' => new MongoID($dealId), 'user_id' => intval($userId)))->count();
- if ($includeHistory) {
- $dealCount += $historyCollection->find(array('deal_id' => new MongoID($dealId), 'user_id' => intval($userId)))->count();
- }
- } else {
- $dealCount = $collection->find(array('deal_id' => new MongoID($dealId)))->count();
- if ($includeHistory) {
- $dealCount += $historyCollection->find(array('deal_id' => new MongoID($dealId)))->count();
- }
- }
- return $dealCount;
- }
- public static function countTimesTakenPerDay($dealId) {
- $collection = Yii::app()->edmsMongoCollection('deals_live');
- $historyCollection = Yii::app()->edmsMongoCollection('deals_history');
- $dealCount = $collection->find(array("deal_id" => new MongoID($dealId), 'date_taken' => date('Y-m-d')))->count();
- if ($includeHistory) {
- $dealCount += $historyCollection->find(array('deal_id' => new MongoID($dealId), 'date_taken' => date('Y-m-d')))->count();
- }
- return $dealCount;
- }
- public function validateMongoId() {
- $regex = '/^[0-9a-z]{24}$/';
- if (preg_match($regex, $this->dealId)) {
- return true;
- }
- return false;
- }
- public function updatePromised($deal, $minus = false) {
- //convert object to array
- if (is_object($deal)) {
- $deal = (array) $deal;
- }
- if ($deal['owner']['id']) {
- $comunityid = $deal['owner']['id'];
- } else if ($this->communityId) {
- $comunityid = $this->communityId;
- }
- //fetching for affiliate
- $query = array();
- $balanceForAffiliate = NULL;
- if ($deal['affiliate_fee'] && is_array($deal['affiliate_fee'])) {
- if ($deal['affiliate_fee']['type'] == 'reward' && $deal['affiliate_fee']['amount'] && $deal['affiliate_fee']['wallet_id']) {
- //fetching query
- $query['balance_id'] = $deal['owner']['id'];
- if ($deal['owner']['type'] == 'community') {
- $query['balance_type'] = 2;
- } else if ($deal['owner']['type'] == 'user') {
- $query['balance_type'] = 1;
- } else {
- $this->internalError('pay affiliate fee', NULL, 'affiliate');
- }
- $query['wallet_type_id'] = $deal['affiliate_fee']['wallet_id'];
- //fetching balance
- $balanceForAffiliate = WalletBalances::model()->findByAttributes($query);
- //validating
- if (!$minus) {
- if (!$balanceForAffiliate) {
- throw new CHttpException(403, "insufficient_balance");
- }
- $balanceForAffiliate->balance_promised += $deal['affiliate_fee']['amount'];
- if (!$balanceForAffiliate->validate()) {
- throw new CHttpException(403, "insufficient_balance");
- }
- } else {
- if (!$balanceForAffiliate) {
- $this->internalError('pay affiliate fee', $balanceForAffiliate, 'affiliate');
- }
- $balanceForAffiliate->balance_promised -= $deal['affiliate_fee']['amount'];
- if (!$balanceForAffiliate->validate()) {
- $this->internalError('pay affiliate fee', $balanceForAffiliate, 'affiliate');
- }
- }
- }
- /* if($deal['affiliate_fee']['type'] == 'reward'
- && $deal['affiliate_fee']['amount']){
- $balanceForAffiliate = Communities::model()->findByPk($comunityid);
- if(!$minus){
- if(($balanceForAffiliate->community_credits-$balanceForAffiliate->community_promised_credits)<$deal['affiliate_fee']['amount']){
- throw new CHttpException(403,"insufficient_balance");
- }
- else{
- $balanceForAffiliate->community_promised_credits += $deal['affiliate_fee']['amount'];
- }
- }
- else{
- $balanceForAffiliate->community_promised_credits -= $deal['affiliate_fee']['amount'];
- }
- } */
- }
- //fetching for reward
- $query = array();
- $balanceForReward = NULL;
- if ($deal['rewardinfo']['type'] == 'wallet' && $deal['rewardinfo']['amount'] && $deal['rewardinfo']['wallet_id']) {
- //fetching query
- $query = array();
- $query['balance_id'] = $deal['owner']['id'];
- if ($deal['owner']['type'] == 'community') {
- $query['balance_type'] = 2;
- } else if ($deal['owner']['type'] == 'user') {
- $query['balance_type'] = 1;
- } else {
- $this->internalError('reward using wallet', NULL, 'reward');
- }
- $query['wallet_type_id'] = $deal['rewardinfo']['wallet_id'];
- //fetching balance
- if ($balanceForAffiliate && $balanceForAffiliate->wallet_type_id == $query['wallet_type_id']) {
- $balanceForReward = $balanceForAffiliate;
- } else {
- $balanceForReward = WalletBalances::model()->findByAttributes($query);
- }
- //validating
- if (!$minus) {
- if (!$balanceForReward) {
- throw new CHttpException(403, "insufficient_balance");
- }
- $balanceForReward->balance_promised += $deal['rewardinfo']['amount'];
- if (!$balanceForReward->validate()) {
- throw new CHttpException(403, "insufficient_balance");
- }
- } else {
- if (!$balanceForReward) {
- $this->internalError('reward using wallet', $balanceForReward, 'reward');
- }
- $balanceForReward->balance_promised -= $deal['rewardinfo']['amount'];
- if (!$balanceForReward->validate()) {
- $this->internalError('reward using wallet', $balanceForReward, 'reward');
- }
- }
- //Common::pre($deal['rewardinfo'], true);
- } else if ($deal['rewardinfo']['type'] == 'reward' && $deal['rewardinfo']['amount']) {
- $balanceForReward = Communities::model()->findByPk($comunityid);
- if (!$minus) {
- if (($balanceForReward->community_credits - $balanceForReward->community_promised_credits) < $deal['rewardinfo']['amount']) {
- throw new CHttpException(403, "insufficient_balance");
- } else {
- $balanceForReward->community_promised_credits += $deal['rewardinfo']['amount'];
- }
- } else {
- $balanceForReward->community_promised_credits -= $deal['rewardinfo']['amount'];
- }
- }
- //committing
- if ($balanceForAffiliate) {
- $balanceForAffiliate->save();
- }
- if ($balanceForReward) {
- if ($deal['rewardinfo']['type'] == 'wallet') {
- if ($balanceForAffiliate &&
- ($balanceForAffiliate->wallet_type_id == $balanceForReward->wallet_type_id)) {
- //return true;
- } else {
- $balanceForReward->save();
- }
- } else if ($deal['rewardinfo']['type'] == 'reward') {
- $balanceForReward->save();
- }
- }
- //Common::pre($deal, true);
- return true;
- }
- // depreciated
- public static function getAllDealsOfACommunity($communityId, $status = NULL, $publicOnly = false) {
- $deal = new Deals;
- $filter = array();
- $filter['communityId'] = $communityId;
- if ($status) {
- $filter['status'] = $status;
- }
- if ($publicOnly) {
- $filter['visibility'] = 'public';
- }
- //print_r($filter);exit;
- return $deal->searchDeals($filter);
- }
- // need to organise below
- public static function userAccess($live_deal_id, $mode, $date, $time) {
- $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
- $liveDeal = $liveCollection->findOne(array("_id" => new MongoId($live_deal_id)));
- $accessList = $liveDeal['access_info'];
- $accessList[count($liveDeal['access_info'])] = array($mode, $date, $time);
- $liveCollection->update(array(
- "_id" => new MongoID($live_deal_id)
- ), array('$set' => array("access_info" => $accessList)));
- return "transaction_saved";
- }
- public static function listAccess($live_deal_id, $user) {
- $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
- $liveDeal = $liveCollection->findOne(array("_id" => new MongoId($live_deal_id), "user_id" => intval($user)));
- //count access data
- $count = count($liveDeal['access_info']);
- if ($count > 0) {
- $liveDeal['access_info'] = array_reverse($liveDeal['access_info']);
- $object = new stdClass;
- $object->access_data = $liveDeal['access_info'];
- return $object;
- } else {
- return "access_info_empty";
- }
- }
- public static function listAccessTagverts($user_id, $communityId) {
- $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
- $liveDeals = $liveCollection->find(array("user_id" => intval($user_id), "type" => "access", "owner.id" => intval($communityId)));
- $parsedDeals = array();
- foreach ($liveDeals as $key => $deal) {
- $object = new stdClass;
- $object->id = $deal['_id']->__toString();
- $object->title = $deal['title'];
- $parsedDeals[] = $object;
- }
- return $parsedDeals;
- }
- public static function validateTransfer($live_deal_id, $target, $sender) {
- $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
- $deal_to_transfer = $liveCollection->findOne(array("_id" => new MongoID($live_deal_id)));
- if (is_numeric($target) == 1) {
- $user = Users::model()->findByPk($target);
- if ($user) {
- $email = $user->user_email;
- $member = CommunityUsers::model()->findByAttributes(array("user_id" => $user->id, "community_id" => $deal_to_transfer['owner']['id']));
- if ($member) {
- $checkIfMemberRole = CommunityUsers::getRoleOfUser($user->id, $deal_to_transfer['owner']['id']);
- if ($checkIfMemberRole->role_type == 3) {
- $checkIfAlreadyTaken = $liveCollection->findOne(array("deal_id" => new MongoID($deal_to_transfer['deal_id']), "user_id" => intval($user->id)));
- if ($checkIfAlreadyTaken) {
- if (((string) $checkIfAlreadyTaken['_id']) != ((string) $live_deal_id)) {
- return "user_already_own_this_reward";
- } else {
- return "tagvert_already_taken";
- }
- } else {
- $transfer_info = array(
- "user_email" => $email
- );
- $liveCollection->update(array(
- "_id" => new MongoID($live_deal_id)
- ), array('$set' => array("tagvert_transfer_info" => $transfer_info)));
- return "transfer_to_member_ok";
- }
- } else {
- return "not_member_role";
- }
- } else {
- $transfer_info = array(
- "user_email" => $email
- );
- $stat = $liveCollection->update(array(
- "_id" => new MongoID($live_deal_id)
- ), array('$set' => array("tagvert_transfer_info" => $transfer_info)));
- return "transfer_to_non_member_ok";
- }
- } else {
- return "invalid_id";
- }
- } else {
- $user = Users::model()->findByAttributes(array("user_email" => $target));
- if ($user) {
- $email = $user->user_email;
- $member = CommunityUsers::model()->findByAttributes(array("user_id" => $user->id, "community_id" => $deal_to_transfer['owner']['id']));
- if ($member) {
- $checkIfMemberRole = CommunityUsers::getRoleOfUser($user->id, $deal_to_transfer['owner']['id']);
- if ($checkIfMemberRole->role_type == 3) {
- $checkIfAlreadyTaken = $liveCollection->findOne(array("deal_id" => new MongoID($deal_to_transfer['deal_id']), "user_id" => intval($user->id)));
- if ($checkIfAlreadyTaken) {
- return "tagvert_already_taken";
- } else {
- $transfer_info = array(
- "user_email" => $email
- );
- $liveCollection->update(array(
- "_id" => new MongoID($live_deal_id)
- ), array('$set' => array("tagvert_transfer_info" => $transfer_info)));
- return "transfer_to_member_ok";
- }
- } else {
- return "not_member_role";
- }
- } else {
- $transfer_info = array(
- "user_email" => $email
- );
- $liveCollection->update(array(
- "_id" => new MongoID($live_deal_id)
- ), array('$set' => array("tagvert_transfer_info" => $transfer_info)));
- return "transfer_to_non_member_ok";
- }
- } else {
- $email_transfer = Deals::sendTagvertTransfer($target, $live_deal_id, $sender);
- return $email_transfer;
- }
- }
- }
- public static function sendTagvertTransfer($email, $liveTagvert, $user_id) {
- $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
- $settings = array(
- 'view' => 'tagvertTransfer',
- 'subject' => "Someone wants to give a tagvert to you!",
- );
- $sender = Users::model()->findByPk($user_id);
- $dealData = $liveCollection->findOne(array("_id" => new MongoID($liveTagvert)));
- $mail = new YiiMailer();
- $mail->IsSMTP();
- $mail->Host = 'smtp.gmail.com';
- $mail->Port = 465;
- $mail->SMTPAuth = true;
- $mail->SMTPSecure = 'ssl';
- $mail->Username = Yii::app()->params['adminEmail'];
- $mail->Password = Yii::app()->params['adminEmailPassword'];
- $mail->setView('dealtransfer');
- $mail->setData(array(
- 'dealTitle' => $dealData['title'],
- 'sender' => $sender->user_firstname . ' ' . $sender->user_lastname,
- 'email' => $email
- ));
- $mail->render();
- $mail->From = Yii::app()->params['adminEmail'];
- $mail->FromName = Yii::app()->name;
- $mail->Subject = Yii::t('labels', Yii::t("labels", "Tagbond tagvert transfer"));
- $mail->AddAddress($contact->user_email);
- if ($mail->Send()) {
- $transfer_info = array(
- "user_email" => $email
- );
- $liveCollection->update(array(
- "_id" => new MongoID($liveTagvert)
- ), array('$set' => array("tagvert_transfer_info" => $transfer_info)));
- return "email_request_sent";
- } else {
- return "email_request_failed";
- }
- }
- public static function pendingTransfer($user_id) {
- $user = Users::model()->findByPk($user_id);
- $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
- $pending = $liveCollection->find(array("tagvert_transfer_info.user_email" => $user->user_email));
- $pending_deals = array();
- foreach ($pending as $key => $value) {
- $deal_id = $value['deal_id']->__toString();
- $deal_live_id = $value['_id']->__toString();
- $deal_title = $value['title'];
- $deal_owner_id = $value['user_id'];
- $deal_owner_name = $value['userinfo']['user_firstname'] . " " . $value['userinfo']['user_lastname'];
- array_push($pending_deals, array("deal_id" => $deal_id, "live_deal_id" => $deal_live_id, "title" => $deal_title, "owner_id" => $deal_owner_id, "owner_name" => $deal_owner_name));
- }
- return $pending_deals;
- }
- public static function acceptTransfer($liveDeal, $user_id) {
- $user = Users::model()->findByPk($user_id);
- $new_user_info = array('id' => intval($user_id), 'user_firstname' => $user->user_firstname, 'user_lastname' => $user->user_lastname);
- $transfer_info = array();
- $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
- $liveCollection->update(array(
- "_id" => new MongoID($liveDeal)
- ), array('$set' => array("tagvert_transfer_info" => $transfer_info, "user_id" => $user_id, "userinfo" => $new_user_info)));
- return "transfer_ok";
- }
- public static function removeTransfer($liveDeal) {
- $transfer_info = array();
- $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
- $liveCollection->update(array(
- "_id" => new MongoID($liveDeal)
- ), array('$set' => array("tagvert_transfer_info" => $transfer_info)));
- return "transfer_removed";
- }
- public function deactivateDeal() {
- if (!TagMongo::isValidId($this->dealId)) {
- throw new CHttpException(404, "invalid_deal_id");
- }
- $collection = Yii::app()->edmsMongoCollection('deals');
- $deal = $collection->findOne(array("_id" => new MongoID($this->dealId)));
- if ($deal) {
- if ($deal['status'] == 1) {
- $collection->update(
- array("_id" => new MongoID($this->dealId)), array('$set' => array("status" => 4))
- );
- return true;
- }
- return false;
- } else {
- throw new CHttpException(404, "invalid_deal_id");
- }
- }
- public function activateDeal() {
- if (!TagMongo::isValidId($this->dealId)) {
- throw new CHttpException(404, "invalid_deal_id");
- }
- $collection = Yii::app()->edmsMongoCollection('deals');
- $deal = $collection->findOne(array("_id" => new MongoID($this->dealId)));
- if ($deal) {
- if ($deal['status'] == 4) {
- $collection->update(
- array("_id" => new MongoID($this->dealId)), array('$set' => array("status" => 1))
- );
- return true;
- }
- return false;
- } else {
- throw new CHttpException(404, "invalid_deal_id");
- }
- }
- public function getCurrentDealStatus($dealId, $affiliateId = NULL) {
- $collection = Yii::app()->edmsMongoCollection('deals');
- $deal = $collection->findOne(array(
- "_id" => new MongoID($dealId),
- ));
- if ($deal) {
- $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
- $liveDeal = $liveCollection->findOne(array(
- "deal_id" => new MongoID($dealId),
- "user_id" => intval($this->userId)
- ));
- if ($liveDeal) {
- //can take_action (add stamp)
- if ($liveDeal['type'] == "stamp") {
- $user_deal_details['deal_status'] = 'can_not_take_action';
- $user_deal_details['message'] = '';
- if (($liveDeal['status'] == 1) && ($liveDeal['dealinfo']['take_action'])) {
- $user_deal_details['deal_status'] = 'can_take_action';
- $user_deal_details['message'] = '';
- }
- }
- //can redeem
- if (($liveDeal['status'] == 3) && ($liveDeal['rewardinfo']['self_redeem'])) {
- $user_deal_details['deal_status'] = 'can_redeem';
- }
- } else {
- $user_details = Deals::checkIfUserCanTakeDeal($deal, $this->userId, $affiliateId);
- if ($user_details->can_take == 1) {
- $user_deal_details['deal_status'] = 'can_take';
- } else {
- $user_deal_details['deal_status'] = 'can_not_take';
- $user_deal_details['message'] = $user_details->errors;
- }
- }
- $user_deal_details['deal_type'] = $deal['type'];
- return $user_deal_details;
- } else {
- return false;
- }
- }
- public function dealQRCodeAction($qr_code, $action_auto = false) {
- $collection = Yii::app()->edmsMongoCollection('deals_live');
- $deal = $collection->findOne(array("dealinfo.code" => intval($qr_code)));
- if ($deal) {
- $data['dealid'] = $deal['deal_id']->__toString();
- $data['type'] = $deal['type'];
- if ($deal['type'] == 'stamp') {
- if ($action_auto == 'auto') {
- $result = $this->takeAction($data['dealid'], $this->userId, NULL, $this->communityId);
- if ($result) {
- $data['status'] = $result;
- }
- }
- return $data;
- }
- throw new CHttpException(403, 'no_action_associated_for_this_tagvert');
- }
- throw new CHttpException(403, 'invalid_code');
- }
- public function getTypes() {
- $collection = Yii::app()->edmsMongoCollection('deals');
- $deal = $collection->distinct("type");
- return $deal;
- }
- public function getAdvertList($filter = array(), $params = array()) {
- $collection = Yii::app()->edmsMongoCollection('deals');
- // pagination
- if (isset($this->pageOffset) && (!is_numeric($this->pageOffset) || $this->pageOffset < 0)) {
- $this->pageOffset = 0;
- }
- if (isset($this->pageCount) && (!is_numeric($this->pageCount) || $this->pageCount < 0)) {
- $this->pageCount = 100;
- }
- //sorting
- if ($params['sort']) {
- $params['sort'] = intval($params['sort']);
- } else {
- $params['sort'] = -1;
- }
- $query = array();
- $query['visibility'] = 'public';
- if (is_array($filter['type'])) {
- //$query['type'] = $filter['type'];
- $query['type'] = array('$in' => $filter['type']);
- }
- if ($filter['status']) {
- if ($filter['status'] == 'expired') {
- $query['status'] = 2;
- } else if ($filter['status'] == 'disabled') {
- $query['status'] = 4;
- } else {
- $query['status'] = 1;
- }
- }
- if (is_array($filter['title'])) {
- //$query['title'] = array('$regex' => $filter['title'], '$options' => 'i');
- $query['title'] = array('$in' => $filter['title']);
- }
- if (is_array($filter['city'])) {
- //$query['city'] = array('$regex' => $filter['city'], '$options' => 'i');
- $query['city'] = array('$in' => $filter['city']);
- }
- if ($filter['country_id']) {
- $countryIds = array();
- foreach ($filter['country_id'] as $country) {
- $countryIds[] = intval($country);
- }
- $query['owner.id'] = array('$in' => $countryIds);
- //$query['country.id'] = intval($filter['country_id']);
- }
- if (is_array($filter['tags'])) {
- foreach ($filter['tags'] as $tag) {
- $tags[] = ucwords($tag);
- }
- $filter['tags'] = array_merge($filter['tags'], $tags);
- $query['tags'] = array('$in' => $filter['tags']);
- }
- //filter by owner
- if ($filter['community_id']) {
- $communityIds = array();
- foreach ($filter['community_id'] as $community) {
- $communityId[] = intval($community);
- }
- $query['owner.id'] = array('$in' => $communityId);
- $query['owner.type'] = 'community';
- }
- // executing query
- $deals = $collection->find($query)
- ->skip($this->pageOffset)
- ->limit($this->pageCount)
- ->sort(array("_id" => $params['sort']));
- // parsing the result
- $parsedDeals = array();
- $settings = SiteSettings::getSettings();
- if ($this->communityId) {
- $id = $this->communityId;
- $defaults = CommunityPreferences::model()->findByPk($id);
- } else {
- $id = $this->userId;
- $defaults = UserPreferences::model()->findByPk($id);
- }
- $wallet_id = $defaults['pref_wallet_id'] > 0 ? $defaults['pref_wallet_id'] : 1;
- $imageS3Path = 'uploads/tagverts';
- if ($deals) {
- $i = 0;
- foreach ($deals as $deal) {
- $dealId = $deal['_id']->__toString();
- $parsedDeals[$i]['title'] = $deal['title'];
- $parsedDeals[$i]['type'] = $deal['type'];
- $parsedDeals[$i]['description'] = $deal['description'];
- //$parsedDeals[$i]['url'] = $settings->site_url.'/d/'.$dealId.'?userId='.$id.'&wallet_id='.$wallet_id;
- $parsedDeals[$i]['url'] = 'http://www.tagbond.com/d/' . $dealId . '?userId=' . $id . '&wallet_id=' . $wallet_id;
- //get advert images
- if ($filter['image_type'] == 'base64') {
- $imageData = false;
- $imageS3Name = 'd_' . $deal['_id']->__toString() . '.png';
- $resultS3 = Yii::app()->tamazon->isObjectExist($imageS3Path, $imageS3Name);
- if ($resultS3) {
- $resultS3 = Yii::app()->tamazon->getObject($imageS3Path, $imageS3Name);
- $imageData = base64_encode($resultS3['Body']);
- }
- $parsedDeals[$i]['image'] = $imageData;
- } else {
- $parsedDeals[$i]['image_url'] = $settings->site_url . '/image/tagvert/' . $dealId;
- }
- $i++;
- }
- }
- return $parsedDeals;
- }
- public function avatarUpload($dealId, $imageData) {
- $imageData = base64_decode($imageData);
- if ($imageData) {
- if (UserImages::checkAws() && UserImages::getImageType($imageData)) {
- $collection_permission = Yii::app()->edmsMongoCollection('deals');
- $permitted = $collection_permission->findOne(array("_id" => new MongoId($dealId), "owner.id" => intval($this->communityId)));
- if (!$permitted)
- throw new CHttpException(403, "permission_denied");
- $imageData = UserImages::convertImage($imageData);
- if ($imageData) {
- //save original image to s3
- $imageName = 'd_' . $dealId . ".jpg";
- $imagePath = Yii::app()->params['uploadPath'] . '/avatars/';
- $imageS3Name = 'd_' . $dealId . '.png';
- $imageS3Path = 'uploads/tagverts';
- //save image
- $resultS3 = Yii::app()->tamazon->uploadObject($imageS3Path, $imageS3Name, $imageData);
- if (!$resultS3) {
- file_put_contents($imagePath . $imageName, $imageData);
- } else {
- //create thumb 1
- $imageData_thumb_1 = UserImages::imagesSizes($imageData, 50, 50);
- //save thumb 1
- $thumbnail_1 = Yii::app()->tamazon->uploadObject('uploads/tagverts/thumbnail_1', $imageName, $imageData_thumb_1);
- //create thumb 2
- $imageData_thumb_2 = UserImages::imagesSizes($imageData, 75, 75);
- //save thumb 2
- $thumbnail_2 = Yii::app()->tamazon->uploadObject('uploads/tagverts/thumbnail_2', $imageName, $imageData_thumb_2);
- //create thumb 3
- $imageData_thumb_3 = UserImages::imagesSizes($imageData, 150, 150);
- //save thumb 3
- $thumbnail_3 = Yii::app()->tamazon->uploadObject('uploads/tagverts/thumbnail_3', $imageName, $imageData_thumb_3);
- }
- return true;
- }
- }
- }
- return false;
- }
- public function checkPPTValidity($deal_id) {
- $dealCollection = Yii::app()->edmsMongoCollection('deals');
- $dealData = $dealCollection->findOne(array("_id" => new MongoID($deal_id)));
- $budget = $dealData['pay_per_take']['budget'];
- $return_data['amount'] = $dealData['pay_per_take']['amount'];
- $return_data['community_id'] = $dealData['owner']['id'];
- $return_data['wallet_id'] = $dealData['pay_per_take']['wallet_id'];
- if ($budget < $return_data['amount'])
- throw new CHttpException(403, "ppt_budget_reached");
- if ($dealData['pay_per_take']['type'] == 'reward') {
- $community = Communities::model()->findByPk();
- $community_balance = $community->community_credits;
- } else if ($dealData['pay_per_take']['type'] == 'wallet') {
- $wallet_balance = WalletBalances::getWalletBalance($dealData['owner']['id'], '2', $dealData['pay_per_take']['wallet_id']);
- $community_balance = $wallet_balance['amount'];
- }
- if ($return_data['amount'] > $community_balance)
- throw new CHttpException(403, "not_enough_community_balance_for_ppt");
- return $return_data;
- }
- public function getEventDetails($filter, $params) {
- $collection = Yii::app()->edmsMongoCollection('deals_live');
- // pagination
- if (isset($this->pageOffset) && (!is_numeric($this->pageOffset) || $this->pageOffset < 0)) {
- $this->pageOffset = 0;
- }
- if (isset($this->pageCount) && (!is_numeric($this->pageCount) || $this->pageCount < 0)) {
- $this->pageCount = 100;
- }
- //sorting
- if ($params['sort']) {
- $params['sort'] = intval($params['sort']);
- } else {
- $params['sort'] = -1;
- }
- $query = array();
- if ($filter['user_id']) {
- $query['user_id'] = intval($filter['user_id']);
- }
- if ($filter['deal_id']) {
- $query['deal_id'] = new MongoID($filter['deal_id']);
- }
- //$query['owner.id'] = intval($this->communityId);
- if ($filter['paid']) {
- $query['paid'] = $filter['paid'];
- }
- // executing query
- $deals = $collection->find($query)
- ->skip($this->pageOffset)
- ->limit($this->pageCount)
- ->sort(array("_id" => $params['sort']));
- // parsing the result
- $parsedDeals = array();
- if ($deals) {
- $i = 0;
- foreach ($deals as $deal) {
- $parsedDeals['title'] = $deal['title'];
- $parsedDeals['eventdetails'] = $deal['dealinfo'];
- $parsedDeals['tickets'][$i] = $deal['price'];
- $parsedDeals['userdetails'][$i][id] = $deal['userinfo']['id'];
- $parsedDeals['userdetails'][$i][user_firstname] = $deal['userinfo']['user_firstname'];
- $parsedDeals['userdetails'][$i][user_lastname] = $deal['userinfo']['user_lastname'];
- $parsedDeals['userdetails'][$i]['date_taken'] = $deal['date_taken'];
- $parsedDeals['userdetails'][$i]['tickets'] = $deal['purchasedTickets'];
- if ($filter['transactions'])
- $parsedDeals['userdetails'][$i]['transactionlist'] = $deal['purchasedTickets'];
- $i++;
- }
- }
- if (count($parsedDeals) == 0) {
- throw new CHttpException(404, "no_event_found");
- }
- return $parsedDeals;
- }
- public function markTransactionPaid($filter) {
- $collection = Yii::app()->edmsMongoCollection('deals_live');
- if ($filter['user_id'] && $filter['deal_id'] && $filter['transaction_id']) {
- $query['user_id'] = intval($filter['user_id']);
- $query['deal_id'] = new MongoID($filter['deal_id']);
- $query['owner.id'] = intval($this->communityId);
- $query['purchasedTickets.history.transaction_code'] = $filter['transaction_id'];
- }
- $deals = $collection->find($query);
- $payment_status = $filter['paid'] == 'yes' ? 'yes' : 'no';
- if ($deals) {
- foreach ($deals as $d) {
- $owner_id = $d['owner']['id'];
- $collection_id = $d['_id'];
- $deal['transaction'] = $d['purchasedTickets'];
- }
- }
- if (!count($deal)) {
- throw new CHttpException(403, "not_a_valid_transaction");
- }
- $array = $deal['transaction']['history'];
- $key = 'transaction_code';
- $value = $filter['transaction_id'];
- $count = count($array);
- for ($i = 0; $i < $count; $i++) {
- if (Deals::search_in_array($value, $array[$i])) {
- $found = $i;
- break;
- }
- }
- $collection->update(
- array("_id" => new MongoID($collection_id)), array('$set' => array("purchasedTickets.history.$found.paid" => $payment_status))
- );
- return $this->getTicketDetails($filter);
- }
- public function updateTicketsUsageStatus($filter) {
- $collection = Yii::app()->edmsMongoCollection('deals_live');
- if ($filter['ticket_id']) {
- $query['deal_id'] = new MongoID($filter['deal_id']);
- $query['user_id'] = intval($filter['user_id']);
- $query['owner.id'] = intval($this->communityId);
- $query['purchasedTickets.tickets.id'] = $filter['ticket_id'];
- }
- $deals = $collection->find($query);
- if ($deals) {
- foreach ($deals as $d) {
- $owner_id = $d['owner']['id'];
- $collection_id = $d['_id'];
- $deal['history'] = $d['purchasedTickets'];
- }
- }
- if (!count($deal)) {
- throw new CHttpException(403, "not_a_valid_ticket");
- }
- $array = $deal['history']['tickets'];
- $key = 'id';
- $value = $filter['ticket_id'];
- $count = count($array);
- for ($i = 0; $i < $count; $i++) {
- if (Deals::search_in_array($value, $array[$i])) {
- $found = $i;
- break;
- }
- }
- $filter['transaction_id'] = $deal['history']['tickets'][$found]['transaction'];
- $collection->update(
- array("_id" => new MongoID($collection_id)), array('$set' => array("purchasedTickets.tickets.$found.used" => "yes"))
- );
- return $this->getTicketDetails($filter);
- }
- public function getTicketDetails($filter) {
- $collection = Yii::app()->edmsMongoCollection('deals_live');
- // pagination
- if (isset($this->pageOffset) && (!is_numeric($this->pageOffset) || $this->pageOffset < 0)) {
- $this->pageOffset = 0;
- }
- if (isset($this->pageCount) && (!is_numeric($this->pageCount) || $this->pageCount < 0)) {
- $this->pageCount = 100;
- }
- //sorting
- if ($params['sort']) {
- $params['sort'] = intval($params['sort']);
- } else {
- $params['sort'] = -1;
- }
- $query = array();
- //$query['owner.id'] = intval($this->communityId);
- $query['deal_id'] = new MongoID($filter['deal_id']);
- if ($filter['ticket_id'])
- $query['purchasedTickets.tickets.id'] = $filter['ticket_id'];
- $query['purchasedTickets.tickets.transaction'] = $filter['transaction_id'];
- $ticket_id = $filter['ticket_id'];
- // executing query
- $deals = $collection->find($query)
- ->skip($this->pageOffset)
- ->limit($this->pageCount)
- ->sort(array("_id" => $params['sort']));
- // parsing the result
- $parsedDeals = array();
- if (!$deals) {
- throw new CHttpException(403, "not_live_ticket");
- }
- if ($deals) {
- foreach ($deals as $d) {
- $deal['tickets'] = $d['price'];
- $deal['history'] = $d['purchasedTickets'];
- $parsedDeals['event_details'] = $d['dealinfo'];
- $parsedDeals['user'] = $d['userinfo'];
- $owner_id = $d['owner']['id'];
- }
- }
- if (!count($parsedDeals)) {
- throw new CHttpException(403, "not_a_live_ticket");
- }
- /* only community owner can view ticket details */
- if ($owner_id != intval($this->communityId)) {
- throw new CHttpException(403, "permission_denied");
- }
- $array = $deal['history']['tickets'];
- $key = 'id';
- $value = $ticket_id;
- $count = count($array);
- for ($i = 0; $i < $count; $i++) {
- if (Deals::search_in_array($value, $array[$i])) {
- $found = $i;
- break;
- }
- }
- $parsedDeals['ticket_details'] = $deal['history']['tickets'][$found];
- if ($parsedDeals['ticket_details']['index'])
- unset($parsedDeals['ticket_details']['index']);
- $price_type = $deal['tickets']['type'];
- if ($deal['tickets']['type'] == 'tPoints') {
- $price_type = 'TAG Points';
- } else {
- $price_type = WalletTypes::getWalletName($deal['tickets']['wallet_id'], true);
- }
- $p_index = $deal['history']['tickets'][$found]['index'];
- $parsedDeals['ticket_details']['price'] = $deal['tickets']['options'][$p_index]['price'] . " " . $price_type;
- for ($u = 0; $u < count($deal['history']['history']); $u++) {
- if ($deal['history']['history'][$u]['transaction_code'] == $filter['transaction_id']) {
- $parsedDeals['ticket_details']['paid'] = $deal['history']['history'][$u]['paid'];
- $parsedDeals['ticket_details']['paidUsing'] = $deal['history']['history'][$u]['paidUsing'];
- }
- }
- return $parsedDeals;
- }
- public function getTicketCount($deal_id) {
- $collection = Yii::app()->edmsMongoCollection('deals_live');
- $query = array();
- $query['deal_id'] = new MongoID($filter['deal_id']);
- // executing query
- $deals = $collection->find($query);
- // parsing the result
- $parsedDeals = array();
- if (!$deals) {
- throw new CHttpException(403, "not_live_ticket");
- }
- if ($deals) {
- foreach ($deals as $d) {
- $deal['tickets'] = $d['price'];
- $deal['history'] = $d['purchasedTickets'];
- $parsedDeals['event_details'] = $d['dealinfo'];
- $parsedDeals['user'] = $d['userinfo'];
- $owner_id = $d['owner']['id'];
- }
- }
- if (!count($parsedDeals)) {
- throw new CHttpException(403, "not_a_live_ticket");
- }
- /* only community owner can view ticket details */
- if ($owner_id != intval($this->communityId)) {
- throw new CHttpException(403, "permission_denied");
- }
- $array = $deal['history'];
- $key = 'id';
- $value = $ticket_id;
- $count = count($array);
- for ($i = 0; $i < $count; $i++) {
- if (Deals::search_in_array($value, $array[$i])) {
- $found = $i;
- break;
- }
- }
- $parsedDeals['ticket_details'] = $deal['history'][$found]['history'][0];
- $parsedDeals['ticket_details']['category'] = $deal['tickets']['options'][$found]['category'];
- $tickets = $deal['history'][$found]['tickets'][0];
- if ($tickets) {
- for ($t = 0; $t < count($tickets); $t++) {
- if ($tickets[$t]['id'] == $ticket_id) {
- $parsedDeals['ticket_details']['id'] = $ticket_id;
- $parsedDeals['ticket_details']['used'] = $tickets[$t]['used'];
- }
- }
- }
- //return $parsedDeals;
- }
- //payreferral fee
- public function payReferral($dealId, $tracker, $user) {
- $collection = Yii::app()->edmsMongoCollection('deals');
- $deal = $collection->findOne(array(
- "_id" => new MongoID($dealId),
- "tracker" => $tracker
- ));
- $affiliate_details = $deal['affiliate_fee'];
- $from_id = $affiliate_details[''][0];
- $transfer = new WalletTransfers();
- $transfer->setIdentity($this->thisObj);
- $transfer->reference_id = uniqid() . rand(10 * 45, 100 * 98);
- $transfer->transfer_from_wallet_id = $transfer->transfer_to_wallet_id = $affiliate_details['wallet_id'][0];
- $transfer->transfer_from_amount = $transfer->transfer_amount = $affiliate_details['amount'][0];
- $transfer->transfer_to_id = $user;
- $transfer->transfer_to_type = 1;
- $transfer->transfer_from_id = $deal['owner']['id'];
- $transfer->transfer_from_type = ($deal['owner']['type'] == 'user') ? '1' : '2';
- $transfer->transfer_narration = 'Referral Commission #' . $dealId;
- if (!$transfer->transfer()) {
- $status_message['payment_failed'][] = $user;
- return false;
- }
- //dbug::p($transfer->getErrors());
- }
- //generic call for ppt, ppc, and ppr -- incomplete
- public function payCommission() {
- switch ($this->type) {
- case 'ppt':
- $type = 10;
- break;
- case 'ppc':
- $type = 14;
- break;
- case 'ppr':
- $type = 15;
- break;
- }
- $settings = SiteSettings::getSettings();
- $walletBalance = WalletBalances::model()->findByAttributes(array(
- 'balance_id' => $userId,
- 'balance_type' => 1,
- 'wallet_type_id' => $deal['price']['wallet_id'],
- ));
- /* if(!$walletBalance || !$walletBalance->checkWalletBalance($deal['price']['amount'])){
- $status_message['insufficient_amount'][] = $assigneeUserId;
- continue;
- }* */
- $transfers = new WalletTransfers();
- //$transfers->transfer_from_wallet_id = $deal['price']['wallet_id'];
- if ($type == 10) {//ppt
- }
- }
- public function getPromoCodeDetails() {
- $collection = Yii::app()->edmsMongoCollection('deals_live');
- $query = array();
- $query['type'] = "promo";
- $query['owner.id'] = intval($this->communityId);
- $query['dealinfo.promo_codes.code'] = $this->promoCodes;
- // executing query
- $deals = $collection->find($query);
- // parsing the result
- $parsedDeals = array();
- if (!$deals) {
- throw new CHttpException(403, "invalid_promocode");
- }
- if ($deals) {
- foreach ($deals as $d) {
- $parsedDeals['promo_type'] = $d['dealinfo']['promo_type'];
- $parsedDeals['user'] = $d['userinfo'];
- $parsedDeals['emailInfo'] = $d['dealinfo']['emailInfo'];
- }
- }
- if (!count($parsedDeals)) {
- throw new CHttpException(403, "invalid_promocode");
- }
- return $parsedDeals;
- }
- public static function payAffiliateReward($live = NULL, $deal, $method, $quantity, $affiliateInfo = NULL) {
- $from = $deal->owner->id;
- $fromType = 2;
- $wallet = ($live != NULL) ? $live->affiliate_info->wallet_id : $affiliateInfo->wallet_id;
- //for affiliate user
- $totalForAffiliate = ($live != NULL) ? $live->affiliate_info->amount : $affiliateInfo->amount;
- $to = ($live != NULL) ? $live->affiliate_info->id : $affiliateInfo->id;
- $userGets = $totalForAffiliate * $quantity;
- $narration = "Affiliate reward for sharing " . $deal->dealinfo['event_name'] . " advert (" . $totalForAffiliate . " x " . $quantity . ")";
- self::transferPayment($userGets, $from, $fromType, $to, 1, $wallet, $narration);
- //for system
- $totalForSystem = ($live != NULL) ? $live->affiliate_info->systemAmount : $affiliateInfo->systemAmount;
- $systemGets = $totalForSystem * $quantity;
- $to = Yii::app()->params['tagcashID'];
- $narration = "30% Affiliate reward for sharing " . $deal->dealinfo['event_name'] . " advert (" . $totalForSystem . " x " . $quantity . ")";
- self::transferPayment($systemGets, $from, $fromType, $to, 2, $wallet, $narration);
- return true;
- }
- public static function payPercentageAffiliateReward($live = NULL, $deal, $method, $quantity, $price, $percentage, $affiliateInfo = NULL) {
- $set = $percentage * 100;
- $totalSales = $quantity * $price;
- $toBegiven = $totalSales * $percentage;
- $from = $deal->owner->id;
- $fromType = 2;
- $wallet = ($live != NULL) ? $live->affiliate_info->wallet_id : $affiliateInfo->wallet_id;
- //for affiliate user
- $totalForAffiliate = $toBegiven * .7;
- $to = ($live != NULL) ? $live->affiliate_info->id : $affiliateInfo->id;
- $userGets = $totalForAffiliate;
- $narration = "Affiliate reward for sharing " . $deal->dealinfo['event_name'] . " advert (" . $set . "% of total sales)";
- self::transferPayment($userGets, $from, $fromType, $to, 1, $wallet, $narration);
- //for system
- $totalForSystem = $toBegiven * .3;
- $systemGets = $totalForSystem;
- $to = Yii::app()->params['tagcashID'];
- $narration = "30% Affiliate reward for sharing " . $deal->dealinfo['event_name'] . " advert (" . $set . "% of total sales)";
- self::transferPayment($systemGets, $from, $fromType, $to, 2, $wallet, $narration);
- return true;
- }
- public function transferPayment($amount, $from, $fromType, $to, $toType, $wallet, $narration, $return_ref_id = false) {
- $preTransaction = Yii::app()->db->getCurrentTransaction();
- if (!$preTransaction) {
- $transaction = Yii::app()->db->beginTransaction();
- }
- $code = uniqid() . rand(10 * 45, 100 * 98);
- $modelWalletTransfers = new WalletTransfers();
- $modelWalletTransfers->settings = SiteSettings::getSettings();
- $modelWalletTransfers->user = Users::model()->findByPk($from);
- $modelWalletTransfers->reference_id = $code;
- $modelWalletTransfers->transfer_type = 1;
- $modelWalletTransfers->transfer_amount = $amount;
- $modelWalletTransfers->transfer_from_id = $from;
- $modelWalletTransfers->transfer_from_type = $fromType; //1 - user , 2 - community
- $modelWalletTransfers->transfer_from_wallet_id = $wallet;
- $modelWalletTransfers->transfer_from_amount = $amount;
- $modelWalletTransfers->transfer_to_id = $to;
- $modelWalletTransfers->transfer_to_type = $toType; //1 - user , 2 - community
- $modelWalletTransfers->transfer_to_wallet_id = $wallet;
- $modelWalletTransfers->transfer_narration = $narration;
- $modelWalletTransfers->userId = $from;
- $stat = $modelWalletTransfers->transfer();
- if ($stat) {
- //end transaction - commiting
- if (!$preTransaction) {
- $transaction->commit();
- }
- if ($return_ref_id == true)
- return $stat;
- return true;
- }
- else {
- if ($return_ref_id == true) {
- return $modelWalletTransfers->getErrors();
- }
- return false;
- }
- }
- public function itemPurchasePayment($merchant_pay, $from, $wallet, $order_id) {
- $preTransaction = Yii::app()->db->getCurrentTransaction();
- if (!$preTransaction) {
- $transaction = Yii::app()->db->beginTransaction();
- }
- $transfer_type = 1; // wallet escrow transfer. see above commented code.
- $narration = 'Purchase Catalog : #' . $order_id;
- $escrow = new Escrow;
- $escrow->setIdentity($this->thisObj);
- $params = array(
- 'from_wallet_id' => $wallet,
- 'to_type' => 'community',
- 'to_id' => 2,
- 'to_wallet_id' => $wallet,
- 'amount' => array_sum($merchant_pay),
- 'narration' => $narration,
- 'transfer_type' => $transfer_type
- );
- $stat = $escrow->initiate($params, true);
- if ($stat) {
- SELF::updateItemPurchaseMerchantPayments($merchant_pay, 1, $wallet, $stat, $order_id);
- //end transaction - commiting
- if (!$preTransaction) {
- $transaction->commit();
- }
- return $stat;
- } else {
- return false;
- }
- }
- public static function updateItemPurchaseMerchantPayments($merchant_pay, $payment_method = 1, $wallet, $stat, $order_id) {
- foreach ($merchant_pay as $merchant_id => $amount) {
- $purchseRecord = new ItemPurchaseMerchantPayments;
- $purchseRecord->order_id = $order_id;
- $purchseRecord->payment_id = $stat;
- $purchseRecord->payment_method = $payment_method;
- $purchseRecord->merchant_id = $merchant_id;
- $purchseRecord->amount = $amount;
- $purchseRecord->wallet_id = $wallet;
- $purchseRecord->pay_date = gmdate("Y-m-d H:i:s");
- $purchseRecord->status = 0;
- $purchseRecord->save(true);
- if ($purchseRecord->getErrors()) {
- return false;
- }
- return true;
- }
- }
- public function purchaseTicket() {
- $object = new stdClass;
- $object->errors = array();
- $collection = Yii::app()->edmsMongoCollection('deals');
- $deal = $collection->findOne(array(
- "_id" => new MongoID($this->dealId),
- ));
- if ($deal) {
- if ($this->payment_method) {
- if (!in_array($this->payment_method, $deal['methodOfPayment']['method'])) {
- throw new CHttpException(403, "payment_method_not_available");
- }
- } else {
- if ($deal['methodOfPayment']['method']) {
- throw new CHttpException(403, "payment_method_not_valid");
- }
- }
- $checkMember = CommunityUsers::model()->findByAttributes(array("user_id" => $this->userId, "community_id" => $deal['owner']['id']));
- //if not member : auto join
- if (!$checkMember) {
- $default_role = CommunityRoles::model()->findByAttributes(array('community_id' => $deal->owner->id, 'role_default' => '1'));
- $roleId = $default_role->id;
- $modelUsers = new CommunityUsers;
- $modelUsers->user_id = $this->userId;
- $modelUsers->community_id = $deal['owner']['id'];
- $modelUsers->role_id = $roleId;
- $modelUsers->communityuser_status = 1;
- $modelUsers->communityuser_relation = 1;
- $modelUsers->save();
- }
- //limits - Per User, Per Day and Global Limit
- if ($deal['limits']['max_global_limit']) {
- if (Deals::countTimesTaken($this->dealId, true) >= $deal['limits']['max_global_limit']) {
- $object->errors[] = 'limit_exceeded';
- }
- } else {
- if ($deal['limits']['max_limit_per_day']) {
- if (Deals::countTimesTakenPerDay($this->dealId) >= $deal['limits']['max_limit_per_day']) {
- $object->errors[] = 'limit_per_day_exceeded';
- }
- } else {
- if ($deal['limits']['max_limit_per_user']) {
- if (Deals::countTimesTaken($this->dealId, true, $this->userId) >= $deal['limits']['max_limit_per_user']) {
- $object->errors[] = 'limit_per_user_exceeded';
- }
- }
- }
- }
- if (!$object->errors) {
- //check for payment method 0= tagpoints; 1 = tagcash payment; 2= cash on pickup/delivery
- if ($this->payment_method) {
- if ($this->payment_method == 1) { //pay using tagcash
- if ($this->wallet_id <= 0)
- throw new CHttpException(403, "invalid_wallet_id");
- $response = $this->payTicketViaTagcash();
- if ($response)
- $object->result->transaction_id = $response;
- else
- $object->errors[] = 'payment_failed';
- }
- elseif ($this->payment_method == 2) { //pay on site
- $response = $this->payTicketsOnSite();
- if ($response)
- $object->result->transaction_id = $response;
- else
- $object->errors[] = 'transaction_failed';
- }
- elseif ($this->payment_method == 3) { //paypal
- if ($this->paypalInfo && $this->paypalInfo['txn_id'] && $this->paypalInfo['payment_date']) {
- $response = $this->payTicketsViaPaypal();
- if ($response)
- $object->result->transaction_id = $response;
- else
- $object->errors[] = 'transaction_failed';
- }
- else {
- throw new CHttpException(403, "incomplete_paypal_information");
- }
- } elseif ($this->payment_method == 4) { //dragonpay
- $response = $this->payTicketsViaDragonpay();
- if ($response)
- $object->result->url = $response;
- else
- $object->errors[] = 'transaction_failed';
- }
- }else {
- if ($deal['price']['type'] == 'tPoints') {
- $this->wallet_id = 20;
- $response = $this->payTicketViaTagcash();
- if ($response)
- $object->result->transaction_id = $response;
- else
- $object->errors[] = 'transaction_failed';
- }else {
- $response = $this->getFreeTickets();
- if ($response)
- $object->result->transaction_id = $response;
- else
- $object->errors[] = 'transaction_failed';
- }
- }
- }
- return $object;
- }
- }
- public function getFreeTickets() {
- $cart_tickets = $this->tickets;
- $dealId = $this->dealId;
- $userId = $this->userId;
- $ticket_index = array_keys($cart_tickets);
- $ticket_count = array_values($cart_tickets);
- $quantity = array_sum($cart_tickets);
- $collection = Yii::app()->edmsMongoCollection('deals');
- $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
- $livePurchasedTicket = self::liveDealInfo($dealId, $userId);
- $deal = self::dealInfo($dealId);
- //affiliate
- if ($params['affiliateId'] && ($params['affiliateId'] != $this->userId)) {
- $affiliateId = $params['affiliateId'];
- $affiliateWalletId = $params['affiliateWalletId'];
- } else {
- $affiliateId = NULL;
- }
- if (!$livePurchasedTicket) {
- //initialize bookmark of event
- SELF::bookmarkDeal($dealId, $affiliateId, NULL, $affiliateWalletId);
- $purchasedTickets = array('history' => array(), 'tickets' => array());
- } else {
- $purchasedTickets = $livePurchasedTicket->purchasedTickets;
- }
- $transaction_id = uniqid() . rand(10 * 45, 100 * 98);
- $purchaseDetails = array(
- 'transaction_code' => $transaction_id,
- 'date_purchased' => date('Y-m-d H:i:s A'),
- 'quantity' => $quantity,
- 'paid' => 'yes',
- 'paidUsing' => 'Free Ticket'
- );
- if ($params['participant']['additional']) {
- $purchaseDetails['additional'] = $params['participant']['additional'];
- }
- $totalAmount = 0;
- for ($i = 0; $i < sizeOf($ticket_index); $i++) {
- if ($deal->price['options'][$ticket_index[$i]]['price'] && $deal->price['options'][$ticket_index[$i]]['price'] > 0)
- return false;
- if ($ticket_count[$i] > 0) {
- for ($counter = 0; $counter < $ticket_count[$i]; $counter++) {
- $ticket_id = uniqid() . rand(10 * 45, 100 * 98);
- $ticket = array(
- 'id' => $ticket_id,
- 'index' => $ticket_index[$i],
- 'used' => 'no',
- 'category' => $deal->price['options'][$ticket_index[$i]]['category'],
- 'transaction' => $transaction_id,
- 'first_name' => $params['fname'],
- 'middle_name' => $params['mname'],
- 'last_name' => $params['lname'],
- 'email' => $params['email'],
- 'contact' => $params['number']
- );
- array_push($purchasedTickets['tickets'], $ticket);
- }
- if ($deal->price['options'][$ticket_index[$i]]['quantity'] != "") {
- $deal->price['options'][$ticket_index[$i]]['quantity'] -= $ticket_count[$i];
- }
- }
- }
- array_push($purchasedTickets['history'], $purchaseDetails);
- $collection->update(
- array(
- "_id" => new MongoID($dealId),
- ), array('$set' => array("price" => $deal->price))
- );
- $liveCollection->update(
- array(
- "deal_id" => new MongoID($dealId),
- "user_id" => intval($this->userId),
- ), array('$set' => array("status" => intval(8), "price" => $deal->price, "purchasedTickets" => $purchasedTickets))
- );
- return $transaction_id;
- }
- public function payTicketViaTagcash() {
- $cart_tickets = $this->tickets;
- $dealId = $this->dealId;
- $userId = $this->userId;
- $ticket_index = array_keys($cart_tickets);
- $ticket_count = array_values($cart_tickets);
- $collection = Yii::app()->edmsMongoCollection('deals');
- $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
- $livePurchasedTicket = self::liveDealInfo($dealId, $userId);
- $deal = self::dealInfo($dealId);
- $quantity = array_sum($cart_tickets);
- $fromId = $userId;
- $fromType = 1;
- $walletId = $this->wallet_id;
- $toId = $deal->owner['id'];
- $toType = 2;
- $narration = "Payment for purchasing tickets for the upcoming " . $deal->dealinfo['event_name'];
- //affiliate
- if ($params['affiliateId'] && ($params['affiliateId'] != $this->userId)) {
- $affiliateId = $params['affiliateId'];
- $affiliateWalletId = $params['affiliateWalletId'];
- } else {
- $affiliateId = NULL;
- }
- if (!$livePurchasedTicket) {
- //initialize bookmark of event
- SELF::bookmarkDeal($dealId, $affiliateId, NULL, $affiliateWalletId);
- $purchasedTickets = array('history' => array(), 'tickets' => array());
- } else {
- $purchasedTickets = $livePurchasedTicket->purchasedTickets;
- }
- $transaction_id = uniqid() . rand(10 * 45, 100 * 98);
- $purchaseDetails = array(
- 'transaction_code' => $transaction_id,
- 'date_purchased' => date('Y-m-d H:i:s A'),
- 'quantity' => $quantity,
- 'paid' => 'yes',
- 'paidUsing' => 'tagcash'
- );
- if ($params['participant']['additional']) {
- $purchaseDetails['additional'] = $params['participant']['additional'];
- }
- $totalAmount = 0;
- for ($i = 0; $i < sizeOf($ticket_index); $i++) {
- $totalAmount += (($deal->price['options'][$ticket_index[$i]]['price']) * $ticket_count[$i]);
- if ($ticket_count[$i] > 0) {
- for ($counter = 0; $counter < $ticket_count[$i]; $counter++) {
- $ticket_id = uniqid() . rand(10 * 45, 100 * 98);
- $ticket = array(
- 'id' => $ticket_id,
- 'index' => $ticket_index[$i],
- 'used' => 'no',
- 'category' => $deal->price['options'][$ticket_index[$i]]['category'],
- 'transaction' => $transaction_id,
- 'first_name' => $params['fname'],
- 'middle_name' => $params['mname'],
- 'last_name' => $params['lname'],
- 'email' => $params['email'],
- 'contact' => $params['number']
- );
- array_push($purchasedTickets['tickets'], $ticket);
- }
- if ($deal->price['options'][$ticket_index[$i]]['quantity'] != "") {
- $deal->price['options'][$ticket_index[$i]]['quantity'] -= $ticket_count[$i];
- }
- }
- }
- //check user wallet balance
- $user_balance = WalletBalances::getWalletBalance($userId, 1, $walletId);
- if ($totalAmount > $user_balance['amount'])
- throw new CHttpException(403, "insufficient_amount");
- array_push($purchasedTickets['history'], $purchaseDetails);
- //start transaction - if sns error it wont update mongo, so roll back
- $preTransaction = Yii::app()->db->getCurrentTransaction();
- if (!$preTransaction) {
- $transaction = Yii::app()->db->beginTransaction();
- }
- $stat = Deals::transferPayment($totalAmount, $fromId, $fromType, $toId, $toType, $walletId, $narration);
- if ($stat) {
- $collection->update(
- array(
- "_id" => new MongoID($dealId),
- ), array('$set' => array("price" => $deal->price))
- );
- $liveCollection->update(
- array(
- "deal_id" => new MongoID($dealId),
- "user_id" => intval($this->userId),
- ), array('$set' => array("status" => intval(8), "price" => $deal->price, "purchasedTickets" => $purchasedTickets))
- );
- $transaction->commit();
- return $transaction_id;
- } else
- return false;
- }
- public function payTicketsOnSite() {
- $cart_tickets = $this->tickets;
- $dealId = $this->dealId;
- $userId = $this->userId;
- $ticket_index = array_keys($cart_tickets);
- $ticket_count = array_values($cart_tickets);
- $quantity = array_sum($cart_tickets);
- $collection = Yii::app()->edmsMongoCollection('deals');
- $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
- $livePurchasedTicket = self::liveDealInfo($dealId, $userId);
- $deal = self::dealInfo($dealId);
- //affiliate
- if ($params['affiliateId'] && ($params['affiliateId'] != $this->userId)) {
- $affiliateId = $params['affiliateId'];
- $affiliateWalletId = $params['affiliateWalletId'];
- } else {
- $affiliateId = NULL;
- }
- if (!$livePurchasedTicket) {
- //initialize bookmark of event
- SELF::bookmarkDeal($dealId, $affiliateId, NULL, $affiliateWalletId);
- $purchasedTickets = array('history' => array(), 'tickets' => array());
- } else {
- $purchasedTickets = $livePurchasedTicket->purchasedTickets;
- }
- $transaction_id = uniqid() . rand(10 * 45, 100 * 98);
- $purchaseDetails = array(
- 'transaction_code' => $transaction_id,
- 'date_purchased' => date('Y-m-d H:i:s A'),
- 'quantity' => $quantity,
- 'paid' => 'no',
- 'paidUsing' => 'pickup'
- );
- if ($params['participant']['additional']) {
- $purchaseDetails['additional'] = $params['participant']['additional'];
- }
- $totalAmount = 0;
- for ($i = 0; $i < sizeOf($ticket_index); $i++) {
- $totalAmount += (($deal->price['options'][$ticket_index[$i]]['price']) * $ticket_count[$i]);
- if ($ticket_count[$i] > 0) {
- for ($counter = 0; $counter < $ticket_count[$i]; $counter++) {
- $ticket_id = uniqid() . rand(10 * 45, 100 * 98);
- $ticket = array(
- 'id' => $ticket_id,
- 'index' => $ticket_index[$i],
- 'used' => 'no',
- 'category' => $deal->price['options'][$ticket_index[$i]]['category'],
- 'transaction' => $transaction_id,
- 'first_name' => $params['fname'],
- 'middle_name' => $params['mname'],
- 'last_name' => $params['lname'],
- 'email' => $params['email'],
- 'contact' => $params['number']
- );
- array_push($purchasedTickets['tickets'], $ticket);
- }
- if ($deal->price['options'][$ticket_index[$i]]['quantity'] != "") {
- $deal->price['options'][$ticket_index[$i]]['quantity'] -= $ticket_count[$i];
- }
- }
- }
- array_push($purchasedTickets['history'], $purchaseDetails);
- $collection->update(
- array(
- "_id" => new MongoID($dealId),
- ), array('$set' => array("price" => $deal->price))
- );
- $liveCollection->update(
- array(
- "deal_id" => new MongoID($dealId),
- "user_id" => intval($this->userId),
- ), array('$set' => array("status" => intval(8), "price" => $deal->price, "purchasedTickets" => $purchasedTickets))
- );
- return $transaction_id;
- }
- public static function payTicketsViaPaypal() {
- $cart_tickets = $this->tickets;
- $dealId = $this->dealId;
- $userId = $this->userId;
- $ticket_index = array_keys($cart_tickets);
- $ticket_count = array_values($cart_tickets);
- $quantity = array_sum($cart_tickets);
- $collection = Yii::app()->edmsMongoCollection('deals');
- $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
- $livePurchasedTicket = self::liveDealInfo($dealId, $userId);
- $deal = self::dealInfo($dealId);
- //affiliate
- if ($params['affiliateId'] && ($params['affiliateId'] != $this->userId)) {
- $affiliateId = $params['affiliateId'];
- $affiliateWalletId = $params['affiliateWalletId'];
- } else {
- $affiliateId = NULL;
- }
- if (!$livePurchasedTicket) {
- //initialize bookmark of event
- SELF::bookmarkDeal($dealId, $affiliateId, NULL, $affiliateWalletId);
- $purchasedTickets = array('history' => array(), 'tickets' => array());
- } else {
- $purchasedTickets = $livePurchasedTicket->purchasedTickets;
- }
- $transaction_id = uniqid() . rand(10 * 45, 100 * 98);
- $purchaseDetails = array(
- 'transaction_code' => $transaction_id,
- 'date_purchased' => date('Y-m-d H:i:s A'),
- 'quantity' => $quantity,
- 'paid' => 'yes',
- 'paidUsing' => 'paypal',
- 'paypalInfo' => $this->paypalInfo
- );
- if ($params['participant']['additional']) {
- $purchaseDetails['additional'] = $params['participant']['additional'];
- }
- $totalAmount = 0;
- for ($i = 0; $i < sizeOf($ticket_index); $i++) {
- $totalAmount += (($deal->price['options'][$ticket_index[$i]]['price']) * $ticket_count[$i]);
- if ($ticket_count[$i] > 0) {
- for ($counter = 0; $counter < $ticket_count[$i]; $counter++) {
- $ticket_id = uniqid() . rand(10 * 45, 100 * 98);
- $ticket = array(
- 'id' => $ticket_id,
- 'index' => $ticket_index[$i],
- 'used' => 'no',
- 'category' => $deal->price['options'][$ticket_index[$i]]['category'],
- 'transaction' => $transaction_id,
- 'first_name' => $params['fname'],
- 'middle_name' => $params['mname'],
- 'last_name' => $params['lname'],
- 'email' => $params['email'],
- 'contact' => $params['number']
- );
- array_push($purchasedTickets['tickets'], $ticket);
- }
- if ($deal->price['options'][$ticket_index[$i]]['quantity'] != "") {
- $deal->price['options'][$ticket_index[$i]]['quantity'] -= $ticket_count[$i];
- }
- }
- }
- array_push($purchasedTickets['history'], $purchaseDetails);
- $collection->update(
- array(
- "_id" => new MongoID($dealId),
- ), array('$set' => array("price" => $deal->price))
- );
- $liveCollection->update(
- array(
- "deal_id" => new MongoID($dealId),
- "user_id" => intval($this->userId),
- ), array('$set' => array("status" => intval(8), "price" => $deal->price, "purchasedTickets" => $purchasedTickets))
- );
- return $transaction_id;
- }
- public function payTicketsViaDragonpay() {
- $cart_tickets = $this->tickets;
- $dealId = $this->dealId;
- $userId = $this->userId;
- $ticket_index = array_keys($cart_tickets);
- $ticket_count = array_values($cart_tickets);
- $quantity = array_sum($cart_tickets);
- $collection = Yii::app()->edmsMongoCollection('deals');
- $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
- $livePurchasedTicket = self::liveDealInfo($dealId, $userId);
- $deal = self::dealInfo($dealId);
- $fromId = $userId;
- $fromType = 1;
- $walletId = $this->wallet_id;
- $toId = $deal->owner['id'];
- $toType = 2;
- $narration = "Payment for purchasing tickets for the upcoming " . $deal->dealinfo['event_name'];
- //affiliate
- if ($params['affiliateId'] && ($params['affiliateId'] != $this->userId)) {
- $affiliateId = $params['affiliateId'];
- $affiliateWalletId = $params['affiliateWalletId'];
- } else {
- $affiliateId = NULL;
- }
- if (!$livePurchasedTicket) {
- //initialize bookmark of event
- SELF::bookmarkDeal($dealId, $affiliateId, NULL, $affiliateWalletId);
- $purchasedTickets = array('history' => array(), 'tickets' => array());
- } else {
- $purchasedTickets = $livePurchasedTicket->purchasedTickets;
- }
- $transaction_id = uniqid() . rand(10 * 45, 100 * 98);
- $purchaseDetails = array(
- 'transaction_code' => $transaction_id,
- 'date_purchased' => date('Y-m-d H:i:s A'),
- 'quantity' => $quantity,
- 'paid' => 'no',
- 'paidUsing' => 'dragonpay'
- );
- if ($params['participant']['additional']) {
- $purchaseDetails['additional'] = $params['participant']['additional'];
- }
- $totalAmount = 0;
- for ($i = 0; $i < sizeOf($ticket_index); $i++) {
- $totalAmount += (($deal->price['options'][$ticket_index[$i]]['price']) * $ticket_count[$i]);
- if ($ticket_count[$i] > 0) {
- for ($counter = 0; $counter < $ticket_count[$i]; $counter++) {
- $ticket_id = uniqid() . rand(10 * 45, 100 * 98);
- $ticket = array(
- 'id' => $ticket_id,
- 'index' => $ticket_index[$i],
- 'used' => 'no',
- 'category' => $deal->price['options'][$ticket_index[$i]]['category'],
- 'transaction' => $transaction_id,
- 'first_name' => $params['fname'],
- 'middle_name' => $params['mname'],
- 'last_name' => $params['lname'],
- 'email' => $params['email'],
- 'contact' => $params['number']
- );
- array_push($purchasedTickets['tickets'], $ticket);
- }
- if ($deal->price['options'][$ticket_index[$i]]['quantity'] != "") {
- $deal->price['options'][$ticket_index[$i]]['quantity'] -= $ticket_count[$i];
- }
- }
- }
- array_push($purchasedTickets['history'], $purchaseDetails);
- //initiate dragon pay transaction
- $dragonpayTransaction = new DragonpayTransaction;
- $dragonpayTransaction->transfer_from_id = $fromId;
- $dragonpayTransaction->transfer_from_type = $fromType;
- $dragonpayTransaction->transfer_to_id = $toId;
- $dragonpayTransaction->transfer_to_type = $toType;
- $dragonpayTransaction->transfer_from_wallet_id = $walletId;
- $dragonpayTransaction->transfer_to_wallet_id = $walletId;
- $dragonpayTransaction->transfer_from_amount = $totalAmount;
- $dragonpayTransaction->transfer_to_amount = $totalAmount;
- $dragonpayTransaction->custom_field_1 = $dealId;
- $dragonpayTransaction->custom_field_2 = $transaction_id;
- $dragonpayTransaction->transfer_narration = $narration;
- $dragonpayTransaction->method = "tag77";
- $result = $dragonpayTransaction->postDragonpayTransaction();
- if ($result->status == 'success') {
- //update mongo
- $collection->update(
- array(
- "_id" => new MongoID($dealId),
- ), array('$set' => array("price" => $deal->price))
- );
- $liveCollection->update(
- array(
- "deal_id" => new MongoID($dealId),
- "user_id" => intval($this->userId),
- ), array('$set' => array("status" => intval(8), "price" => $deal->price, "purchasedTickets" => $purchasedTickets))
- );
- $redirectUrl = $result->url . '?' . $result->fields;
- return $redirectUrl;
- }
- return false;
- }
- public function bookmarkDeal($dealId = NULL, $affiliate_id = NULL, $assigner_id = NULL, $affiliate_wallet_id = NULL, $tracker = NULL, $userId = NULL) {
- if ($dealId)
- $Deal = self::dealInfo($dealId);
- else
- $Deal = self::dealInfo($this->dealId);
- if (!$userId)
- $userId = $this->userId;
- $checkMember = CommunityUsers::model()->findByAttributes(array("user_id" => $userId, "community_id" => $Deal->owner->id));
- //if not member; automatically adds
- if (!$checkMember) {
- $role = CommunityRoles::model()->findByAttributes(array('community_id' => $Deal->owner->id, 'role_default' => '1'));
- $roleId = $role->id;
- $modelUsers = new CommunityUsers;
- $modelUsers->user_id = $userId;
- $modelUsers->community_id = $Deal->owner->id;
- $modelUsers->role_id = $roleId;
- $modelUsers->communityuser_status = 1;
- $modelUsers->communityuser_relation = 1;
- $modelUsers->save();
- }
- $user = Users::model()->findByPk($userId);
- //copying to live deal
- $liveDeal = new stdClass();
- $liveDeal->deal_id = new MongoID($this->dealId);
- $liveDeal->title = $Deal->title;
- $liveDeal->type = $Deal->type;
- $liveDeal->description = $Deal->description;
- $liveDeal->hiddenDescription = $Deal->hiddenDescription;
- $liveDeal->status = 7;
- $liveDeal->module = $Deal->module;
- $liveDeal->city = $Deal->city;
- $liveDeal->town = $Deal->town;
- $liveDeal->zipCode = $Deal->zipCode;
- $liveDeal->country = $Deal->country;
- $liveDeal->owner = $Deal->owner;
- $liveDeal->start_date = $Deal->start_date;
- $liveDeal->end_date = $Deal->end_date;
- $liveDeal->date_taken = date('Y-m-d H:i:s');
- $liveDeal->date_redeemed = "";
- $liveDeal->auto = $Deal->auto;
- $liveDeal->visibility = $Deal->visibility;
- $liveDeal->dealinfo = $Deal->dealinfo;
- $liveDeal->tags = $Deal->tags;
- $liveDeal->limits = $Deal->limits;
- $liveDeal->roles = $Deal->roles;
- $liveDeal->total_value = $Deal->total_value;
- $liveDeal->credit_type = $Deal->credit_type;
- $liveDeal->assigner_id = $assigner_id;
- $liveDeal->user_id = intval($userId);
- //user details
- $userInfo = new stdClass;
- $userInfo->id = intval($userId);
- $userInfo->user_firstname = $user->user_firstname;
- $userInfo->user_lastname = $user->user_lastname;
- $liveDeal->userinfo = $userInfo;
- if ($liveDeal->scanCount) {
- $liveDeal->scanCount = $Deal->scanCount;
- }
- if ($liveDeal->scanSchedule) {
- $liveDeal->scanSchedule = $Deal->scanSchedule;
- }
- if ($Deal->methodOfPayment) {
- $liveDeal->methodOfPayment = $Deal->methodOfPayment;
- }
- if ($Deal->digitalDelivery) {
- $liveDeal->digitalDelivery = $Deal->digitalDelivery;
- }
- if ($Deal->pickUpAddress) {
- $liveDeal->pickUpAddress = $Deal->pickUpAddress;
- }
- if ($Deal->price) {
- $liveDeal->price = $Deal->price;
- }
- if ($Deal->multiDelivery) {
- $liveDeal->multiDelivery = $Deal->multiDelivery;
- }
- if ($Deal->affiliate_fee) {
- $liveDeal->affiliate_fee = $Deal->affiliate_fee;
- }
- if ($Deal->rewardinfo) {
- $liveDeal->rewardinfo = $Deal->rewardinfo;
- }
- if ($Deal->paypertake) {
- $liveDeal->paypertake = $Deal->paypertake;
- }
- if ($Deal->payperclick) {
- $liveDeal->payperclick = $Deal->payperclick;
- }
- if ($Deal->bankDeposit) {
- $liveDeal->bankDeposit = $Deal->bankDeposit;
- }
- if ($affiliate_id) {
- //get affiliate info
- $affiliate = Users::model()->findByPk($affiliate_id);
- //set affiliate info
- $affiliateInfo = new stdClass;
- $affiliateInfo->user_id = intval($affiliate_id);
- $affiliateInfo->user_firstname = $affiliate->user_firstname;
- $affiliateInfo->user_lastname = $affiliate->user_lastname;
- if ($Deal->affiliate_fee['wallet_id']) {
- if (in_array($affiliate_wallet_id, $Deal->affiliate_fee['wallet_id'])) {
- $key = array_search($affiliate_wallet_id, $Deal->affiliate_fee['wallet_id']);
- if ($affiliate_wallet_id) {
- $affiliateInfo->wallet_id = intval($affiliate_wallet_id);
- }
- if ($Deal->affiliate_fee['affiliate_price_type'][$key] == 0) {
- $affiliateInfo->amount = ($Deal->affiliate_fee['amount'][$key] * .7);
- $affiliateInfo->systemAmount = ($Deal->affiliate_fee['amount'][$key] * .3);
- } else {
- $affiliateInfo->amount = $Deal->affiliate_fee['amount'][$key] / 100;
- }
- $affiliateInfo->affiliate_price_type = $Deal->affiliate_fee['affiliate_price_type'][$key];
- }
- }
- $liveDeal->affiliate_info = $affiliateInfo;
- }
- //Stamp Deal
- if ($Deal->type == "stamp") {
- $liveDeal->stamp_log = array();
- $liveDeal->stamp_notes = array();
- }
- //Poll/Survey Deal
- if ($Deal->type == "survey") {
- $response = new stdClass;
- $response->status = 0;
- $response->answer = NULL;
- $liveDeal->response = $response;
- }
- //ticket
- if ($Deal->type == "ticket") {
- $purchasedTickets = array('history' => array(), 'tickets' => array());
- $liveDeal->purchasedTickets = $purchasedTickets;
- }
- if ($tracker) {
- if ($Deal->tracker == $tracker) {
- $liveDeal->tracker = $Deal->tracker;
- self::countBookMark($this->dealId, $affiliate_id);
- }
- }
- $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
- if ($liveCollection->insert($liveDeal))
- return true;
- else
- return false;
- }
- public static function checkIfDealIsBookmarkable($dealId, $user = NULL) {
- $collection = Yii::app()->edmsMongoCollection('deals');
- $deal = (object) $collection->findOne(array("_id" => new MongoID($dealId)));
- if ($deal->status == 2 || strtotime(date('Y-m-d')) > strtotime($deal->end_date)) {
- return "expired_deal";
- }
- if ($deal->status != 1) {
- return "cannot_bookmark";
- }
- $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
- if ($user) {
- $deal_count = $liveCollection->find(array("deal_id" => new MongoID($dealId), "user_id" => intval($user), "status" => intval(7)))->count();
- } else {
- $deal_count = $liveCollection->find(array("deal_id" => new MongoID($dealId), "status" => intval(7)))->count();
- }
- if ($deal_count > 0) {
- return "already_bookmarked";
- } else {
- return 0;
- }
- }
- public static function countBookMark($dealId, $affiliate = NULL) {
- $deal = self::dealInfo($dealId);
- $collection = Yii::app()->edmsMongoCollection('deals');
- if ($deal->sharedBookmarkCount) {
- $count = $deal->sharedBookmarkCount + 1;
- } else {
- $count = 1;
- }
- $collection->update(
- array(
- "_id" => new MongoID($dealId),
- ), array('$set' => array("sharedBookmarkCount" => intval($count)))
- );
- return true;
- }
- //get user bookmarked deals of $type
- public function getBookmarkedDeals($type, $id) {
- // pagination
- if (isset($this->pageOffset) && (!is_numeric($this->pageOffset) || $this->pageOffset < 0)) {
- $this->pageOffset = 0;
- }
- if (isset($this->pageCount) && (!is_numeric($this->pageCount) || $this->pageCount < 0)) {
- $this->pageCount = 100;
- }
- $collection = Yii::app()->edmsMongoCollection('deals_live');
- if ($type == 'community')
- $query = array("owner.id" => intval($id), "owner.type" => "community");
- else
- $query = array("user_id" => intval($id));
- //$query["dealinfo.end_event_date"] = array('$gt' => date('Y-m-d'));
- $query['status'] = intval(7);
- //sort by date
- $result = $collection->find($query)->sort(array('start_date' => -1))->skip($this->pageOffset)->limit($this->pageCount);
- $deals = array();
- foreach ($result as $liveDeal) {
- $object = new stdClass;
- $object->deal_id = $liveDeal['deal_id']->__toString();
- $object->title = $liveDeal['title'];
- $object->description = $liveDeal['description'];
- if (strtotime(date('Y-m-d')) > strtotime($liveDeal['end_date']))
- $object->deal_status = self::formatStatus(2);
- else
- $object->deal_status = self::formatStatus($liveDeal['status']);
- $object->userinfo = $liveDeal['userinfo'];
- $object->dealinfo = $liveDeal['dealinfo'];
- $object->roles = $liveDeal['roles'];
- $object->userinfo['status'] = self::formatStatus($liveDeal['status']);
- $object->userinfo['taken_date'] = date("Y-m-d H:i:s", $liveDeal['_id']->getTimestamp());
- $object->owner = $liveDeal['owner'];
- //can take action (add stamp)
- if ($liveDeal['type'] == "stamp") {
- if ($liveDeal['status'] == 1) {
- if ($roleDetails->role_type == 1) {
- //if owner
- $object->can_take_action = true;
- } else if ($roleDetails->role_type == 2) {
- //If a staff member is trying to take action
- if (in_array($roleDetails->role_id, $liveDeal['roles']['redeem'])) {
- $object->can_take_action = true;
- }
- } else {
- //if member
- if ($liveDeal['dealinfo']['take_action']) {
- $object->can_take_action = true;
- }
- }
- }
- }
- //show ticket and transaction details
- if ($liveDeal['type'] == "ticket") {
- if ($liveDeal['price']) {
- $object->price = $liveDeal['price'];
- }
- if ($liveDeal['purchasedTickets']) {
- $object->purchasedTickets = $liveDeal['purchasedTickets'];
- }
- if ($liveDeal['scanCount']) {
- $object->scanCount = $liveDeal['scanCount'];
- }
- if ($liveDeal['scanSchedule']) {
- $object->scanSchedule = $liveDeal['scanSchedule'];
- }
- }
- //can redeem
- $object->can_redeem = false;
- if ($liveDeal['status'] == 3) {
- if ($roleDetails->role_type == 1) {
- //if owner
- $object->can_redeem = true;
- } else if ($roleDetails->role_type == 2) {
- //if staff
- if (in_array($roleDetails->role_id, $liveDeal['roles']['redeem'])) {
- $object->can_redeem = true;
- }
- } else {
- //if member
- if ($liveDeal['rewardinfo']['self_redeem']) {
- $object->can_redeem = true;
- }
- }
- }
- $deals[] = $object;
- }
- return $deals;
- }
- public static function countActiveBookmarks($dealId) {
- $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
- $liveCount = $liveCollection->find(array("deal_id" => new MongoID($dealId), "status" => intval(7)))->count();
- return $liveCount;
- }
- public static function getRemainingUserTicketLimit($dealId, $index, $userId) {
- $deal = self::dealInfo($dealId);
- $liveDeal = self::liveDealInfo($dealId, $userId);
- $limit = $deal->price['options'][$index]['limit'];
- if ($liveDeal) {
- $tickets = $liveDeal->purchasedTickets['tickets'];
- $counter = 0;
- for ($i = 0; $i < sizeOf($tickets); $i++) {
- if ($tickets[$i]['index'] == $index) {
- $counter++;
- }
- }
- $balance = $limit - $counter;
- } else {
- $balance = $limit;
- }
- return $balance;
- }
- public static function getRemainingTicketQuantity($dealId, $index) {
- $deal = self::dealInfo($dealId);
- return $deal ? $deal->price['options'][$index]['quantity'] : 0;
- }
- public static function getRemainingLimitForTicket($id, $optionLimit, $index) {
- $liveDeal = self::liveDealInfo($dealId, $userId);
- if ($live) {
- $tickets = $liveDeal->purchasedTickets['tickets'];
- $counter = 0;
- for ($i = 0; $i < sizeOf($tickets); $i++) {
- if ($tickets[$i]['index'] == $index) {
- $counter++;
- }
- }
- $limit = $optionLimit - $counter;
- } else {
- $limit = $optionLimit;
- }
- return $limit;
- }
- public static function getRemainingLimitForFree($id, $optionLimit) {
- $liveDeal = self::liveDealInfo($dealId, $userId);
- if ($live) {
- $tickets = $liveDeal->purchasedTickets['tickets'];
- $counter = 0;
- for ($i = 0; $i < sizeOf($tickets); $i++) {
- $counter++;
- }
- $limit = $optionLimit - $counter;
- if ($limit <= 0) {
- $limit = 0;
- }
- } else {
- $limit = $optionLimit;
- }
- return $limit;
- }
- public function assignTicket($userId) {
- $cart_tickets = $this->tickets;
- $dealId = $this->dealId;
- $ticket_index = array_keys($cart_tickets);
- $ticket_count = array_values($cart_tickets);
- $quantity = array_sum($cart_tickets);
- $collection_permission = Yii::app()->edmsMongoCollection('deals');
- $permitted = $collection_permission->findOne(array("_id" => new MongoId($dealId), "owner.id" => intval($this->communityId)));
- if (!$permitted) {
- throw new CHttpException(403, 'permission_denied');
- }
- $count = 0;
- foreach ($ticket_index as $index) {
- //check limit of user to buy
- $balance = SELF::getRemainingUserTicketLimit($dealId, $index, $userId);
- if ($balance < $ticket_count[$count]) {
- throw new CHttpException(403, 'user_limit_reached_for_ticket(s)');
- }
- //check enough quantity to buy
- $balance_qty = SELF::getRemainingTicketQuantity($dealId, $index);
- if ($balance_qty < $ticket_count[$count])
- throw new CHttpException(403, 'not_enough_tickets_to_buy)');
- $count++;
- }
- $deal_status = 8;
- if ($this->paid == 'no') {
- $payment_status = 'no';
- $paid_using = 'pickup';
- } else {
- $payment_status = 'yes';
- $paid_using = 'assign';
- }
- $collection = Yii::app()->edmsMongoCollection('deals');
- $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
- $livePurchasedTicket = self::liveDealInfo($dealId, $userId);
- $deal = self::dealInfo($dealId);
- //affiliate
- $affiliateId = NULL;
- $affiliateWalletId = NULL;
- if (!$livePurchasedTicket) {
- //initialize bookmark of event
- SELF::bookmarkDeal($dealId, $affiliateId, NULL, $affiliateWalletId, NULL, $userId);
- $purchasedTickets = array('history' => array(), 'tickets' => array());
- } else {
- $purchasedTickets = $livePurchasedTicket->purchasedTickets;
- }
- if (!$this->visitor_details) {
- //get user info
- $user_details = Users::model()->findByPk($userId);
- $user['fname'] = $user_details['user_firstname'];
- $user['lname'] = $user_details['user_lastname'];
- $user['mname'] = '';
- $user['email'] = $user_details['user_email'];
- $user['number'] = $user_details['user_mobile'];
- } else
- $user = $this->visitor_details;
- $transaction_id = uniqid() . rand(10 * 45, 100 * 98);
- $purchaseDetails = array(
- 'transaction_code' => $transaction_id,
- 'date_purchased' => date('Y-m-d H:i:s A'),
- 'quantity' => $quantity,
- 'paid' => $payment_status,
- 'paidUsing' => $paid_using
- );
- $totalAmount = 0;
- for ($i = 0; $i < sizeOf($ticket_index); $i++) {
- if ($ticket_count[$i] > 0) {
- for ($counter = 0; $counter < $ticket_count[$i]; $counter++) {
- $ticket_id = uniqid() . rand(10 * 45, 100 * 98);
- $ticket = array(
- 'id' => $ticket_id,
- 'index' => $ticket_index[$i],
- 'used' => 'no',
- 'category' => $deal->price['options'][$ticket_index[$i]]['category'],
- 'transaction' => $transaction_id,
- 'first_name' => $user['fname'],
- 'middle_name' => $user['mname'],
- 'last_name' => $user['lname'],
- 'email' => $user['email'],
- 'contact' => $user['number']
- );
- array_push($purchasedTickets['tickets'], $ticket);
- }
- if ($deal->price['options'][$ticket_index[$i]]['quantity'] != "") {
- $deal->price['options'][$ticket_index[$i]]['quantity'] -= $ticket_count[$i];
- }
- }
- }
- array_push($purchasedTickets['history'], $purchaseDetails);
- $collection->update(
- array(
- "_id" => new MongoID($dealId),
- ), array('$set' => array("price" => $deal->price))
- );
- $liveCollection->update(
- array(
- "deal_id" => new MongoID($dealId),
- "user_id" => intval($userId),
- ), array('$set' => array("status" => intval($deal_status), "price" => $deal->price, "purchasedTickets" => $purchasedTickets))
- );
- return $result['transaction_id'] = $transaction_id;
- }
- public static function getPaymentMethods($dealId) {
- $deal = Yii::app()->edmsMongoCollection('deals');
- $details = (array) $deal->findOne(array("_id" => new MongoID($dealId)));
- if ($details['price']['type'] == 'wallet') {
- if ($details && sizeOf($details['methodOfPayment']['method']) > 0)
- return $result = SELF::formatPaymentMethod($details['methodOfPayment']['method']);
- else
- return false;
- }
- else if ($details['price']['type'] == 'rewards') {
- return 'community_points';
- } else if ($details['price']['type'] == 'others') {
- return $details['price']['otherPayment'];
- } else
- return false;
- }
- /* public function getUnpaidTickets(){
- $collectionLive = Yii::app()->edmsMongoCollection('deals_live');
- $tickets = $collectionLive->find(array("deal_id" => new MongoID($this->dealId),"owner.id" => intval($this->communityId), "purchasedTickets.history.paid" => "no"));
- $parsedDeals = array();
- $i = 0;
- foreach($tickets as $ticket){
- $parsedDeals[$i]['deal_id'] = $ticket['deal_id'];
- $parsedDeals[$i]['userinfo'] = $ticket['userinfo'];
- $parsedDeals[$i]['price'] = $ticket['price'];
- $j = 0;
- foreach($ticket['purchasedTickets']['history'] as $history){
- if($history['paid'] == 'no'){
- $transaction_id = $history['transaction_code'];
- $parsedDeals[$i]['purchasedTickets']['history'][$j] = $history;
- $k = 0;
- foreach($ticket['purchasedTickets']['tickets'] as $tickets){
- if($tickets['transaction'] == $transaction_id){
- $parsedDeals[$i]['purchasedTickets']['tickets'][] = $tickets;
- }
- $k++;
- }
- }
- $j++;
- }
- //$parsedDeals[$i]['purchasedTickets']= $ticket['purchasedTickets'];
- $i++;
- }
- } */
- //for all e-commerce deals exluding tickets.
- public function dealTransaction($params) {
- $collection = Yii::app()->edmsMongoCollection('deals_live');
- $query = array();
- $query["paid"] = array('$exists' => false);
- $query["deal_id"] = new MongoID($params['deal_id']);
- $query['module'] = 'ecommerce';
- $query["userinfo.id"] = intval($this->userId);
- $deal = $collection->findOne($query);
- $paid = 'no';
- if ($deal) {
- if (!(in_array($params['payment_method'], $deal['methodOfPayment']['method']))) {
- $result['error'] = "payment_method_not_available";
- return $result;
- }
- //tagcash payment
- if (intval($params['payment_method']) == 1) {
- $wallet_id = $deal['price']['wallet_id'];
- $amount = $deal['price']['amount'];
- $narration = "Payment for taking Tagvert ID: <a href='http://tagbond.local/tagvert/details/" . $filter['deal_id'] . "'>" . $filter['deal_id'] . "</a>";
- $stat = Deals::transferPayment($amount, $this->userId, 1, $deal['owner']['id'], 2, $wallet_id, $narration);
- if ($stat) {
- $paid_using = "wallet";
- $paid = 'yes';
- } else {
- $result['error'] = "error_occured_or_insufficient_balance";
- return $result;
- }
- }
- //Cash on Pickup
- else if (intval($params['payment_method']) == 2) {
- $paid_using = "COD";
- }
- //paypal
- else if (intval($params['payment_method']) == 3) {
- $paid_using = "Paypal";
- }
- //creditCard : DragonPay
- else if (intval($params['payment_method']) == 4) {
- $paid_using = "Dragonpay";
- } else {
- $paid_using = "Others";
- }
- $collection->update(
- array(
- "_id" => new MongoID($deal['_id']),
- ), array('$set' => array("orderedDate" => date("Y-m-d H:i:s"), "paid" => $paid, "paidUsing" => $paid_using, "orderItemCount" => intval(1)))
- );
- return "transaction_successfull";
- } else {
- $result['error'] = "invalid_live_deal";
- return $result;
- }
- }
- public static function changeQRCode($id) {
- $collection = Yii::app()->edmsMongoCollection('deals');
- $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
- $newCode = rand();
- $collection->update(
- array("_id" => new MongoID($id)), array('$set' => array("dealinfo.code" => $newCode))
- );
- $liveCollection->update(
- array("deal_id" => new MongoID($id)), array('$set' => array("dealinfo.code" => $newCode))
- );
- return true;
- }
- public static function changeLiveDealPriority($status, $dealId, $communityId) {
- //0 - urgent 1 - non urgent
- if ($status == 1 || $status == 0) {
- $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
- $stat = $liveCollection->update(
- array("deal_id" => new MongoID($dealId),
- "owner.id" => intval($communityId),
- "owner.type" => "community"), array('$set' => array("priority" => $status))
- );
- if ($stat) {
- if ($status == 1) {
- //if catalog, relase payment if any
- $result = $liveCollection->findOne(
- array("deal_id" => new MongoID($dealId),
- "owner.id" => intval($communityId),
- "owner.type" => "community"));
- if ($stat['type'] == 'catalog') {
- //relaease payment
- }
- }
- return true;
- } else
- return false;
- }
- return false;
- }
- public function getCatalogItems($params, $itemsonly = false, $search = false) {
- $collection = Yii::app()->edmsMongoCollection('deals');
- $deal = $collection->findOne(array("_id" => new MongoID($params['deal_id'])));
- $items = array();
- if ($deal && $deal['items']) {
- $catalogImages = new CatalogImages;
- foreach ($deal['items'] as $item) {
- if ($search) {
- if ($params['catalog_name'] && $item['catalog_name']) {
- $pos = strpos(strtolower($item['catalog_name']), strtolower($params['catalog_name']));
- if ($pos === false)
- continue;
- }
- if ($params['category_id'] > 0) {
- if ($item['category']['id'] != $params['category_id'])
- continue;
- }
- }
- if ($itemsonly)
- $items[] = $item['id'];
- else {
- $item_details = SELF::formatItemDetails($item['id']);
- if (empty($item['category'])) {
- $item_details['category']['id'] = 0;
- $item_details['category']['name'] = '';
- }
- $item['price']['wallet'] = $item['price']['wallet_name'];
- unset($item['price']['wallet_name']);
- $image = $catalogImages->getCatalogImages($item['id']);
- $item_details['image'] = $image ? $image : array();
- if (!$this->communityId)
- $item_details['favorite'] = FavoriteCatalogs::checkFavourite($this->userId, $params['deal_id'], $item['id']);
- $items[] = $item_details;
- }
- }
- }
- return $items;
- }
- public function getSlotDeals($params, $imageOnly = false) {
- //offset wont work isnce image checking is enabled
- if (!$params['count'] || $params['count'] < 0)
- $count = 0;
- else
- $count = $params['count'];
- if (!$params['offset'] || $params['offset'] < 0)
- $offset = 100;
- else
- $offset = $params['offset'];
- $result = array();
- $query = array();
- $query['status'] = intval(1);
- $query['country.id'] = intval($params['country_id']);
- $query['end_date'] = array('$gte' => date('Y-m-d'));
- //only coupon tagverts now
- $query['type'] = 'coupon';
- //disbale for testing. need to uncomment below two lines when goes live
- $query["game_slots.status"] = intval(1);
- $query["game_slots.limit"] = array('$gt' => intval(0));
- $collection = Yii::app()->edmsMongoCollection('deals');
- //random result
- $array_key = array('_id', 'title', 'description', 'start_date', 'end_date', 'country.id', 'type');
- $array_sort = array(1, -1);
- $rand_sort = $array_sort[array_rand($array_sort)];
- $rand_sort1 = $array_sort[array_rand($array_sort)];
- $rand1 = $array_key[array_rand($array_key)];
- $rand = $array_key[array_rand($array_key)];
- if ($rand)
- $sort[$rand] = $rand_sort;
- if ($rand1)
- $sort[$rand1] = $rand_sort1;
- $deals = $collection->find($query)
- ->sort($sort);
- /* ->skip($offset)
- ->limit($count); */
- if ($deals) {
- $details = array();
- foreach ($deals as $deal) {
- if (!$imageOnly) {
- $detail['id'] = $deal['_id']->__toString();
- $detail['title'] = $deal['title'];
- $detail['link'] = Yii::app()->params['site_url'] . "/d/" . $detail['id'];
- }
- $tFilePath = 'uploads/tagverts/thumbnail_1';
- $tFileName = 'd_' . $detail['id'] . '.png';
- $tresultS3 = Yii::app()->tamazon->isObjectExist($tFilePath, $tFileName);
- if (!$tresultS3) {
- $tFileName = 'd_' . $detail['id'] . '.jpg';
- $tresultS3 = Yii::app()->tamazon->isObjectExist($tFilePath, $tFileName);
- }
- $detail['image_url'] = "";
- if (!$tresultS3) {
- //hinding temporarly
- /* $filePath = 'uploads/tagverts';
- $fileName = 'd_'.$detail['id'].'.png';
- $resultS3 = Yii::app()->tamazon->isObjectExist($filePath, $fileName);
- if(!$resultS3){
- $fileName = 'd_'.$detail['id'].'.jpg';
- $resultS3 = Yii::app()->tamazon->isObjectExist($filePath, $fileName);
- if(!$resultS3) */
- continue;
- /* }
- $imageDataS3 = Yii::app()->tamazon->getObject($filePath, $fileName);
- $imageData = UserImages::createThumb($imageDataS3['Body'], 40, 40);
- $uResultS3 = Yii::app()->tamazon->uploadObject($tFilePath, $tFileName, $imageData); */
- }
- $detail['image_url'] = sprintf('http://%s.s3.amazonaws.com/uploads/tagverts/thumbnail_1/%s', Yii::app()->tamazon->bucketRoot, $tFileName);
- $result[] = $detail;
- if (sizeof($result) == $count)
- break;
- }
- return $result;
- }
- }
- public function paymentCheckout($data) {
- $criteria = new CDbCriteria;
- $criteria->select = 'community_id, stock, price, price_wallet, email, catalog_name';
- $transaction = Yii::app()->db->beginTransaction();
- $cart = json_decode($data['item']);
- $purchased_item_ids = array();
- $global_items_ids = array();
- $total_delivery = 0;
- $collection = Yii::app()->edmsMongoCollection('deals');
- $order_id = $this->userId . time();
- foreach ($cart as $catalog_id => $catalog) {
- $catalog_wise_purchased_item_ids = array();
- $deal = $collection->findOne(array("_id" => new MongoID($catalog_id)));
- if (!$deal)
- throw new CHttpException(403, "invalid_deal");
- $items = $deal['items'];
- $delivery_charge = $deal['delivery_options']['amount'];
- $items_ids = array();
- foreach ($items as $item) {
- $items_ids[] = $item['id'];
- $catalog_details = Catalog::model()->findByPk($item['id'], $criteria);
- $item_details[$item['id']]['stock'] = intval($catalog_details['stock']);
- $item_details[$item['id']]['price'] = $catalog_details['price'];
- $item_details[$item['id']]['wallet_id'] = $catalog_details['price_wallet'];
- $item_details[$item['id']]['delivery_amount'] = $deal['delivery_options']['amount'];
- $item_details[$item['id']]['delivery_wallet_id'] = $deal['delivery_options']['wallet_id'];
- $item_details[$item['id']]['email'] = $catalog_details['email'];
- $item_details[$item['id']]['name'] = $catalog_details['catalog_name'];
- $item_details[$item['id']]['community_id'] = $catalog_details['community_id'];
- }
- foreach ($catalog as $cart_details) {
- $cart_item_id = $cart_details->item;
- $global_items_ids[$cart_item_id] += $cart_details->count;
- $emaildata['item_id'] = $cart_item_id;
- $emaildata['item_name'] = $item_details[$cart_item_id]['name'];
- $emaildata['email'] = $item_details[$cart_item_id]['email'];
- $emaildata['quantity'] = $global_items_ids[$cart_item_id];
- $emaildata['price'] = $item_details[$cart_item_id]['price'];
- $emaildata['community_id'] = $item_details[$cart_item_id]['community_id'];
- $emailinfo[] = $emaildata;
- //this is for checking item exists as well as stock. if no item, 'if' succeed
- if ($cart_details->count > $item_details[$cart_item_id]['stock']) {
- $response['result']['error'] = 'insufficient_stock';
- $response['result']['values'] = array('item_id' => $cart_item_id, 'stock' => $item_details[$cart_item_id]['stock']);
- $response['status'] = 'failed';
- Rest::sendResponse(403, json_encode($response, JSON_NUMERIC_CHECK));
- } else {
- $merchant_pay[$deal['owner']['id']] += ($item_details[$cart_item_id]['price'] * $cart_details->count);
- $total_amount += ($item_details[$cart_item_id]['price'] * $cart_details->count);
- $item_wallets[$item_details[$cart_item_id]['wallet_id']] = $item_details[$cart_item_id]['wallet_id'];
- }
- }
- $items_missing = array_diff($catalog_wise_purchased_item_ids, $items_ids);
- if (sizeof($items_missing) > 0) {
- $miss_details[$catalog_id] = $items_missing;
- $response['result']['error'] = 'items_does_not_exists';
- $response['result']['values'] = $miss_details;
- $response['status'] = 'failed';
- Rest::sendResponse(403, json_encode($response, JSON_NUMERIC_CHECK));
- }
- $merchant_pay[$deal['owner']['id']] += $delivery_charge;
- $total_amount += $delivery_charge;
- $total_delivery += $delivery_charge;
- }
- $item_wallets = array_values($item_wallets);
- if (sizeof($item_wallets) > 1)
- throw new CHttpException(403, "clubbing_multiple_currencies_not_available");
- foreach ($global_items_ids as $item => $count) {
- if ($count > $item_details[$item]['stock']) {
- $response['result']['error'] = 'insufficient_stock';
- $response['result']['values'] = array('item_id' => $item, 'stock' => $item_details[$item]['stock']);
- $response['status'] = 'failed';
- Rest::sendResponse(403, json_encode($response, JSON_NUMERIC_CHECK));
- }
- if ($item_details[$item]['delivery_amount'] > 0) {
- if ($item_wallets[0] != $item_details[$item]['delivery_wallet_id']) {
- $response['result']['error'] = 'delivery_not_available';
- $response['result']['values'] = array('item_id' => $item, 'delivery_wallet_id' => $item_details[$item]['delivery_wallet_id']);
- $response['status'] = 'failed';
- Rest::sendResponse(403, json_encode($response, JSON_NUMERIC_CHECK));
- }
- }
- }
- //amount sent is differnt from actual amount
- if ($total_amount != $data['amount'])
- throw new CHttpException(403, "item_or_delivery_amount_changed");
- $response = array();
- //validations OK. process payment
- if ($data['payment_method'] == 'tagcash') {
- $stat = 0;
- $data['ref_id'] = 1;
- if ($data['amount'] > 0) {
- $result = $this->itemPurchasePayment($merchant_pay, $this->userId, $item_wallets[0], $order_id);
- if ($result) {
- $data['ref_id'] = $response['reference_id'] = $result;
- $stat = 1;
- } else
- return false;
- }
- }
- if ($data['payment_method'] == 'bank') {
- $data['payment_details'] = json_decode($data['payment_details'], true);
- $stat = 0;
- if ($data['payment_details']['bank_code'] && $data['payment_details']['banking_method'] && $data['payment_details']['date'] && $data['payment_details']['time']) {
- if (Banks::isExisting($data['payment_details']['bank_code'])) {
- $response['status'] = "success";
- $txn = new PayTransactions('initial');
- $txn->refno = uniqid(rand(10 * 45, true));
- $txn->txnid = (isset($data['payment_details']['transaction_id'])) ? $data['payment_details']['transaction_id'] : rand() . time();
- $txn->depositor_id = 2;
- $txn->depositor_type = 2;
- $txn->email = $this->user->user_email;
- $txn->amount = array_sum($merchant_pay);
- $txn->currency = "PHP";
- $txn->status = "P";
- $txn->digest = sha1($txn->depositor_id . ':' . $txn->depositor_type . ':' . $txn->txnid . ':' . $txn->email . ':' . $txn->currency);
- $txn->proc_id = ($data['payment_details']['banking_method'] == "otc") ? $data['payment_details']['bank_code'] . "X" : $data['payment_details']['bank_code'] . "C";
- $txn->agree_to_terms = 1;
- if ($txn->validate() && $txn->save()) {
- $deposit = DepositConfirmations::model()->findByAttributes(array('refno' => $txn->txnid));
- $txnDate = explode(' ', $data['payment_details']['date']);
- $model = new DepositConfirmations;
- $model->refno = $txn->refno;
- $model->amount = $txn->amount;
- $model->txnid = $txn->txnid;
- $model->date = date('Y-m-d', strtotime($data['payment_details']['date']));
- $model->time = $data['payment_details']['time'];
- if ($model->validate() && $model->save()) {
- /* notify admin */
- $txnDetails = PayTransactions::getData($txn->refno);
- $settings = array(
- 'view' => 'notify',
- 'subject' => "TAGPay Request",
- );
- $emaildata = array(
- 'email' => "accounts@tagcash.com",
- 'data' => $txnDetails,
- );
- $mail = new TagbondMail;
- $mail->sendTagbondMail($settings, $emaildata);
- }
- $data['ref_id'] = $response['reference_id'] = $txn->refno;
- if (SELF::updateItemPurchaseMerchantPayments($merchant_pay, 3, $item_wallets[0], $data['ref_id'], $order_id))
- $stat = 1;
- else
- return false;
- }
- }else {
- throw new CHttpException(403, "bank_not_found");
- }
- } else {
- throw new CHttpException(403, "missing_payment_details");
- }
- }
- if ($data['payment_method'] == '7connect') {
- $stat = 0;
- $modelCliqq = new CliqqLog;
- $settings = SiteSettings::getSettings();
- $transactURL = $this->thisObj->_SETTINGS->{'7Connect_turl'};
- $transactionKey = $this->thisObj->_SETTINGS->{'7Connect_transactionkey'};
- $merchantId = $this->thisObj->_SETTINGS->{'7Connect_merchantId'};
- $merchantRef = rand() . time();
- $successURL = Yii::app()->createAbsoluteUrl('credit/saveCliqqStatus', array('access_token' => $_POST['access_token']));
- $failURL = Yii::app()->createAbsoluteUrl('credit/saveCliqqStatus', array('access_token' => $_POST['access_token']));
- $token = sha1($merchantId . $merchantRef . '{' . $transactionKey . '}');
- $modelCliqq->user_id = 2;
- $modelCliqq->user_type = 2;
- $modelCliqq->website = 2;
- $modelCliqq->wallet_id = 1;
- $modelCliqq->amount = array_sum($merchant_pay);
- $modelCliqq->reference_id = $merchantRef;
- if ($modelCliqq->save()) {
- $fields = array(
- 'merchantID' => $merchantId,
- 'merchantRef' => $merchantRef,
- 'amount' => array_sum($merchant_pay),
- 'successURL' => $successURL,
- 'failURL' => $failURL,
- 'token' => $token,
- 'transactionDescription' => 'Tagcash Deposit via 7connect - ' . array_sum($merchant_pay),
- 'returnPaymentDetails' => 'Y'
- );
- $params = http_build_query($fields);
- $response['link'] = $transactURL . '?' . $params;
- $response['reference_id'] = $merchantRef;
- $data['ref_id'] = $merchantRef;
- if (SELF::updateItemPurchaseMerchantPayments($merchant_pay, 2, $item_wallets[0], $merchantRef, $order_id))
- $stat = 1;
- else
- return false;
- }
- else {
- return false;
- }
- }
- if ($data['payment_method'] == 'agent') {
- $stat = 0;
- $agentObj = new PaybyagentLog();
- $agentObj->setIdentity($this->thisObj);
- foreach ($merchant_pay as $merchant_id => $amount) {
- $log['beneficiary_id'] = $merchant_id;
- $log['beneficiary_type'] = 2;
- $log['wallet_id'] = $item_wallets[0];
- $log['amount'] = $amount;
- $log['custom'] = 'catalog purchase';
- $logs[] = $log;
- }
- $agent_ref = $agentObj->logTransaction($logs, true);
- if ($agent_ref) {
- if (SELF::updateItemPurchaseMerchantPayments($merchant_pay, 4, $item_wallets[0], $agent_ref, $order_id)) {
- $stat = 1;
- $data['ref_id'] = $response['reference_id'] = $agent_ref;
- } else
- return false;
- } else
- return false;
- }
- if ($stat === 1) {
- foreach ($cart as $catalog_id => $catalog) {
- $deal_data = array();
- $deal_data['purchased_items'] = $catalog;
- $deal_data['delivery_address'] = $data['delivery_address'];
- $deal_data['amount'] = $data['amount'] ? $data['amount'] : 0;
- if ($deal_data['delivery_method']) {
- $deal_data['delivery_method']['method'] = $data['delivery_method'];
- }
- $deal_data['payment_method'] = $data['payment_method'];
- $deal_data['transaction_id'] = $data['ref_id'];
- $deal_data['wallet_id'] = $item_wallets[0];
- $deal_data['order_id'] = $order_id;
- $deal_stat = Deals::takeDeal($catalog_id, NULL, NULL, $deal_data);
- }
- foreach ($global_items_ids as $item => $count) {
- SELF::updateStock($item, $count);
- }
- if ($transaction) {
- $transaction->commit();
- }
- $response['order_id'] = $order_id;
- //send GCM notification
- //send notifiction to user who placed the order
- $message = array(
- 'message' => 'Your catalog purchase order on Miskio is confirmed #' . $order_id,
- 'user_id' => $this->user->id,
- 'user_type' => 1,
- 'notification_type' => 17,
- 'count' => 1
- //'vibrate' => 1,
- //'sound' => 1
- );
- //sendMessage
- Gcm::sendMessage($message);
- //send order details - email
- //email to user and item owner
- $user_email = $this->user->user_email;
- $user_settings = array(
- 'view' => 'common',
- 'subject' => 'Your order is confirmed #' . $order_id
- );
- $user_body = '
- Thank you for placing an order with ' . $this->thisObj->_CLIENTDETAILS['name'] . '!<br/><br/>Order Id : #' . $order_id . '<br/><br/>
- <table width="100%" cellpadding="5">
- <tr bgcolor="#eb3f3c">
- <td><font color="#FFF">Item</font></td><td width="15%"><font color="#FFF">Quantity</font></td><td width="15%"><font color="#FFF">Price</font></td><td width="25%"><font color="#FFF">Price Total</font></td>
- </tr>
- ';
- $settings = array(
- 'view' => 'common',
- 'subject' => 'New purchase order #' . $order_id
- );
- $gross = 0;
- $wallet = WalletTypes::getWalletName($item_wallets[0], true);
- foreach ($emailinfo as $iteminfo) {
- if ($iteminfo['email']) {
- $body = 'One of the user has placed an order!<br/><br/>
- <table width="100%"><tr><td width="25%">
- Order Id </td><td>' . $order_id . '</td></tr>';
- $body .= '<tr><td>Item </td><td> ' . $iteminfo['item_name'] . '(#' . $iteminfo['item_id'] . ')</td></tr>
- <tr><td>Quantity </td><td> ' . $iteminfo['quantity'] . '</td></tr>
- <tr><td>User </td><td> ' . $this->user->user_firstname . ' ' . $this->user->user_lastname . '</td></tr>
- <tr><td>Delivery Address </td><td> ' . $data['delivery_address'] . '</td></tr>
- <tr><td><b>Payment details</b></td></tr>
- <tr><td>Payment method</td><td> ' . $data['payment_method'] . '</td></tr>
- <tr><td>Transaction Id</td><td>' . $data['ref_id'] . '</td></tr>';
- if ($data['payment_method'] == 'bank')
- $body .= '<tr><td></td><td>' . $data['payment_details'] . '</td></tr><tr><td></td></tr>';
- $body .='</table>';
- $data_arr = array(
- 'email' => $iteminfo['email'],
- 'head' => $this->thisObj->_CLIENTDETAILS['name'],
- 'message' => $body
- );
- $mail = new TagbondMail();
- $mail->sendTagbondMail($settings, $data_arr, '');
- }
- //send notifiction to merchant : product owner
- $message = array(
- 'message' => 'Received a Miskio purchase order #' . $order_id,
- 'user_id' => $iteminfo['community_id'],
- 'user_type' => 2,
- 'notification_type' => 18,
- 'count' => 1
- //'vibrate' => 1,
- //'sound' => 1
- );
- //sendMessage
- Gcm::sendMessage($message);
- $total_price = intval($iteminfo['quantity']) * floatval($iteminfo['price']);
- $gross += $total_price;
- $user_body .= '
- <tr>
- <td>' . $iteminfo['item_name'] . '</td><td align="center">' . $iteminfo['quantity'] . '</td><td align="center">' . round($iteminfo['price'], 2) . ' ' . $wallet . '</td><td align="center">' . round($total_price, 2) . ' ' . $wallet . '</td>
- </tr>';
- }
- $user_body .= '</table><table width = "100%"><tr><td></td></tr>
- <tr>
- <td width="25%"><b>Delivery charges</b></td><td colspan="3">: ' . $total_delivery . ' ' . $wallet . '</td>
- </tr>
- <tr>
- <td><b>Gross Total</b></td><td colspan="3">: ' . ($gross + $total_delivery) . ' ' . $wallet . '</td>
- </tr>
- <tr>
- <td>Delivery Address</td><td colspan="3">: ' . $data['delivery_address'] . '</td>
- </tr></table>';
- $user_body .= '<table><tr><th>
- Payment Details </th></tr>
- <tr><td>Payment method </td><td>: ' . $data['payment_method'] . '</td></tr>
- <tr><td>Transaction Id </td><td>: ' . $data['ref_id'] . '</td></tr></table>';
- if ($data['payment_method'] == '7connect') {
- $user_body .= 'Please make payment<br/>
- Payment Url : ' . $response['link'] . '<br/>';
- }
- $data_arr = array(
- 'email' => $user_email,
- 'head' => $this->thisObj->_CLIENTDETAILS['name'],
- 'toName' => ucfirst($this->user->user_firstname . ' ' . $this->user->user_lastname),
- 'message' => $user_body
- );
- $mail_u = new TagbondMail();
- $mail_u->sendTagbondMail($user_settings, $data_arr, '');
- return $response;
- } else {
- return false;
- }
- }
- public static function updateStock($item_id, $count) {
- try {
- $result = Catalog::model()->findByPk($item_id);
- $result->stock -= $count;
- $result->save();
- $collection = Yii::app()->edmsMongoCollection('deals');
- $deals = $collection->find(array('items.id' => $item_id));
- if ($deals) {
- foreach ($deals as $deal) {
- $item_list = array();
- $items = $deal['items'];
- foreach ($items as $item) {
- $update_item = $item;
- if ($item['id'] == $item_id) {
- if ($item['stock'] > 0) {
- $update_item['stock'] = $item['stock'] - $count;
- }
- }
- //$update_item['stock'] = $update_item['stock']>=0?intval($update_item['stock']):0;
- $item_list[] = $update_item;
- }
- $collection->update(
- array(
- "_id" => new MongoID($deal['_id']->__toString()),
- ), array('$set' => array("items" => $item_list))
- );
- }
- }
- } catch (Exception $e) {
- }
- }
- /* public function payForItems($params){
- $collection = Yii::app()->edmsMongoCollection('deals');
- $deal = $collection->findOne(array("_id" => new MongoID($params['deal_id'])));
- //validations
- if(!$deal)
- throw new CHttpException(403, "invalid_deal");
- $items = $deal['items'];
- $purchased_items = $params['catalog_item'];
- $pitems = array_keys($purchased_items);
- $total_weight = 0;
- //get Item ids, weight for delivery charges
- foreach($items as $item){
- $item_id[] = $item['id'];
- if(in_array($item['id'], $pitems)){
- $item_price+= ($item['price']['amount'])*$purchased_items[$item['id']];
- $item_wallet[$item['price']['wallet_id']]++;
- $total_weight += $item['weight'];
- }
- }
- //calculate delivery cost
- $delivery_cost = 0;
- if(isset($params['delivery_method'])){
- if($params['delivery_method']['method'] == 'xend'){
- $xendObj = new Xend(SiteSettings::getSettings());
- $delivery_cost = $xendObj->calculate($params['province'], $params['pouch'], $total_weight);
- }
- else{
- if($deal['delivery_options']['amount'] > 0 && $deal['delivery_options']['wallet_id'] > 0) {
- $delivery_cost = $deal['delivery_options']['amount'];
- }
- }
- }
- $total_amount = $item_price+$delivery_cost;
- //amount sent is differnt from actual amount
- if($total_amount != $params['amount'])
- throw new CHttpException(403, "item_or_delivery_amount_changed");
- //multiple wallet types
- if(sizeof($item_wallet)!=1){
- throw new CHttpException(403, "clubbing_multiple_wallet_types");
- }
- else{
- reset($item_wallet);
- $wallet = key($item_wallet);
- if($wallet != $params['wallet_id']){
- throw new CHttpException(403, "wallet_missmatch");
- }
- }
- //check all passed items are active in deal
- $result = array_intersect($pitems, $item_id);
- if(sizeof($result) != sizeof($purchased_items)){
- throw new CHttpException(403, "all_items_not_available");
- }
- //validation ends
- //reset($item_wallet);
- //$wallet = key($item_wallet);
- //$converted_amount = Currency::convertCurrency($params['amount'], $wallet, WalletTypes::getWalletName($params['wallet_id'],true));
- $data = array();
- $data['purchased_items'] = $purchased_items;
- $data['delivery_address'] = $params['delivery_address'];
- $data['amount'] = $params['amount']?$params['amount']:0;
- $data['item_details'] = $params['item_details'];
- if($params['delivery_method']){
- $data['delivery_method']['method'] = $params['delivery_method'];
- $data['delivery_method']['amount'] = $delivery_cost;
- }
- if($params['payment_method'] == 'tagcash'){
- $stat = 1;
- if($params['amount'] > 0){
- $transaction = Yii::app()->db->beginTransaction();
- $stat = Deals::transferPayment($params['amount'],$this->userId,1,$deal['owner']['id'],2,$params['wallet_id'],'catalog_purchase',true);
- }
- if(is_numeric($stat)){
- $data['payment_method'] = $params['payment_method'];
- $data['transaction_id'] = $stat;
- $deal_stat = SELF::takeDeal($params['deal_id'], NULL, NULL, $data);
- if($deal_stat){
- if($transaction)
- $transaction->commit();
- return $stat;
- }
- }
- else{
- if($stat['transfer_amount'][0])
- throw new CHttpException(403, $stat['transfer_amount'][0]);
- }
- }
- if($params['payment_method'] == 'bank'){
- $stat = 1;
- if(isset($params['ref_id'])){
- //verify ref id exists in table
- }
- else{
- return false;
- }
- $data['payment_method'] = $params['payment_method'];
- $data['transaction_id'] = $params['ref_id'];
- $deal_stat = SELF::takeDeal($params['deal_id'], NULL, NULL, $data);
- if($deal_stat){
- if($transaction)
- $transaction->commit();
- return $stat;
- }
- }
- if($params['payment_method'] == '7connect'){
- $stat = 1;
- if(isset($params['ref_id'])){
- //verify ref id exists in table
- }
- else{
- return false;
- }
- $data['payment_method'] = $params['payment_method'];
- $data['transaction_id'] = $params['ref_id'];
- $deal_stat = SELF::takeDeal($params['deal_id'], NULL, NULL, $data);
- if($deal_stat){
- if($transaction)
- $transaction->commit();
- return $stat;
- }
- }
- return false;
- } */
- public function updateDeliveryOptions($params) {
- $collection = Yii::app()->edmsMongoCollection('deals');
- $deal = $collection->findOne(array("_id" => new MongoID($params['deal_id'])));
- ///need to check permission for updating
- if ($deal) {
- $collection->update(
- array(
- "_id" => new MongoID($params['deal_id']),
- ), array('$set' => array("delivery_options" => $params['delivery_options']))
- );
- return true;
- } else {
- return false;
- }
- }
- public function getDeliveryOptions($deal_id) {
- $collection = Yii::app()->edmsMongoCollection('deals');
- $deal = $collection->findOne(array("_id" => new MongoID($deal_id), "delivery_options" => array('$exists' => true)));
- if (isset($deal['delivery_options']))
- return $deal['delivery_options'];
- else
- return '';
- }
- public function markFavorite($deal_id) {
- $collection = Yii::app()->edmsMongoCollection('deals');
- $deal = $collection->findOne(array("_id" => new MongoID($deal_id)));
- if ($deal) {
- $favorites = array();
- if (isset($deal['users_favorite']))
- $favorites = $deal['users_favorite'];
- if (in_array($this->userId, $favorites)) {
- if (($key = array_search($this->userId, $favorites)) !== false)
- unset($favorites[$key]);
- $favorites = array_values($favorites);
- $result = 'removed_from_favorites';
- }
- else {
- $favorites[] = $this->userId;
- $result = 'added_to_favorites';
- }
- $collection->update(
- array(
- "_id" => new MongoID($deal_id),
- ), array('$set' => array("users_favorite" => $favorites))
- );
- return $result;
- } else {
- return false;
- }
- }
- public static function getFavoriteDeals($userId, $pageOffset, $pageCount) {
- $collection = Yii::app()->edmsMongoCollection('deals');
- $query['users_favorite'] = array('$in' => array($userId));
- $result = $collection->find($query)
- ->skip($pageOffset)
- ->limit($pageCount);
- $response = array();
- if ($result) {
- $data = array();
- foreach ($result as $deal) {
- $details = SELF::formatDeal($deal, false, null, $userId);
- $response[] = $details;
- }
- }
- return $response;
- }
- public function gameSlotAward($details) {
- $dealId = $details['deal_id'];
- $assigneeId = $details['user_id'];
- if (!TagMongo::isValidId($dealId)) {
- throw new CHttpException(404, "invalid_deal_id");
- }
- $userId = $this->userId;
- $collection = Yii::app()->edmsMongoCollection('deals');
- $deal = (object) $collection->findOne(array("_id" => new MongoID($dealId)));
- //check deal validity
- if (!$deal) {
- throw new CHttpException(404, "invalid_deal");
- } else if ($deal->status != 1) {
- throw new CHttpException(403, "deal_unavailable");
- }
- $checkMember = CommunityUsers::model()->findByAttributes(array("user_id" => $assigneeId, "community_id" => $deal->owner['id']));
- //if not member; automatically adds
- if (!$checkMember) {
- $role = CommunityRoles::model()->findByAttributes(array('community_id' => $deal->owner['id'], 'role_default' => '1'));
- $roleId = $role->id;
- $modelUsers = new CommunityUsers;
- $modelUsers->user_id = $assigneeId;
- $modelUsers->community_id = $deal->owner['id'];
- $modelUsers->role_id = $roleId;
- $modelUsers->communityuser_status = 1;
- $modelUsers->communityuser_relation = 1;
- $modelUsers->save();
- }
- $liveDeal = new stdClass();
- $liveDeal->deal_id = new MongoID($dealId);
- $liveDeal->type = $deal->type;
- $liveDeal->owner = $deal->owner;
- $liveDeal->title = $deal->title;
- $liveDeal->description = $deal->description;
- $liveDeal->hiddenDescription = $deal->hiddenDescription;
- $liveDeal->start_date = $deal->start_date;
- $liveDeal->end_date = $deal->end_date;
- $liveDeal->city = $deal->city;
- $liveDeal->town = $deal->town;
- $liveDeal->zipCode = $deal->zipCode;
- $liveDeal->date_taken = date('Y-m-d');
- $liveDeal->date_redeemed = "";
- $liveDeal->auto = $deal->auto;
- $liveDeal->country = $deal->country;
- $liveDeal->visibility = $deal->visibility;
- $liveDeal->tags = $deal->tags;
- $liveDeal->dealinfo = $deal->dealinfo;
- $liveDeal->roles = $deal->roles;
- $liveDeal->limits = $deal->limits;
- $liveDeal->total_value = $deal->total_value;
- $liveDeal->credit_type = $deal->credit_type;
- if ($deal->methodOfPayment) {
- $liveDeal->methodOfPayment = $deal->methodOfPayment;
- }
- if ($deal->digitalDelivery) {
- $liveDeal->digitalDelivery = $deal->digitalDelivery;
- }
- if ($deal->pickUpAddress) {
- $liveDeal->pickUpAddress = $deal->pickUpAddress;
- }
- if ($deal->price) {
- $liveDeal->price = $deal->price;
- }
- if ($deal->affiliate_fee) {
- $liveDeal->affiliate_fee = $deal->affiliate_fee;
- }
- if ($deal->rewardinfo) {
- $liveDeal->rewardinfo = $deal->rewardinfo;
- }
- if ($deal->pay_per_take)
- $liveDeal->pay_per_take = $deal->pay_per_take;
- if ($deal->pay_per_click)
- $liveDeal->pay_per_click = $deal->pay_per_click;
- $liveDeal->module = $deal->module;
- if ($deal->module == "ecommerce") {
- $liveDeal->status = 9;
- } else {
- $liveDeal->status = 8;
- }
- $liveDeal->user_id = intval($assigneeId);
- $liveDeal->assigner_id = intval($userId);
- $user = Users::model()->findByPk($assigneeId);
- if (!$user) {
- throw new CHttpException(403, "user_doesnt_exist");
- }
- if ($deal->type == "stamp") {
- $userinfo = new stdClass;
- $userinfo->id = intval($user->id);
- $userinfo->user_firstname = $user->user_firstname;
- $userinfo->user_lastname = $user->user_lastname;
- $liveDeal->stamp_log = array();
- $liveDeal->stamp_notes = array();
- } else {
- $userinfo = new stdClass;
- $userinfo->id = intval($user->id);
- $userinfo->user_firstname = $user->user_firstname;
- $userinfo->user_lastname = $user->user_lastname;
- }
- //ticket
- if ($deal->type == "ticket" && $deal->module == "ecommerce") {
- $purchasedTickets = array('history' => array(), 'tickets' => array());
- $liveDeal->purchasedTickets = $purchasedTickets;
- }
- if ($deal->type == "catalog") {
- if (!isset($details['item_id']) || $details['item_id'] < 1)
- throw new CHttpException(403, "invalid_item");
- $items = $deal->items;
- foreach ($items as $item) {
- if ($details['item_id'] == $item['id']) {
- $item_details = $item;
- $item_details['count'] = 1;
- break;
- }
- }
- if (!item_details) {
- throw new CHttpException(403, "item_doesnot_exists");
- } else {
- $liveDeal->purchase_details['items'] = $item_details;
- $liveDeal->purchase_details['delivery_address'] = $details['delivery_address'];
- $liveDeal->purchase_details['delivery_method'] = array();
- $liveDeal->purchase_details['payment_details']['total_amount'] = 0;
- $liveDeal->purchase_details['payment_details']['paid_using'] = 'gameslotaward';
- $liveDeal->purchase_details['payment_details']['transaction_id'] = '';
- }
- } else {
- $liveDeal->paid = 'yes';
- $liveDeal->paidUsing = 'gameslotaward';
- }
- $liveDeal->userinfo = $userinfo;
- $liveDeal->orderedDate = date("Y-m-d H:i:s");
- $liveDeal->orderItemCount = 1;
- $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
- $liveCollection->insert($liveDeal);
- return true;
- }
- public static function bookABus($id, $passengers, $obj) {
- $originalTagvert = Yii::app()->edmsMongoCollection('deals');
- $deal = $originalTagvert->findOne(array("_id" => new MongoID($id)));
- $deal['dealinfo']['passengers'] = json_decode($passengers, true);
- //check if available seats
- if ($deal['dealinfo']['bus_info']['available'] < count($deal['dealinfo']['passengers'])) {
- throw new CHttpException(403, "insufficient_seats");
- }
- //check if seats are available
- $occupiedSeats = Deals::getOccupiedSeats($id);
- foreach ($deal['dealinfo']['passengers'] as $v) {
- if (in_array($v['seat_no'], $occupiedSeats)) {
- throw new CHttpException(403, "seat_not_available");
- }
- }
- $total = 0;
- $totalSeatPrice = ($deal['dealinfo']['price'] * count($deal['dealinfo']['passengers']));
- $total += $totalSeatPrice;
- //add reservation fee
- if ($deal['price']) {
- $total += $deal['price']['amount'];
- }
- $mealArr = array();
- $totalMealPrice = 0;
- if ($deal['dealinfo']['passengers']) {
- foreach ($deal['dealinfo']['passengers'] as $v) {
- if ($v['meals']) {
- foreach ($v['meals'] as $m) {
- if (array_key_exists($m['meal'], $mealArr)) {
- $mealArr[$m['meal']] += 1;
- } else {
- $mealArr[$m['meal']] = 1;
- }
- $totalSeatPrice += $m['price'];
- $totalMealPrice += $m['price'];
- }
- }
- }
- }
- $additional = '';
- if ($mealArr) {
- $mealsStr = '';
- foreach ($mealArr as $k => $m) {
- $mealsStr .= $k . " x" . $m . ",";
- }
- $additional = 'Meals (' . trim($mealsStr, ",") . ' = total of ' . $totalMealPrice . ')';
- }
- if (!WalletBalances::checkIfCanPay($obj->_USERID, 1, 1, $total)) {
- throw new CHttpException(403, "insufficient_funds");
- }
- $d = new Deals;
- $d->setIdentity($obj);
- //take tagvert
- if ($d->takeDeal($id, null, null, $deal['dealinfo']['passengers'])) {
- $transfer = new WalletTransfers();
- $transfer->setIdentity($obj);
- $transfer->reference_id = uniqid() . rand(10 * 45, 100 * 98);
- $transfer->transfer_from_amount = $totalSeatPrice;
- $transfer->transfer_amount = NULL;
- $transfer->transfer_from_id = $obj->_USERID;
- $transfer->transfer_from_type = 1;
- $transfer->walletFrom = $deal['price']['wallet_id'];
- $transfer->transfer_to_amount = $total;
- $transfer->transfer_narration = "Payment for " . $deal['dealinfo']['bus_info']['name'] . " seats. " . $deal['dealinfo']['price'] . " per seat (x" . count($deal['dealinfo']['passengers']) . ") " . $additional . " - total of " . WalletTypes::getWalletName($deal['price']['wallet_id'], true) . " " . $totalSeatPrice;
- $transfer->setTo(2, $deal['owner']['id']);
- $transfer->setType(1);
- $transfer->setWallets($transfer->walletFrom, $transfer->walletFrom);
- $transfer->transfer();
- //update bus tagvert's available seats
- $originalTagvert->update(array(
- "_id" => new MongoID($id),
- ), array(
- '$set' => array(
- 'dealinfo.bus_info.available' => $deal['dealinfo']['bus_info']['available'] - count($deal['dealinfo']['passengers'])
- )
- )
- );
- return true;
- }
- return false;
- }
- public static function getOccupiedSeats($dealId) {
- if (!TagMongo::isValidId($dealId)) {
- throw new CHttpException(404, invalid_deal_id);
- }
- $collection = Yii::app()->edmsMongoCollection('deals_live');
- $live = $collection->find(array('deal_id' => new MongoId($dealId)));
- $seats = array();
- if ($live->count()) {
- foreach ($live as $v) {
- $passengers = $v['dealinfo']['passengers'];
- foreach ($passengers as $p) {
- $seats[] = $p['seat_no'];
- }
- }
- }
- return $seats;
- }
- public function getBusTicket($dealId, $id) {
- if (!TagMongo::isValidId($dealId)) {
- throw new CHttpException(404, invalid_deal_id);
- }
- $details = $this->getLiveDealDetails($dealId, $id);
- $ticket = array();
- if ($details) {
- $ticket['booked_by'] = $details->userinfo;
- $ticket['date_reserved'] = $details->userinfo['taken_date'];
- $ticket['route_from'] = BusReservationRoutes::getRouteName($details->dealinfo['route_from']);
- $ticket['route_to'] = BusReservationRoutes::getRouteName($details->dealinfo['route_to']);
- $ticket['date_time'] = date('D d M', strtotime($details->dealinfo['date'])) . ' ' . $details->dealinfo['departure_time'] . ' - ' . $details->dealinfo['arrive_time'];
- $ticket['issued'] = "Tagcash";
- $ticket['passengers_count'] = sizeOf($details->dealinfo['passengers']);
- $ticket['passengers'] = $details->dealinfo['passengers'];
- if ($details->price) {
- $ticket['price'] = $details->price;
- }
- }
- return $ticket;
- }
- public static function createResume($data) {
- $collection = Yii::app()->edmsMongoCollection('user_resumes');
- return $collection->insert((object) $data);
- }
- public static function updateResume($id, $data) {
- $collection = Yii::app()->edmsMongoCollection('user_resumes');
- $update = $collection->update(array(
- '_id' => new MongoId($id)
- ), array('$set' => array('resume_info' => $data)
- )
- );
- return $update;
- }
- public static function getResumes($id, $offset = 0, $limit = 20) {
- $collection = Yii::app()->edmsMongoCollection('user_resumes');
- if ($id) {
- $query = $collection->findOne(array('_id' => new MongoId($id)));
- } else {
- $query = $collection->find()->sort(array('created_date' => -1))->skip($offset)->limit($limit);
- if ($query) {
- $resumes = array();
- foreach ($query as $v) {
- $resumes[] = $v;
- }
- $query = $resumes;
- }
- }
- return $query;
- }
- public static function deleteResume($id) {
- $collection = Yii::app()->edmsMongoCollection('user_resumes');
- $query = $collection->remove(array('_id' => new MongoId($id)));
- return $query;
- }
- public function getItems($filter) {
- $parsedDeals = array();
- $query = array();
- $deal_type_master_list = array();
- //sorting ( by cost_per_view) descending order
- $sort = array("cost_per_view.amount" => -1, "status" => 1, "end_date" => 1);
- if ($filter['loc']) {
- $location['long'] = $filter['loc']['long'];
- $location['lat'] = $filter['loc']['lat'];
- }
- $collection = Yii::app()->edmsMongoCollection('deals');
- $query['type'] = 'catalog';
- $query['items'] = array('$exists' => true, '$ne' => null, '$not' => array('$size' => 0));
- $query['status'] = 1;
- $query["end_date"] = array('$gte' => date('Y-m-d'));
- if ($filter['country_id']) {
- //$query['country.id'] = intval($filter['country_id']);
- }
- if ($filter['deal_id'])
- $query['_id'] = new MongoID($filter['deal_id']);
- if (is_array($filter['tags'])) {
- $query['tags'] = array('$all' => $filter['tags']);
- }
- //filter by owner
- if ($filter['community_id']) {
- $query['owner.id'] = intval($filter['community_id']);
- $query['owner.type'] = 'community';
- }
- //$query['visibility'] = 'public';
- $query['switch'] = array('$ne' => intval(0));
- if ($location['long'] && $location['lat']) {
- $long = $location['long'];
- $lat = $location['lat'];
- if ($filter['distance'])
- $distance = $filter['distance'];
- else
- $distance = 2; // default 2km
- $query["location"] = array('$near' => array(floatval($long), floatval($lat)), '$maxDistance' => floatval($distance / 111.12));
- unset($query['$or']); // or wont work with $near geospacial
- $sort = array(); //no need of sort- automatically sorting via distance
- }
- //filter by category
- if ($filter['category_id']) {
- $query['category.id'] = $filter['category_id'];
- }
- //filter by catalog_id / item_id
- if ($filter['item_id']) {
- $query['items.id'] = intval($filter['item_id']);
- }
- //filter by hashtags
- if (is_array($filter['hashtags'])) {
- $query['$and'] = array();
- $orQ['$or'][] = array("title" => array('$in' => $filter['hashtags']));
- $orQ['$or'][] = array("items.hashtags" => array('$in' => $filter['hashtags']));
- $orQ['$or'][] = array("items.catalog_name" => array('$in' => $filter['hashtags']));
- $query['$and'] = array($orQ);
- //$query['items.hashtags'] = array('$all' => $filter['hashtags']);
- }
- // executing query
- //print_r(json_encode($query)); exit;
- $deals = $collection->find($query)
- ->sort($sort);
- // parsing the result
- if ($deals) {
- $items = array();
- $i = 0;
- foreach ($deals as $deal) {
- $image = array();
- $catalogImages = new CatalogImages;
- $items_count = sizeOf($deal['items']);
- foreach ($deal['items'] as $item) {
- if ($i < $this->pageOffset) {
- $i++;
- continue;
- }
- //filter by item id
- if ($filter['item_id'] && $item['id'] != $filter['item_id'])
- continue;
- if ($item['category'])
- unset($item['category']);
- if ($filter['hashtags'] && !empty($filter['hashtags'])) {
- if (!is_array($item['hashtags'])) {
- $item['hashtags'] = array();
- }
- if (empty(array_intersect($item['hashtags'], $filter['hashtags'])) && !in_array($deal['title'], $filter['hashtags']) && !in_array($item['catalog_name'], $filter['hashtags'])) {
- continue;
- }
- }
- $itm = SELF::formatItemDetails($item['id']);
- $itm['image'] = $catalogImages->getCatalogImages($item['id']) ? $catalogImages->getCatalogImages($item['id']) : $image;
- $itm['deal_id'] = $deal['_id']->__toString();
- $itm['title'] = $deal['title'];
- $itm['items_count'] = $items_count;
- $itm['item_rating'] = Ratings::getItemRate($item['id']);
- $itm['favorite_item'] = FavoriteCatalogs::checkFavourite($this->userId, $item['deal_id'], $item['id']);
- $itm['owner'] = self::formatOwner($deal['owner']);
- $itm['city'] = is_array($deal['city']) ? $deal['city']['name'] : $deal['city'];
- $itm['delivery_options'] = empty($deal['delivery_options']) ? (object) $deal['delivery_options'] : $deal['delivery_options'];
- $items[] = $itm;
- $i++;
- if ($i == $this->pageOffset + $this->pageCount)
- break;
- }
- if ($i == $this->pageOffset + $this->pageCount)
- break;
- }
- return $items;
- }
- return array();
- }
- public static function formatItemDetails($item_id) {
- $query = Yii::app()->db->createCommand()
- ->select('c.id,c.category_id,c.catalog_name,c.description,c.email,c.price,c.price_wallet,c.weight,c.sizes,c.colors,c.other,wt.currency_code,c.hashtags,c.time_to_ship,c.stock')
- ->from('catalog c')
- //select = cc.category_name + ->leftJoin("catalog_category cc", "cc.id = c.category_id")
- ->leftJoin("wallet_types wt", "wt.id = c.price_wallet")
- ->where('c.id = ' . $item_id);
- $item_details = $query->queryAll();
- $item_details = $item_details[0];
- $item['id'] = $item_id;
- $item['catalog_name'] = $item_details['catalog_name'];
- $item['description'] = $item_details['description'];
- $item['price']['amount'] = $item_details['price'];
- $item['price']['wallet_id'] = $item_details['price_wallet'];
- $item['price']['wallet_name'] = $item_details['currency_code'];
- $item['stock'] = $item_details['stock'];
- $item['category_id'] = $item_details['category_id'];
- $item['weight'] = $item_details['weight'];
- $item['email'] = $item_details['email'];
- $item['sizes'] = $item_details['sizes'] ? explode(',', $item_details['sizes']) : array();
- $item['colors'] = $item_details['colors'] ? explode(',', $item_details['colors']) : array();
- $item['other'] = $item_details['other'] ? explode(',', $item_details['other']) : array();
- $item['hashtags'] = $item_details['hashtags'] ? explode(',', $item_details['hashtags']) : array();
- $item['time_to_ship'] = $item_details['time_to_ship'];
- return $item;
- }
- public function listDealTypes($status = null) {
- $collection = Yii::app()->edmsMongoCollection('deals');
- $query['owner.id'] = intval($this->communityId);
- if ($status == 'active') {
- $query['status'] = 1;
- $query["end_date"] = array('$gte' => date('Y-m-d'));
- }
- $dealTypes = $collection->distinct("type", $query);
- return $dealTypes;
- }
- public function getOrderDetails($transaction_id) {
- $collection = Yii::app()->edmsMongoCollection('deals_live');
- $query['purchase_details.payment_details.transaction_id'] = $transaction_id;
- if (!$this->communityId) {
- $query['userinfo.id'] = intval($this->userId);
- } else if ($this->community['community_resellerid'] == NULL) {
- $query['owner.id'] = intval($this->communityId);
- $query['owner.type'] = 'community';
- }
- $orders = $collection->find($query, array('owner', 'purchase_details', 'userinfo'));
- if ($orders) {
- foreach ($orders as $order) {
- $order['purchase_details']['payment_details']['wallet_name'] = WalletTypes::getWalletName($order['purchase_details']['payment_details']['wallet_id'], true);
- if ($this->community['community_resellerid'] == NULL) {
- $return[] = array('owner' => $order['owner'], 'purchase_details' => $order['purchase_details'], 'userinfo' => $order['userinfo']);
- } else {
- $return[] = array('owner' => $order['owner'], 'payment_details' => $order['purchase_details']['payment_details'], 'userinfo' => $order['userinfo']);
- }
- }
- return $return;
- }
- throw new CHttpException(403, 'invalid_transaction_id');
- }
- }
- ?>
Add Comment
Please, Sign In to add comment