Guest User

Untitled

a guest
Dec 5th, 2016
343
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 352.13 KB | None | 0 0
  1. <?php
  2.  
  3. class Deals extends CFormModel {
  4.  
  5. //api result
  6. public $response;
  7. //pagination
  8. public $pageCount;
  9. public $pageOffset;
  10. //identity
  11. public $user;
  12. public $userId;
  13. public $communityId;
  14. public $thisObj;
  15. public $community;
  16. //General
  17. public $dealId;
  18. public $deal;
  19. //deal attributes
  20. public $type;
  21. public $owner;
  22. public $title;
  23. public $description;
  24. public $start_date;
  25. public $end_date;
  26. public $days;
  27. public $country;
  28. public $city;
  29. public $visibility;
  30. public $credit_type;
  31. public $tags;
  32. public $price;
  33. public $limits;
  34. public $rewardinfo;
  35. public $auto;
  36. public $status;
  37. public $location;
  38. public $cost_per_view;
  39. public $module;
  40. public $view_range_km;
  41. public $probability;
  42. public $level;
  43. public $total_available;
  44. public $group;
  45. public $share_for_reward;
  46. public $category;
  47. //Roles
  48. public $roles;
  49. public $take;
  50. public $assign;
  51. public $redeem;
  52. //rewards
  53. public $rewardtype;
  54. public $amount;
  55. public $auto_redeem;
  56. public $self_redeem;
  57. public $deal_id;
  58. public $role_id;
  59. public $other_reward;
  60. //affiliate
  61. public $affiliate_fee;
  62. //PayPerTake
  63. public $pay_per_take;
  64. public $sharer;
  65. //Food Type
  66. public $food_type;
  67. //types of deals
  68. public $dealinfo;
  69. public $take_action;
  70. // food
  71. public $menu;
  72. //For ticket
  73. public $ticket_type;
  74. public $tickets;
  75. public $visitor_details;
  76. public $venue;
  77. public $event_date;
  78. public $event_type;
  79. public $start_event_date;
  80. public $end_event_date;
  81. public $payment_method;
  82. public $wallet_id;
  83. public $paid;
  84. //for stamp
  85. public $notes;
  86. //prize draw
  87. public $prize_info;
  88. public $prize;
  89. public $terms_and_condition;
  90. public $period;
  91. public $winner;
  92. public $draw_date;
  93. public $prize_redeemed;
  94. public $prize_taken;
  95. public $time;
  96. //survey
  97. public $deal_type;
  98. public $poll_question;
  99. public $poll_choices;
  100. public $survey_type;
  101. public $survey_question;
  102. public $survey_choices;
  103. //competition
  104. public $competition_answer;
  105. public $competition_question;
  106. public $competition_choices;
  107. //For stamp type deal
  108. public $total_stamps;
  109. public $starting_stamps;
  110. public $limit_per_day;
  111. public $code;
  112. //For the limits
  113. public $max_limit_per_user;
  114. public $max_global_limit;
  115. public $max_limit_per_day;
  116. //For Promo
  117. public $promoCodes;
  118. public $promoCodeType;
  119. public $emailSubject;
  120. public $emailMessage;
  121. public $methodofpayment;
  122. public $guestlist;
  123. public $guestListColors;
  124. public $walletId = 534;
  125.  
  126. public function rules() {
  127. return array(
  128. // username and password are required
  129. array('type, owner, title, visibility, start_date, limits, country', 'required', 'except' => 'dataview', 'message' => '{attribute}_required'),
  130. //array('total_stamps, starting_stamps, limit_per_day', 'required', 'on'=>'stamp'),
  131. array('total_stamps', 'required', 'on' => 'stamp'),
  132. array('total_stamps, limit_per_day', 'numerical', 'min' => 1, 'on' => 'stamp'),
  133. //array('days, country, price, total_stamps, starting_stamps, limit_per_day, max_limit_per_user, max_global_limit', 'numerical','integerOnly'=>true,),
  134. array('days, country, total_stamps, limit_per_day, max_limit_per_user, max_global_limit', 'numerical', 'integerOnly' => true,),
  135. array('take', 'validateRole', 'type' => 'member'),
  136. array('assign, redeem', 'validateRole', 'type' => 'staff'),
  137. array('start_date, end_date', 'type', 'type' => 'date', 'dateFormat' => 'yyyy-MM-dd', 'message' => 'invalid_{attribute}_format'),
  138. array('start_date', 'validateDate'),
  139. 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}'),
  140. array('dealinfo', 'validateDealInfo'),
  141. );
  142. }
  143.  
  144. /**
  145. * @return array customized attribute labels (name=>label)
  146. */
  147. public function attributeLabels() {
  148. return array(
  149. 'title' => 'title',
  150. 'food_type' => 'food_type',
  151. 'type' => 'type',
  152. 'description' => 'description',
  153. 'visibility' => 'visibility',
  154. 'country' => 'country',
  155. 'city' => 'city',
  156. 'start_date' => 'start_date',
  157. 'end_date' => 'start_date',
  158. 'days' => 'days',
  159. );
  160. }
  161.  
  162. /*
  163. * * Input and Output
  164. seeErrors
  165. formatOwner
  166. formatStatus
  167. formatDeal
  168. */
  169.  
  170. public function internalError($message, $model = NULL, $action = NULL) {
  171. if (!$action) {
  172. $action = 'general';
  173. }
  174.  
  175. if (!$model)
  176. $model = $this;
  177. //Common::pre($this->getErrors()); exit($message);
  178. Yii::trace($message . ';' . $model->getErrors(), 'system.deal.' . $action);
  179. Yii::log($message, 'error', 'system.deal.' . $action);
  180. throw new CHttpException(403, "internal_error");
  181. }
  182.  
  183. public function seeErrors() {
  184. $result = array();
  185. $errors = $this->getErrors();
  186. $errorsStr = implode(',', array_keys($errors));
  187. Yii::trace('errors=' . $errorsStr, 'system.deal.create');
  188. foreach ($errors as $key => $value) {
  189. $result = array_merge($result, $value);
  190. }
  191.  
  192. return $result;
  193. }
  194.  
  195. public static function formatOwner($owner) {
  196. //For formatting the owner info in deals
  197. $object = new stdClass;
  198. $object->id = intval($owner['id']);
  199. $community = Communities::model()->findByPk($owner['id']);
  200. $object->name = $community->community_name;
  201. $object->type = $owner['type'];
  202. $object->verified = ($owner['verified']) ? "verified" : "unverified";
  203. $object->mobile = $community['community_mobile'];
  204. return $object;
  205. }
  206.  
  207. //search for a value and returns the key in an n dimensional array.
  208. public static function search_in_array($srchvalue, $array) {
  209. if (is_array($array) && count($array) > 0) {
  210. $foundkey = array_search($srchvalue, $array);
  211. if ($foundkey === FALSE) {
  212. foreach ($array as $key => $value) {
  213. if (is_array($value) && count($value) > 0) {
  214. $foundkey = Deals::search_in_array($srchvalue, $value);
  215. if ($foundkey != FALSE)
  216. return $foundkey;
  217. }
  218. }
  219. } else
  220. return $foundkey;
  221. }
  222. }
  223.  
  224. public static function formatStatus($status) {
  225. //For formatting the status type in deals
  226. if ($status == 1) {
  227. return "active";
  228. } elseif ($status == 2) {
  229. return "expired";
  230. } elseif ($status == 3) {
  231. return "complete";
  232. } elseif ($status == 4) {
  233. return "deactivated";
  234. } elseif ($status == 5) {
  235. return "pending";
  236. } elseif ($status == 6) {
  237. return "archived";
  238. } elseif ($status == 7) {
  239. return "bookmarked";
  240. } elseif ($status == 8) {
  241. return "in use";
  242. } elseif ($status == 9) {
  243. return "ordered";
  244. } else {
  245. return "blocked";
  246. }
  247. }
  248.  
  249. public static function formatDeal($deal, $isStaff = false, $communityId = null, $userId = null) {
  250. //For formatting the deal details
  251. $object = new stdClass();
  252. $object->id = $deal['_id']->__toString();
  253. $object->type = $deal['type'];
  254. if ($deal['food_type']) {
  255. $object->food_type = $deal['food_type'];
  256. }
  257. $object->owner = self::formatOwner($deal['owner']);
  258. $object->status = self::formatStatus($deal['status']);
  259. $object->visibility = $deal['visibility'];
  260. $object->title = $deal['title'];
  261. $object->description = $deal['description'];
  262. $object->category = $deal['category'];
  263. $object->start_date = $deal['start_date'];
  264. $object->end_date = $deal['end_date'];
  265. $object->country = $deal['country'];
  266. $object->location = $deal['location'];
  267. $object->city = $deal['city'];
  268. $object->price = $deal['price'];
  269. $object->credit_type = $deal['credit_type'];
  270. $object->tags = $deal['tags'];
  271. $object->rewardinfo = $deal['rewardinfo'];
  272. $object->auto = $deal['auto'];
  273. $object->pay_per_take = $deal['pay_per_take'];
  274. $object->pay_per_click = $deal['pay_per_click'];
  275. $object->view_range_km = $deal['view_range_km'];
  276. $object->probability = $deal['probability'];
  277. $object->level = $deal['level'];
  278. $object->total_available = $deal['total_available'];
  279. $object->limits = $deal['limits'];
  280.  
  281. if ($isStaff) {
  282. $object->dealinfo = $deal['dealinfo'];
  283. }
  284.  
  285. if ($deal['type'] == 'promo') {
  286. $object->limits = $deal['limits']['max_limit_per_user'];
  287. }
  288.  
  289. if (isset($deal['delivery_options'])) {
  290. $object->delivery_options = empty($deal['delivery_options']) ? (object) $deal['delivery_options'] : $deal['delivery_options'];
  291. }
  292.  
  293. if ($deal['type'] == 'catalog')
  294. $object->items = $deal['items'];
  295.  
  296. if ($deal['game_slots'])
  297. $object->game_slots = $deal['game_slots'];
  298.  
  299. if ($isStaff) {
  300. $object->affiliate_fee = $deal['affiliate_fee'];
  301. $object->roles = $deal['roles'];
  302.  
  303. //statistics
  304. $statistics = new stdClass();
  305. $statistics->visit_count = $deal['dealinfo']['visitors'] ? sizeof($deal['dealinfo']['visitors']) : 0;
  306. $statistics->bookmark_count = $deal['sharedBookmarkCount'] ? $deal['sharedBookmarkCount'] : 0;
  307. $statistics->redeem_count = $deal['sharedRedeemCount'] ? $deal['sharedRedeemCount'] : 0;
  308. $object->cost_per_view = $deal['cost_per_view'];
  309. $object->share_for_reward = $deal['share_for_reward'];
  310. $total = 0;
  311. if ($deal['cost_per_view']['amount'] > 0) {
  312. $total = $deal['cost_per_view']['amount'];
  313. $total = $total * $statistics->visit_count . ' ' . WalletTypes::getWalletName($deal['cost_per_view']['wallet_id'], true);
  314. }
  315. $statistics->advertising_spent = $total;
  316. $object->statistics = $statistics;
  317. }
  318.  
  319. if ($communityId == null && $userId > 0) {
  320. $object->take = Deals::checkIfUserCanTakeDeal($deal, $userId);
  321. $object->favorite = FavoriteCatalogs::checkFavourite($userId, $object->id);
  322. }
  323.  
  324. if ($deal['url'])
  325. $object->url = $deal['url'];
  326.  
  327. $object->image = SELF::getAvatar($object->id, true);
  328.  
  329. return $object;
  330. }
  331.  
  332. public static function formatPaymentMethod($methodArray) {
  333. $result = array();
  334. foreach ($methodArray as $key => $value) {
  335. switch ($value) {
  336. case 1:
  337. $result[$value] = 'Tagcash';
  338. break;
  339. case 2:
  340. $result[$value] = 'Cash on Pickup';
  341. break;
  342. case 3:
  343. $result[$value] = 'Paypal';
  344. break;
  345. case 4:
  346. $result[$value] = 'DragonPay';
  347. break;
  348. case 5:
  349. $result[$value] = 'Credit Card';
  350. break;
  351. default:
  352. $result[$value] = 'Other';
  353. break;
  354. }
  355. }
  356. return $result;
  357. }
  358.  
  359. public static function formatDealInfo($deal) {
  360. $object = new stdClass();
  361. $object->type = $deal['type'];
  362. $object->dealinfo = (object) $deal['dealinfo'];
  363. //dbug::p($object->dealinfo, true);
  364.  
  365. if ($object->type == "inventory") {
  366. if ($object->dealinfo->inventoryType) {
  367. $object->dealinfo->inventory_type = $object->dealinfo->inventoryType;
  368. unset($object->dealinfo->inventoryType);
  369. }
  370. }
  371.  
  372. if ($object->type == "game") {
  373. $gameType = $deal['dealinfo']['gameType'];
  374. if ($gameType == 1) {
  375. $object->dealinfo->game_type = "bomb";
  376. if ($object->dealinfo->cellSize) {
  377. $object->dealinfo->cell_size = $object->dealinfo->cellSize;
  378. unset($object->dealinfo->cellSize);
  379. }
  380. } else if ($gameType == 2) {
  381. $object->dealinfo->game_type = "hi_lo";
  382. } else if ($object->gameType == 3) {
  383. $object->dealinfo->game_type = "dice";
  384. } else if ($gameType == 4) {
  385. $object->dealinfo->game_type = "spin_wheel";
  386.  
  387. //wins
  388. if ($object->dealinfo->winCount) {
  389. $object->dealinfo->wins = $object->dealinfo->winCount;
  390. unset($object->dealinfo->winCount);
  391. }
  392.  
  393. //loses
  394. if ($object->dealinfo->loseCount) {
  395. $object->dealinfo->loses = $object->dealinfo->loseCount;
  396. unset($object->dealinfo->loseCount);
  397. }
  398. } else if ($gameType == 5) {
  399. $object->dealinfo->game_type = "rock_paper_scissor";
  400. }
  401. unset($object->dealinfo->gameType);
  402. }
  403.  
  404. return $object->dealinfo;
  405. }
  406.  
  407. /*
  408. * * end of Input and Output
  409. */
  410.  
  411. /*
  412. * * General
  413. setIdentity
  414. */
  415.  
  416. public function setIdentity($thisObj) {
  417. $this->thisObj = $thisObj;
  418. $this->communityId = $thisObj->_COMMUNITYID;
  419. $this->userId = $thisObj->_USERID;
  420. $this->user = $thisObj->_USEROBJ;
  421. $this->community = $thisObj->_COMMUNITYOBJ;
  422. return true;
  423. }
  424.  
  425. /*
  426. * * Validations
  427. validateRole
  428. validateDealId
  429. validateDate
  430. checkIfDealExists
  431. isPermission
  432. */
  433.  
  434. public function validateRole($attribute, $params) {
  435. if ($params['type'] == "member") {
  436. $criteria = new CDbCriteria();
  437. $criteria->condition = "role_type != 3";
  438. $criteria->addInCondition("id", $this->$attribute);
  439. $result = CommunityRoles::model()->findAll($criteria);
  440. } else {
  441. $criteria = new CDbCriteria();
  442. $criteria->condition = "role_type = 3";
  443. $criteria->addInCondition("id", $this->$attribute);
  444. $result = CommunityRoles::model()->findAll($criteria);
  445. }
  446.  
  447. if ($result) {
  448. //meaning there was a validation error
  449. $this->addError($attribute, 'Role error');
  450. }
  451. }
  452.  
  453. public function validateDealId($attribute, $params) {
  454. $collection = Yii::app()->edmsMongoCollection('deals');
  455. $deal = $collection->findOne(array("_id" => new MongoID($this->$attribute)));
  456.  
  457. if (!$deal) {
  458. $this->addError($attribute, 'Invalid deal Id');
  459. } else {
  460. if ($deal['rewardinfo']['type'] == "deal") {
  461. $this->addError($attribute, 'Deal chaining not allowed');
  462. }
  463.  
  464. if (strtotime($this->start_date) < strtotime($deal['start_date']) || strtotime($this->start_date) > strtotime($deal['end_date'])) {
  465. $this->addError("start_date", "Deal start date should be within the reward deal's duration");
  466. }
  467.  
  468. if (strtotime($this->end_date) < strtotime($deal['start_date']) || strtotime($this->end_date) > strtotime($deal['end_date'])) {
  469. $this->addError("end_date", "Deal end date should be within the reward deal's duration");
  470. }
  471. }
  472. }
  473.  
  474. public function validateDate($attribute, $params) {
  475. //required
  476. if (!$this->end_date && !$this->days) {
  477. $this->addError('days', 'days_required');
  478. }
  479.  
  480. //validate
  481. $currentDateTimestamp = strtotime(date('Y-m-d'));
  482. $startDateTimestamp = strtotime($this->start_date);
  483. $endDateTimestamp = strtotime($this->end_date);
  484.  
  485. if ($this->start_date && $currentDateTimestamp > $startDateTimestamp) {
  486. $this->addError('start_date', 'invalid_start_dates');
  487. }
  488.  
  489. if ($this->end_date && $endDateTimestamp <= $startDateTimestamp) {
  490. $this->addError('end_date', 'invalid_end_date');
  491. }
  492. }
  493.  
  494. public function checkIfDealExists() {
  495. if (!$this->deal && $this->validateMongoId()) {
  496. $collection = Yii::app()->edmsMongoCollection('deals');
  497.  
  498. $cond = array("_id" => new MongoID($this->dealId));
  499. if ($this->communityId) {
  500. $cond["owner.id"] = intval($communityId);
  501. $cond["owner.type"] = "community";
  502. }
  503. $this->deal = $collection->findOne($cond);
  504. }
  505.  
  506. if (!$this->deal) {
  507. return false;
  508. }
  509.  
  510. return true;
  511. }
  512.  
  513. public function isPermission($todo, $deal = NULL) {
  514. //convert object to array
  515. if (is_object($deal)) {
  516. $deal = (array) $deal;
  517. }
  518.  
  519. $userId = $this->userId;
  520. $communityId = $this->communityId;
  521.  
  522. if ($communityId) {
  523. //If the deal is owned by a community
  524. if (!CommunityUsers::isStaffOf($userId, $communityId)) {
  525. throw new CHttpException(403, "not_staff");
  526. }
  527.  
  528. $role = CommunityUsers::getRoleOfUser($userId, $communityId);
  529.  
  530. if ($todo == 'list') {
  531. //list
  532. } else if ($todo == 'history') {
  533. //history list
  534. } else if ($todo == 'assign') {
  535. //check deal
  536. if (!$deal) {
  537. throw new CHttpException(403, "invalid_deal");
  538. }
  539.  
  540. //check community
  541. if ($deal['owner']['type'] != 'community') {
  542. throw new CHttpException(403, "invalid_deal_community");
  543. } else {
  544. if ($communityId != $deal['owner']['id']) {
  545. throw new CHttpException(403, "invalid_deal_community");
  546. }
  547. }
  548.  
  549. if ($role->role_type == 1) { //owner
  550. return true;
  551. } else {
  552. if (!$deal['roles']['assign']) {
  553. throw new CHttpException(403, "permission_denied");
  554. } else {
  555. if (!in_array($role->role_id, $deal['roles']['assign'])) {
  556. throw new CHttpException(403, "permission_denied");
  557. }
  558. }
  559. }
  560. }
  561. //edit deal
  562. else if ($todo == 'edit') {
  563. //check deal
  564. if (!$deal) {
  565. throw new CHttpException(403, "invalid_deal");
  566. }
  567.  
  568. //check community
  569. if ($deal['owner']['type'] != 'community') {
  570. throw new CHttpException(403, "invalid_deal_community");
  571. } else {
  572. if ($communityId != $deal['owner']['id']) {
  573. throw new CHttpException(403, "invalid_deal_community");
  574. }
  575. }
  576.  
  577. if ($role->role_type == 1) { //owner
  578. return true;
  579. }
  580. } else if ($todo == 'redeem') {
  581. //check deal
  582. if (!$deal) {
  583. throw new CHttpException(403, "invalid_deal");
  584. }
  585.  
  586. //check community
  587. if ($deal['owner']['type'] != 'community') {
  588. throw new CHttpException(403, "invalid_deal_community");
  589. } else {
  590. if ($communityId != $deal['owner']['id']) {
  591. throw new CHttpException(403, "invalid_deal_community");
  592. }
  593. }
  594.  
  595. if ($role->role_type == 1) { //owner
  596. return true;
  597. } else {
  598. if (!$deal['roles']['redeem']) {
  599. throw new CHttpException(403, "permission_denied");
  600. } else {
  601. if (!in_array($role->role_id, $deal['roles']['redeem'])) {
  602. throw new CHttpException(403, "permission_denied");
  603. }
  604. }
  605. }
  606. } else {
  607. $this->internalError('checking permissions', NULL, 'permission');
  608. }
  609.  
  610. return true;
  611. } else {
  612. //If the deal is owned by a user
  613. if ($userId == $deal['owner']['id']) {
  614. return true;
  615. } else if ($todo == 'redeem') {
  616. if ($deal['rewardinfo']['self_redeem']) {
  617. return true;
  618. }
  619.  
  620. throw new CHttpException(403, "not_self_redeem");
  621. }
  622. }
  623.  
  624. //$this->addError('transaction_type', 'permission_denied');
  625. return true;
  626. }
  627.  
  628. public function validateDealInfo($attribute, $params) {
  629. if (in_array($this->type, array('stamp', 'promo', 'inventory', 'game')) && !$this->dealinfo) {
  630. $this->addError($attribute, 'invalid_dealinfo');
  631. }
  632. //dbug::p($this->dealinfo->gameType);
  633. //inventory
  634. if ($this->type == 'inventory') {
  635. if (!$this->dealinfo->inventoryType ||
  636. !in_array($this->dealinfo->inventoryType, array('inOut', 'fixed', 'resale'))) {
  637. $this->addError($attribute, 'invalid_inventory_type');
  638. }
  639. }
  640. //game
  641. else if ($this->type == 'game') {
  642. if (!$this->dealinfo->gameType) {
  643. $this->addError($attribute, 'invalid_game_type');
  644. } else {
  645. //game general params
  646. if (!$this->dealinfo->hits) {
  647. $this->addError($attribute, 'invalid_attempts');
  648. }
  649. if (!$this->dealinfo->needed) {
  650. $this->addError($attribute, 'invalid_needed');
  651. }
  652. if ($this->dealinfo->status === NULL) {
  653. $this->addError($attribute, 'status');
  654. }
  655. if ($this->dealinfo->game_status === NULL) {
  656. $this->addError($attribute, 'game_status');
  657. }
  658.  
  659. //game type
  660. if ($this->dealinfo->gameType == 1) {
  661. if (!$this->dealinfo->bombs) {
  662. $this->addError($attribute, 'invalid_bombs');
  663. }
  664.  
  665. if (!$this->dealinfo->wins) {
  666. $this->addError($attribute, 'invalid_wins');
  667. }
  668.  
  669. if (!$this->dealinfo->cellSize) {
  670. $this->addError($attribute, 'invalid_cell_size');
  671. }
  672. } else if ($this->dealinfo->gameType == 4) {
  673. if (!$this->dealinfo->winCount) {
  674. $this->addError($attribute, 'invalid_wins');
  675. }
  676.  
  677. if (!$this->dealinfo->loseCount) {
  678. $this->addError($attribute, 'invalid_loses');
  679. }
  680. }
  681. }
  682. }
  683. }
  684.  
  685. /*
  686. * * end of Validations
  687. */
  688.  
  689. /*
  690. * * deals - create and extend
  691. */
  692.  
  693. public function createDeal($data, $id, $type) {
  694. $this->owner = new stdClass();
  695. $this->roles = new stdClass();
  696. $this->dealinfo = new stdClass();
  697.  
  698. //Common::pre($data, true);
  699. //$this->attributes = $data;
  700. if ($type == "user") {
  701. //for future
  702. $userModel = Users::model()->findByPk($id);
  703. $this->owner->id = intval($id);
  704. $this->owner->type = "user";
  705. $this->owner->name = $userModel->user_firstname . " " . $userModel->user_lastname;
  706. } else {
  707. //If a community is making the deal
  708. $communityModel = Communities::model()->findByPk($id);
  709. $this->communityId = $id;
  710. $this->owner->id = intval($id);
  711. $this->owner->type = "community";
  712. $this->owner->name = $communityModel->community_name;
  713. $this->owner->mobile = $communityModel->community_mobile;
  714. $this->owner->verified = intval($communityModel->community_verified);
  715.  
  716. $take = array();
  717. $assign = array();
  718. $redeem = array();
  719. $view = array();
  720. for ($i = 0; $i < count($data['roles']['take']); $i++) {
  721. //For converting the elements to integer
  722. $take[$i] = intval($data['roles']['take'][$i]);
  723. }
  724.  
  725. for ($i = 0; $i < count($data['roles']['assign']); $i++) {
  726. //For converting the elements to integer
  727. $assign[$i] = intval($data['roles']['assign'][$i]);
  728. }
  729.  
  730. for ($i = 0; $i < count($data['roles']['redeem']); $i++) {
  731. //For converting the elements to integer
  732. $redeem[$i] = intval($data['roles']['redeem'][$i]);
  733. }
  734.  
  735. for ($i = 0; $i < count($data['roles']['view']); $i++) {
  736. //For converting the elements to integer
  737. $view[$i] = intval($data['roles']['view'][$i]);
  738. }
  739. //if no roles specified, add default roles
  740. if (!isset($data['roles']['take'])) {
  741. $take[] = CommunityRoles::getDefaultRole($this->owner->id)->id;
  742. }
  743.  
  744. /* if(!isset($data['roles']['view'])){
  745. $view[] = CommunityRoles::getDefaultRole($this->owner->id)->id;
  746. } */
  747.  
  748. if (empty($assign)) {
  749. $assign = CommunityRoles::getRoles($id, 'owner');
  750. }
  751.  
  752. if (empty($redeem)) {
  753. $redeem = CommunityRoles::getRoles($id, 'staff');
  754. if (is_array($redeem))
  755. $redeem = array_merge($redeem, $assign);
  756. else
  757. $redeem = $assign;
  758. }
  759.  
  760. $this->roles->take = $take;
  761. $this->roles->assign = $assign;
  762. $this->roles->redeem = $redeem;
  763. $this->roles->view = $view;
  764. $this->take = $take;
  765. $this->assign = $assign;
  766. $this->redeem = $redeem;
  767. $this->credit_type = $data['credit_type'];
  768. //$this->validatorList->add(CValidator::createValidator('required', $this, 'credit_type'));
  769. //$this->validatorList->add(CValidator::createValidator('in', $this, 'credit_type', array('range'=>array("open", "closed"), 'allowEmpty' => false)));
  770. }
  771.  
  772. //title
  773. if ($data['title']) {
  774. $this->title = $data['title'];
  775. }
  776.  
  777. if ($data['food_type']) {
  778. $this->food_type = $data['food_type'];
  779. }
  780.  
  781. //rewardinfo
  782. if ($data['rewardinfo']) {
  783. $this->rewardinfo = $data['rewardinfo'];
  784. }
  785.  
  786. //game slots - include in slot game rewards
  787. if (isset($data['game_slots'])) {
  788. $gameslot = $data['game_slots'];
  789. $game_slots = new stdClass;
  790.  
  791. if ($gameslot['status'] == 1)
  792. $game_slots->status = intval(1);
  793. else
  794. $game_slots->status = intval(0);
  795.  
  796. if ($gameslot['limit'] > 0)
  797. $game_slots->limit = intval($gameslot['limit']);
  798. else
  799. $game_slots->limit = intval(0);
  800. }
  801.  
  802. //share_for_reward
  803. $share_for_reward = new stdClass();
  804. if ($data['share_for_reward'] && $data['share_for_reward']['amount']) {
  805. if ((!in_array($data['type'], array('load', 'bonus'))) && $data['share_for_reward']['wallet_id']) {
  806. $share_for_reward->amount = $data['share_for_reward']['amount'];
  807. $share_for_reward->type = 'wallet';
  808. $share_for_reward->wallet_id = $data['share_for_reward']['wallet_id'];
  809. $this->share_for_reward = $share_for_reward;
  810. } else {
  811. $share_for_reward->amount = $data['share_for_reward']['amount'];
  812. $share_for_reward->type = $data['type'];
  813. $share_for_reward->owner_id = $this->userId;
  814. $this->share_for_reward = $share_for_reward;
  815. }
  816. }
  817.  
  818. //location
  819. if ($data['location']) {
  820. $this->location = array(floatval($data['location'][0]), floatval($data['location'][1]));
  821. if (sizeof($this->location) != 2) {
  822. $this->addError($attribute, 'Invalid location format(long,lat)');
  823. } else if ((floatval($data['location'][0]) == 0) || ((floatval($data['location'][1]) == 0))) {
  824. $this->location = null;
  825. }
  826. }
  827.  
  828. //country
  829. if ($data['country']) {
  830. $this->country = $data['country'];
  831. } else {
  832. $this->country = $this;
  833. }
  834.  
  835. //limits
  836. if ($data['limits']) {
  837. $this->limits = $data['limits'];
  838. $this->max_limit_per_user = $data['limits']['max_limit_per_user'];
  839. $this->max_global_limit = $data['limits']['max_global_limit'];
  840. $this->max_limit_per_day = $data['limits']['max_limit_per_day'];
  841. } else {
  842. $this->limits = array();
  843. }
  844.  
  845. //visibility
  846. if ($data['visibility']) {
  847. $this->visibility = $data['visibility'];
  848. } else {
  849. $this->visibility = 'public';
  850. }
  851.  
  852. //view range in km
  853. if ($data['view_range_km'])
  854. $this->view_range_km = $data['view_range_km'];
  855.  
  856. //probability
  857. if ($data['probability'])
  858. $this->probability = intval($data['probability']);
  859.  
  860. //level
  861. if ($data['level'])
  862. $this->level = intval($data['level']);
  863.  
  864. //total availabe gifts
  865. if ($data['total_available'])
  866. $this->total_available = $data['total_available'];
  867.  
  868. //tag group
  869. if ($data['group'])
  870. $this->group = $data['group'];
  871.  
  872. //price
  873. $price = new stdClass();
  874. $price->type = "none";
  875. if ($data['price'] && $data['price']['amount']) {
  876. $price->amount = $data['price']['amount'];
  877. $price->type = 'reward';
  878. if ($data['price']['type'] == "wallet") {
  879. $price->type = 'wallet';
  880. $price->wallet_id = $data['price']['wallet_id'];
  881. }
  882. } elseif ($data['price'] && $data['price']['options']) {
  883. $price->type = ($data['price']['type']) ? $data['price']['type'] : 'wallet';
  884. $price->wallet_id = ($data['price']['wallet_id']) ? intval($data['price']['wallet_id']) : 0;
  885.  
  886. $priceOptions = array();
  887. foreach ($data['price']['options'] as $options) {
  888. $option = new stdClass();
  889. $option->availability = $options['availability'];
  890. $option->category = $options['category'];
  891. $option->description = $options['description'];
  892. $option->limit = $options['limit'];
  893. $option->price = $options['price'];
  894. $option->quantity = intval($options['quantity']);
  895.  
  896. $priceOptions[] = $option;
  897. }
  898. $price->options = (object) $priceOptions;
  899. }
  900. $this->price = $price;
  901.  
  902. //affiliate fee
  903. if ($data['affiliate_fee'] && $data['affiliate_fee']['amount']) {
  904. $fee = new stdClass();
  905. $fee->amount = $data['affiliate_fee']['amount'];
  906. $fee->type = 'reward';
  907. if ($data['affiliate_fee']['type'] == 'wallet') {
  908. $fee->type = 'wallet';
  909. $fee->wallet_id = $data['affiliate_fee']['wallet_id'];
  910. }
  911.  
  912. $this->affiliate_fee = $fee;
  913. }
  914.  
  915. //pay per take
  916. if ($data['pay_per_take']) {
  917. $ppt = new stdClass();
  918. $ppt->amount = $data['pay_per_take']['amount'];
  919. $ppt->type = $data['pay_per_take']['type'];
  920. $ppt->budget = $data['pay_per_take']['budget'];
  921. if ($data['pay_per_take']['type'] == "wallet") {
  922. $ppt->type = 'wallet';
  923. $ppt->wallet_id = $data['pay_per_take']['wallet_id'];
  924. }
  925.  
  926. $this->pay_per_take = $ppt;
  927. }
  928.  
  929. //pay per click
  930. if ($data['pay_per_click']) {
  931. $ppc = new stdClass();
  932. $ppc->amount = $data['pay_per_click']['amount'];
  933. $ppc->type = $data['pay_per_click']['type'];
  934. $ppc->budget = $data['pay_per_click']['budget'];
  935. if ($data['pay_per_click']['type'] == "wallet") {
  936. $ppc->type = 'wallet';
  937. $ppc->wallet_id = $data['pay_per_click']['wallet_id'];
  938. }
  939.  
  940. $this->pay_per_click = $ppc;
  941. }
  942.  
  943. /*
  944. * * deal types
  945. */
  946. $parsedData = new stdClass();
  947.  
  948. if ($data['type'] == 'stamp') {
  949. $this->module = 'loyalty';
  950. $this->type = 'stamp';
  951.  
  952. $this->total_stamps = $data['dealinfo']['total_stamps'];
  953. $this->starting_stamps = $data['dealinfo']['starting_stamps'];
  954. $this->limit_per_day = $data['dealinfo']['limit_per_day'];
  955. $this->take_action = ($data['dealinfo']['take_action']) ? true : false;
  956.  
  957. $this->dealinfo->code = rand();
  958. $this->dealinfo->total_stamps = ($data['dealinfo']['total_stamps']) ? intval($data['dealinfo']['total_stamps']) : NULL;
  959. $this->dealinfo->starting_stamps = ($data['dealinfo']['starting_stamps']) ? intval($data['dealinfo']['starting_stamps']) : NULL;
  960. $this->dealinfo->limit_per_day = ($data['dealinfo']['limit_per_day']) ? intval($data['dealinfo']['limit_per_day']) : NULL;
  961. $this->dealinfo->take_action = ($data['dealinfo']['take_action']) ? true : false;
  962.  
  963. $this->validatorList->add(CValidator::createValidator('required', $this, 'dealinfo'));
  964.  
  965. $collection = new Collections();
  966. $collection->setIdentity($this->thisObj);
  967. $cData = array('collection_type' => $data['loyalty_stamp_collection_type'],
  968. 'collection_duration' => 1,
  969. 'payment_type' => 'tagcash',
  970. 'name' => $data['title'],
  971. 'created_from' => 'miskio',
  972. 'image' => $data['loyalty_stamp_images'],
  973. 'loyalty_stamp_user_view_type' => $data['loyalty_stamp_user_view_type']);
  974. $parsedData->collection = $collection->createCollection($cData);
  975. } elseif ($data['type'] == 'coupon') {
  976. $this->module = 'loyalty';
  977. $this->type = 'coupon';
  978. } elseif ($data['type'] == 'catalog') {
  979. $this->module = 'ecommerce';
  980. $this->type = 'catalog';
  981. $details = array();
  982. if ($data['catalog_items'] && Common::isJson($data['catalog_items'])) {
  983. $catalog_items = json_decode($data['catalog_items'], true);
  984. foreach ($catalog_items as $item) {
  985. //get complete list of items and store inside items details
  986. $details[$i]['id'] = intval($item);
  987. $query = Yii::app()->db->createCommand()
  988. ->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')
  989. ->from('catalog c')
  990. ->leftJoin("catalog_category cc", "cc.id = c.category_id")
  991. ->leftJoin("wallet_types wt", "wt.id = c.price_wallet")
  992. ->where('c.id = ' . $item . ' AND c.community_id = ' . $id);
  993. $result = $query->queryAll();
  994. if (!$result)
  995. continue;
  996. $result = $result[0];
  997. $details[$i]['catalog_name'] = $result['catalog_name'];
  998. $details[$i]['category'] = $result['category_name'] ? array('id' => $result['category_id'], 'name' => $result['category_name']) : array();
  999. $details[$i]['description'] = $result['description'];
  1000. $details[$i]['price'] = array('amount' => $result['price'] ? $result['price'] : 0, 'wallet_id' => $result['price_wallet'], 'wallet_name' => $result['currency_code']);
  1001. $details[$i]['weight'] = $result['weight'];
  1002. $size = array();
  1003. $color = array();
  1004. if ($result['sizes']) {
  1005. $size = explode(',', $result['sizes']);
  1006. }
  1007. if ($result['colors']) {
  1008. $color = explode(',', $result['colors']);
  1009. }
  1010. if ($result['other']) {
  1011. $other = explode(',', $result['other']);
  1012. }
  1013. $details[$i]['sizes'] = $size;
  1014. $details[$i]['colors'] = $color;
  1015. $details[$i]['other'] = $other;
  1016. $details[$i]['stock'] = intval($result['stock']);
  1017. $details[$i]['hashtags'] = $result['hashtags'] ? explode(',', $result['hashtags']) : array();
  1018. $details[$i]['time_to_ship'] = $result['time_to_ship'];
  1019. $i++;
  1020. }
  1021. $catalogs = $details;
  1022. }
  1023. //delivery option
  1024. $parsedData->delivery_options = array();
  1025. if (isset($data['delivery_options']) && is_array($data['delivery_options'])) {
  1026. if ($data['delivery_options']['type'] == 'xend')
  1027. $parsedData->delivery_options = $data['delivery_options'];
  1028. else if ($data['delivery_options']['amount'] > 0 && $data['delivery_options']['wallet_id'] > 0) {
  1029. $parsedData->delivery_options = $data['delivery_options'];
  1030. }
  1031. }
  1032. } elseif ($data['type'] == 'ticket') {
  1033. $this->module = 'ecommerce';
  1034. $this->type = 'ticket';
  1035.  
  1036. if ($data['dealinfo']) {
  1037. $this->dealinfo->ticket_type = $data['dealinfo']['ticket_type'];
  1038. $this->dealinfo->event_name = $data['dealinfo']['event_name'];
  1039. $this->dealinfo->event_type = $data['dealinfo']['event_type'];
  1040.  
  1041. if ($data['dealinfo']['event_date']) {
  1042. $this->dealinfo->event_date = $data['dealinfo']['event_date'];
  1043. } else {
  1044. $this->dealinfo->start_event_date = $data['dealinfo']['start_event_date'];
  1045. $this->dealinfo->end_event_date = $data['dealinfo']['end_event_date'];
  1046. }
  1047.  
  1048. $this->dealinfo->venue = $data['dealinfo']['venue'];
  1049. $this->dealinfo->eventAdditionalInfo = $data['dealinfo']['eventAdditionalInfo'];
  1050. $this->dealinfo->eventAdditionalInfoMandatory = $data['dealinfo']['eventAdditionalInfoMandatory'];
  1051. $this->dealinfo->eventOpeningTime = $data['dealinfo']['eventOpeningTime'];
  1052. $this->dealinfo->eventAddress = $data['dealinfo']['eventAddress'];
  1053. $this->dealinfo->scanCount = $data['dealinfo']['scanCount'];
  1054.  
  1055. if ($data['dealinfo']['scanSchedule']) {
  1056. $scanSchedule = new stdClass();
  1057.  
  1058. $scanSchedule->activity = intval($data['dealinfo']['scanSchedule']['activity']);
  1059. $scanSchedule->start_date = $data['dealinfo']['scanSchedule']['start_date'];
  1060. $scanSchedule->start_time = $data['dealinfo']['scanSchedule']['start_time'];
  1061. $scanSchedule->end_date = $data['dealinfo']['scanSchedule']['end_date'];
  1062. $scanSchedule->end_time = $data['dealinfo']['scanSchedule']['end_time'];
  1063. }
  1064. $this->dealinfo->scanSchedule = $scanSchedule;
  1065. }
  1066.  
  1067. if ($data['methodofpayment']) {
  1068. $this->methodofpayment = $data['methodofpayment'];
  1069. }
  1070. if ($data['guestListColors']) {
  1071. $this->guestListColors = $data['guestListColors'];
  1072. }
  1073. if ($data['guestlist']) {
  1074. $this->guestlist = intval($data['guestlist']);
  1075. }
  1076. } elseif ($data['type'] == 'sticker') {
  1077. $this->module = 'ecommerce';
  1078. $this->type = 'sticker';
  1079. } elseif ($data['type'] == 'promo') {
  1080. $this->module = 'loyalty';
  1081. $this->type = 'promo';
  1082.  
  1083. $parsedPromocodes = array();
  1084. if ($data['dealinfo']['promo_codes'] && is_array($data['dealinfo']['promo_codes'])) {
  1085. foreach ($data['dealinfo']['promo_codes'] as $promoCode) {
  1086. $object = new stdClass;
  1087. $object->code = $promoCode;
  1088. $object->status = 0;
  1089.  
  1090. $parsedPromocodes[] = $object;
  1091. }
  1092. }
  1093. $this->dealinfo->promo_codes = $parsedPromocodes;
  1094. $this->dealinfo->type = ($data['dealinfo']['type']) ? $data['dealinfo']['type'] : "none";
  1095. $this->total_available = count($parsedPromocodes);
  1096. } elseif ($data['type'] == 'inventory') {
  1097. $this->type = 'inventory';
  1098.  
  1099. if ($data['dealinfo']['inventory_type']) {
  1100. $this->dealinfo->inventoryType = $data['dealinfo']['inventory_type'];
  1101. }
  1102.  
  1103. if ($data['dealinfo']['cost_price']) {
  1104. $this->dealinfo->costPrice = $data['dealinfo']['cost_price'];
  1105. }
  1106.  
  1107. if ($data['dealinfo']['retail_price']) {
  1108. $this->dealinfo->retailPrice = $data['dealinfo']['retail_price'];
  1109. }
  1110.  
  1111. if ($data['dealinfo']['sku_code']) {
  1112. $this->dealinfo->skuCode = $data['dealinfo']['sku_code'];
  1113. }
  1114. //print_r($this->dealinfo->inventoryType); exit;
  1115. } elseif ($data['type'] == 'game') {
  1116. $this->type = 'game';
  1117. if ($data['dealinfo']['game_type']) {
  1118. //general params
  1119. $this->dealinfo->status = 0;
  1120. $this->dealinfo->game_status = 0;
  1121. if ($data['dealinfo']['attempts']) {
  1122. $this->dealinfo->hits = $data['dealinfo']['attempts'];
  1123. }
  1124. if ($data['dealinfo']['needed']) {
  1125. $this->dealinfo->needed = $data['dealinfo']['needed'];
  1126. }
  1127. if ($data['dealinfo']['free_tries']) {
  1128. $this->dealinfo->freeTries = $data['dealinfo']['free_tries'];
  1129. }
  1130. if ($data['dealinfo']['game_time']) {
  1131. $this->dealinfo->gameTime = $data['dealinfo']['game_time'];
  1132. }
  1133.  
  1134. //game type
  1135. if ($data['dealinfo']['game_type'] == 'bomb' || $data['dealinfo']['game_type'] == '1') {
  1136. $this->dealinfo->gameType = 1;
  1137.  
  1138. if ($data['dealinfo']['bombs']) {
  1139. $this->dealinfo->bombs = $data['dealinfo']['bombs'];
  1140. }
  1141.  
  1142. if ($data['dealinfo']['wins']) {
  1143. $this->dealinfo->wins = $data['dealinfo']['wins'];
  1144. }
  1145.  
  1146. if ($data['dealinfo']['cell_size']) {
  1147. $this->dealinfo->cellSize = $data['dealinfo']['cell_size'];
  1148. }
  1149. } else if ($data['dealinfo']['game_type'] == 'hi_lo' || $data['dealinfo']['game_type'] == '2') {
  1150. $this->dealinfo->gameType = 2;
  1151. } else if ($data['dealinfo']['game_type'] == 'dice' || $data['dealinfo']['game_type'] == '3') {
  1152. $this->dealinfo->gameType = 3;
  1153. } else if ($data['dealinfo']['game_type'] == 'spin_wheel' || $data['dealinfo']['game_type'] == '4') {
  1154. $this->dealinfo->gameType = 4;
  1155. $this->dealinfo->winCount = $data['dealinfo']['wins'];
  1156. $this->dealinfo->loseCount = $data['dealinfo']['loses'];
  1157. } else if ($data['dealinfo']['game_type'] == 'rock_paper_scissor' || $data['dealinfo']['game_type'] == '5') {
  1158. $this->dealinfo->gameType = 5;
  1159. }
  1160. }
  1161. } elseif ($data['type'] == 'bus_reservation') {
  1162. $this->module = 'ecommerce';
  1163. $this->type = 'bus_reservation';
  1164. $this->dealinfo = (object) $data['dealinfo'];
  1165. } elseif ($data['type'] == 'food') {
  1166. $this->module = 'ecommerce';
  1167. $this->type = 'food';
  1168. $this->dealinfo->menu = (object) $data['dealinfo'];
  1169. } elseif ($data['type'] == 'book_spa') {
  1170. $this->module = 'ecommerce';
  1171. $this->type = 'book_spa';
  1172. $this->dealinfo = (object) $data['dealinfo'];
  1173. } elseif ($data['type'] == 'jobs') {
  1174. $this->module = 'ecommerce';
  1175. $this->type = 'jobs';
  1176. $this->dealinfo = (object) $data['dealinfo'];
  1177. } elseif ($data['type'] == 'resume') {
  1178. $this->module = 'ecommerce';
  1179. $this->type = 'resume';
  1180. $this->dealinfo = (object) $data['dealinfo'];
  1181. } elseif ($data['type'] == 'datapage') {
  1182. $this->module = 'loyalty';
  1183. $this->type = 'datapage';
  1184. //$this->limits = array('max_limit_per_user' => null, 'max_global_limit' => null, 'max_limit_per_day' => null);
  1185. $this->scenario = 'dataview';
  1186. } elseif ($data['type'] == 'load') {
  1187. $this->module = 'gift';
  1188. $this->type = 'load';
  1189. } elseif ($data['type'] == 'bonus') {
  1190. $this->module = 'gift';
  1191. $this->type = 'bonus';
  1192. }
  1193. //reward
  1194. $rewardinfo = new stdClass();
  1195. if ($data['rewardinfo']['type'] == "reward") {
  1196. $this->rewardtype = "reward";
  1197. $this->amount = $data['rewardinfo']['amount'];
  1198. //$this->validatorList->add(CValidator::createValidator('required', $this, 'amount'));
  1199. //$this->validatorList->add(CValidator::createValidator('numerical', $this, 'amount', array('integerOnly' => true, 'min' => 1)));
  1200.  
  1201. $rewardinfo->type = $data['rewardinfo']['type'];
  1202. $rewardinfo->amount = intval($data['rewardinfo']['amount']);
  1203. $rewardinfo->wallet_id = intval($data['rewardinfo']['wallet_id']);
  1204. $rewardinfo->auto_redeem = false;
  1205. $rewardinfo->self_redeem = false;
  1206. } elseif ($data['rewardinfo']['type'] == "deal") {
  1207. $this->rewardtype = $data['rewardinfo']['type'];
  1208. $this->deal_id = $data['rewardinfo']['deal_id'];
  1209. $this->validatorList->add(CValidator::createValidator('validateDealId', $this, 'deal_id'));
  1210.  
  1211. $rewardinfo->type = $data['rewardinfo']['type'];
  1212. $rewardinfo->deal_id = $data['rewardinfo']['deal_id'];
  1213. $rewardinfo->auto_redeem = ($data['rewardinfo']['auto_redeem']) ? true : false;
  1214. $rewardinfo->self_redeem = ($data['rewardinfo']['self_redeem']) ? true : false;
  1215. } elseif ($data['rewardinfo']['type'] == "rolechange") {
  1216. $this->rewardtype = $data['rewardinfo']['type'];
  1217. $this->role_id = $data['rewardinfo']['role_id'];
  1218.  
  1219. $rewardinfo->type = $data['rewardinfo']['type'];
  1220. $rewardinfo->role_id = intval($data['rewardinfo']['role_id']);
  1221. $rewardinfo->auto_redeem = ($data['rewardinfo']['auto_redeem']) ? true : false;
  1222. $rewardinfo->self_redeem = ($data['rewardinfo']['self_redeem']) ? true : false;
  1223. } elseif ($data['rewardinfo']['type'] == "other") {
  1224. $this->rewardtype = $data['rewardinfo']['type'];
  1225. $this->other_reward = $data['rewardinfo']['other_reward'];
  1226. $this->validatorList->add(CValidator::createValidator('required', $this, 'other_reward'));
  1227.  
  1228. $rewardinfo->type = $data['rewardinfo']['type'];
  1229. $rewardinfo->other_reward = $data['rewardinfo']['other_reward'];
  1230. $rewardinfo->auto_redeem = ($data['rewardinfo']['auto_redeem']) ? true : false;
  1231. $rewardinfo->self_redeem = ($data['rewardinfo']['self_redeem']) ? true : false;
  1232. } elseif ($data['rewardinfo']['type'] == "coupon") {
  1233. $rewardinfo->type = $data['rewardinfo']['type'];
  1234. $rewardinfo->auto_redeem = ($data['rewardinfo']['auto_redeem']) ? true : false;
  1235. $rewardinfo->self_redeem = ($data['rewardinfo']['self_redeem']) ? true : false;
  1236. } elseif ($data['rewardinfo']['type'] == "promo") {
  1237. $rewardinfo->type = $data['rewardinfo']['type'];
  1238. $rewardinfo->auto_redeem = ($data['rewardinfo']['auto_redeem']) ? true : false;
  1239. $rewardinfo->self_redeem = ($data['rewardinfo']['self_redeem']) ? true : false;
  1240. } else {
  1241. $rewardinfo->type = "none";
  1242. $rewardinfo->auto_redeem = ($data['rewardinfo']['auto_redeem']) ? true : false;
  1243. $rewardinfo->self_redeem = ($data['rewardinfo']['self_redeem']) ? true : false;
  1244. }
  1245.  
  1246. //start date
  1247. if ($data['start_date']) {
  1248. $this->start_date = $data['start_date'];
  1249. } else {
  1250. $this->start_date = date('Y-m-d');
  1251. }
  1252.  
  1253. //end date
  1254. if ($data['end_date']) {
  1255. $this->end_date = $data['end_date'];
  1256. } else if ($data['days']) {
  1257. $this->end_date = date('Y-m-d', strtotime($this->start_date . ' + ' . $data['days'] . ' days'));
  1258. } else {
  1259. $this->end_date = date('Y-m-d', strtotime($this->start_date . ' + 1825 days'));
  1260. }
  1261. if ($this->validate()) {
  1262. if ($type == "community") {
  1263. /* * * commented due to change in credit system
  1264. if(Deals::countAllDealsOfACommunity($id)){
  1265. // amount for posting a deal
  1266. //If the community already has a deal, then this deal is a paid deal
  1267. $dealcharge = $data['days'] * Yii::app()->params['dealPricePerDay'];
  1268. $creditTransfers = new CreditTransfers('system');
  1269. $creditTransfers->transfer_from_id = $id;
  1270. $creditTransfers->transfer_from_type = 2;
  1271. $creditTransfers->transfer_amount = $dealcharge;
  1272. $creditTransfers->transfer_narration = "Payment for creating deal";
  1273.  
  1274. if(!$creditTransfers->transferCredits()){
  1275. throw new CHttpException(403, "payment_failed");
  1276. }
  1277.  
  1278. //comission to reseller
  1279. $modelCommunity = Communities::model()->findByPk($id);
  1280. $fee = floor($dealcharge * Yii::app()->params['resellerFeeForDeals']/100);
  1281. if($modelCommunity && $modelCommunity->community_resellerid && $fee>=1){
  1282. $modelCreditTransfers = new CreditTransfers('system');
  1283. $modelCreditTransfers->transfer_to_id = $modelCommunity->community_resellerid;
  1284. $modelCreditTransfers->transfer_to_type = 1;
  1285. $modelCreditTransfers->transfer_amount = $fee;
  1286. $modelCreditTransfers->transfer_narration = "comission to the reseller for deal";
  1287. if(!$modelCreditTransfers->transferCredits()){
  1288. throw new CHttpException(403, "payment_failed");
  1289. }
  1290. }
  1291. }
  1292. */
  1293. } elseif ($type == "user") {
  1294. /* * * commented due to change in credit system
  1295. if(Deals::countAllDealsOfAUser($id)){
  1296. //If the user already has a deal, then this deal is a paid deal
  1297. $dealcharge = $data['days'] * Yii::app()->params['dealPricePerDay'];
  1298.  
  1299. $creditTransfers = new CreditTransfers('system');
  1300. $creditTransfers->transfer_from_id = $id;
  1301. $creditTransfers->transfer_from_type = 1;
  1302. $creditTransfers->transfer_amount = $dealcharge;
  1303. $creditTransfers->transfer_narration = "Payment for creating deal";
  1304.  
  1305. if(!$creditTransfers->transferCredits()){
  1306. throw new CHttpException(403, "payment_failed");
  1307. }
  1308. }
  1309. */
  1310. }
  1311.  
  1312. //cost per view
  1313. if ($data['cost_per_view']) {
  1314. $cost_per_view = new stdClass();
  1315. $cost_per_view->amount = $data['cost_per_view']['amount'];
  1316. $cost_per_view->type = 'wallet';
  1317. $cost_per_view->wallet_id = $data['cost_per_view']['wallet_id'];
  1318. //save spend_ad_limit in mongo
  1319. //deduct ad_balance whenever cost_per_view is deducted.
  1320. $data['cost_per_view']['limit_spend'] = $data['cost_per_view']['limit_spend'] > 0 ? $data['cost_per_view']['limit_spend'] : 0;
  1321. $cost_per_view->ad_balance = $cost_per_view->limit_spend = $data['cost_per_view']['limit_spend'] > 0 ? $data['cost_per_view']['limit_spend'] : 0;
  1322.  
  1323. if ($cost_per_view->limit_spend > 0) {
  1324. //check for balance
  1325. $bal_type = $this->owner->type == 'user' ? 1 : 2;
  1326. $balance = WalletBalances::getWalletBalance($this->owner->id, $bal_type, $cost_per_view->wallet_id)['amount'];
  1327. if ($balance < $cost_per_view->limit_spend)
  1328. throw new CHttpException(404, 'insufficient_balance_to_spend');
  1329. else {
  1330. //deduct balance
  1331. $transferAd = new WalletTransfers;
  1332. $transferAd->settings = SiteSettings::getSettings();
  1333. $transferAd->transfer_from_id = $this->owner->id;
  1334. $transferAd->transfer_from_type = $bal_type;
  1335. $transferAd->transfer_from_wallet_id = $data['cost_per_view']['wallet_id'];
  1336. $transferAd->transfer_from_amount = $cost_per_view->limit_spend;
  1337. $transferAd->transfer_to_id = 8;
  1338. $transferAd->transfer_to_type = 3;
  1339. $transferAd->transfer_to_wallet_id = $data['cost_per_view']['wallet_id'];
  1340. $transferAd->transfer_narration = 'Payment for cost_per_view';
  1341. if (!$transferAd->transferInternal()) {
  1342. throw new CHttpException(403, 'fund_transfer_failed');
  1343. }
  1344. }
  1345. }
  1346. $this->cost_per_view = $cost_per_view;
  1347. }
  1348.  
  1349. //category
  1350. if ($data['category_id'] > 0) {
  1351. $category = new stdClass();
  1352. $category_name = Categories::getCategoryName($data['category_id']);
  1353. if ($category_name) {
  1354. $category->id = $data['category_id'];
  1355. $category->name = $category_name;
  1356. }
  1357. }
  1358.  
  1359. $parsedData->category = $category;
  1360. $parsedData->owner = $this->owner;
  1361. $parsedData->roles = $this->roles;
  1362. $parsedData->credit_type = $this->credit_type;
  1363. $parsedData->cost_per_view = $this->cost_per_view;
  1364. $parsedData->view_range_km = $this->view_range_km;
  1365.  
  1366. if ($this->probability)
  1367. $parsedData->probability = $this->probability;
  1368.  
  1369. if ($this->level)
  1370. $parsedData->level = $this->level;
  1371.  
  1372. if ($this->total_available)
  1373. $parsedData->total_available = $this->total_available;
  1374.  
  1375. if ($this->group)
  1376. $parsedData->group = $this->group;
  1377.  
  1378. /* if ($this->created_via)
  1379. $parsedData->created_via = $this->created_via; */
  1380.  
  1381. $parsedData->share_for_reward = $this->share_for_reward;
  1382. $parsedData->affiliate_fee = $fee;
  1383. $parsedData->pay_per_take = $ppt;
  1384. $parsedData->pay_per_click = $ppc;
  1385. $parsedData->price = $this->price;
  1386. $parsedData->tracker = uniqid() . rand(10 * 45, 100 * 98);
  1387.  
  1388. //Common::pre($parsedData, true);
  1389.  
  1390. $limits = new stdClass();
  1391. $limits->max_limit_per_user = ($data['limits']['max_limit_per_user']) ? intval($data['limits']['max_limit_per_user']) : NULL;
  1392. $limits->max_global_limit = ($data['limits']['max_global_limit']) ? intval($data['limits']['max_global_limit']) : NULL;
  1393. $limits->max_limit_per_day = ($data['limits']['max_limit_per_day']) ? intval($data['limits']['max_limit_per_day']) : NULL;
  1394.  
  1395. $parsedData->title = $data['title'];
  1396. $parsedData->description = $data['description'];
  1397.  
  1398. if ($data['food_type']) {
  1399. $parsedData->food_type = $data['food_type'];
  1400. }
  1401. $parsedData->start_date = $this->start_date;
  1402. $parsedData->end_date = $this->end_date;
  1403.  
  1404. if ($data['country']) {
  1405. $countryModel = Countries::model()->findByPk($data['country']);
  1406. $country = new stdClass();
  1407. $country->id = intval($countryModel->id);
  1408. $country->name = $countryModel->country_name;
  1409. }
  1410. $parsedData->module = $this->module;
  1411. $parsedData->country = $country;
  1412. $parsedData->location = $this->location;
  1413. $parsedData->city = $data['city'];
  1414. $parsedData->auto = $data['auto'];
  1415. $parsedData->visibility = $this->visibility;
  1416. $parsedData->tags = (is_array($data['tags'])) ? $data['tags'] : array();
  1417.  
  1418. $parsedData->rewardinfo = $rewardinfo;
  1419. $parsedData->limits = $limits;
  1420. $parsedData->url = $data['url'];
  1421.  
  1422. $parsedData->type = $this->type;
  1423. if ($this->dealinfo) {
  1424. $parsedData->dealinfo = $this->dealinfo;
  1425. }
  1426. if ($this->guestListColors) {
  1427. $parsedData->guestListColors = $this->guestListColors;
  1428. }
  1429. if ($this->guestlist) {
  1430. $parsedData->guestlist = $this->guestlist;
  1431. }
  1432. if ($this->methodofpayment) {
  1433. $parsedData->methodofpayment = $this->methodofpayment;
  1434. }
  1435. $parsedData->game_slots = $game_slots;
  1436. if ($catalogs)
  1437. $parsedData->items = $catalogs;
  1438. $parsedData->status = 1;
  1439. $collection = Yii::app()->edmsMongoCollection('deals');
  1440. $collection->insert($parsedData);
  1441. $dealId = (string) $parsedData->_id;
  1442. if ($dealId && $data['image'])
  1443. $this->avatarUpload($dealId, $data['image']);
  1444. return $dealId;
  1445. }
  1446. else {
  1447. return false;
  1448. }
  1449. }
  1450.  
  1451. // end of createDeal
  1452. //update deal
  1453. public function editDeal($dealId, $data, $ownerId = null, $type = null) {
  1454. if (!TagMongo::isValidId($dealId)) {
  1455. throw new CHttpException(404, invalid_deal_id);
  1456. }
  1457. $collection = Yii::app()->edmsMongoCollection('deals');
  1458. $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
  1459. $update = new stdClass;
  1460.  
  1461. $deal = $collection->findOne(array(
  1462. "_id" => new MongoID($dealId),
  1463. "owner.id" => intval($this->communityId),
  1464. "owner.type" => "community"
  1465. ));
  1466.  
  1467. if (!$deal) {
  1468. throw new CHttpException(404, 'invalid_deal');
  1469. }
  1470.  
  1471. //check permissions
  1472. if (!$this->isPermission('edit', $deal)) {
  1473. return false;
  1474. }
  1475.  
  1476. if ($data['roles']) {
  1477.  
  1478. if ($data['roles']['take']) {
  1479. $take = array();
  1480. for ($i = 0; $i < count($data['roles']['take']); $i++) {
  1481. //For converting the elements to integer
  1482. $take[$i] = intval($data['roles']['take'][$i]);
  1483. }
  1484. } else
  1485. $take = $deal['roles']['take'];
  1486.  
  1487. if ($data['roles']['assign']) {
  1488. $assign = array();
  1489. for ($i = 0; $i < count($data['roles']['assign']); $i++) {
  1490. //For converting the elements to integer
  1491. $assign[$i] = intval($data['roles']['assign'][$i]);
  1492. }
  1493. } else
  1494. $assign = $deal['roles']['assign'];
  1495.  
  1496. if ($data['roles']['redeem']) {
  1497. $redeem = array();
  1498. for ($i = 0; $i < count($data['roles']['redeem']); $i++) {
  1499. //For converting the elements to integer
  1500. $redeem[$i] = intval($data['roles']['redeem'][$i]);
  1501. }
  1502. } else
  1503. $redeem = $deal['roles']['redeem'];
  1504.  
  1505. if ($data['roles']['view']) {
  1506. $view = array();
  1507. for ($i = 0; $i < count($data['roles']['view']); $i++) {
  1508. //For converting the elements to integer
  1509. $view[$i] = intval($data['roles']['view'][$i]);
  1510. }
  1511. } else
  1512. $view = $deal['roles']['view'];
  1513.  
  1514. $update->roles['take'] = $take;
  1515. $update->roles['assign'] = $assign;
  1516. $update->roles['redeem'] = $redeem;
  1517. $update->roles['view'] = $view;
  1518. }
  1519. if (isset($data['title'])) {
  1520. $update->title = $data['title'];
  1521. }
  1522. if ($data['visibility']) {
  1523. $update->visibility = $data['visibility'];
  1524. }
  1525. if (isset($data['description'])) {
  1526. $update->description = $data['description'];
  1527. }
  1528. if ($data['food_type']) {
  1529. $update->description = $data['food_type'];
  1530. }
  1531. if ($data['location']) {
  1532. $location = array(floatval($data['location'][0]), floatval($data['location'][1]));
  1533. if (sizeof($location) != 2) {
  1534. $this->addError($attribute, 'Invalid location format(long,lat)');
  1535. } else if ((floatval($data['location'][0]) == 0) || ((floatval($data['location'][1]) == 0))) {
  1536. $location = null;
  1537. }
  1538. $update->location = $location;
  1539. }
  1540. if ($data['group']) {
  1541. $update->group = $data['group'];
  1542. }
  1543. if ($data['view_range_km']) {
  1544. $update->view_range_km = $data['view_range_km'];
  1545. }
  1546. if ($data['probability']) {
  1547. $update->probability = $data['probability'];
  1548. }
  1549. if ($data['level']) {
  1550. $update->level = $data['level'];
  1551. }
  1552. if ($data['total_available']) {
  1553. $update->total_available = $data['total_available'];
  1554. }
  1555. if ($data['country']) {
  1556. $countryModel = Countries::model()->findByPk($data['country']);
  1557. $country = new stdClass();
  1558. $country->id = intval($countryModel->id);
  1559. $country->name = $countryModel->country_name;
  1560.  
  1561. $update->country = $country;
  1562. }
  1563.  
  1564. //game slots - include in slot game rewards
  1565. if (isset($data['game_slots'])) {
  1566. $gameslot = $data['game_slots'];
  1567. $game_slots = new stdClass;
  1568.  
  1569. if ($gameslot['status'] == 1)
  1570. $game_slots->status = intval(1);
  1571. else
  1572. $game_slots->status = intval(0);
  1573.  
  1574. if ($gameslot['limit'] > 0)
  1575. $game_slots->limit = intval($gameslot['limit']);
  1576. else
  1577. $game_slots->limit = intval(0);
  1578. $update->game_slots = $game_slots;
  1579. }
  1580.  
  1581. if ($data['dealinfo']) {
  1582.  
  1583. if ($deal['type'] == 'stamp') {
  1584. $dealinfo = array(
  1585. //dealinfo array
  1586. 'take_action' => $takeAction,
  1587. 'total_stamps' => intval($data['dealinfo']['total_stamps']),
  1588. 'limit_per_day' => intval($data['dealinfo']['limit_per_day']));
  1589.  
  1590. $update->dealinfo = $dealinfo;
  1591. }
  1592. if ($deal['type'] == 'promo') {
  1593. $update->dealinfo = $data['dealinfo'];
  1594. }
  1595. if ($data['dealinfo']) {
  1596. if ($deal['type'] == 'food') {
  1597. $food = new stdClass;
  1598. $food->menu = $data['dealinfo'];
  1599. $update->dealinfo = $food;
  1600. }
  1601. if ($deal['type'] == 'book_spa') {
  1602. $update->dealinfo = $data['dealinfo'];
  1603. }
  1604. }
  1605. }
  1606.  
  1607. if ($data['rewardinfo']) {
  1608. //reward
  1609. $rewardinfo = new stdClass();
  1610. if ($data['rewardinfo']['type'] == "reward") {
  1611. $this->rewardtype = "reward";
  1612. $this->amount = $data['rewardinfo']['amount'];
  1613. $this->validatorList->add(CValidator::createValidator('required', $this, 'amount'));
  1614. $this->validatorList->add(CValidator::createValidator('numerical', $this, 'amount', array('integerOnly' => true, 'min' => 1)));
  1615.  
  1616. $rewardinfo->type = $data['rewardinfo']['type'];
  1617. $rewardinfo->amount = intval($data['rewardinfo']['amount']);
  1618. $rewardinfo->wallet_id = intval($data['rewardinfo']['wallet_id']);
  1619. $rewardinfo->auto_redeem = false;
  1620. $rewardinfo->self_redeem = false;
  1621. } elseif ($data['rewardinfo']['type'] == "deal") {
  1622. $this->rewardtype = $data['rewardinfo']['type'];
  1623. $this->deal_id = $data['rewardinfo']['deal_id'];
  1624. $this->validatorList->add(CValidator::createValidator('validateDealId', $this, 'deal_id'));
  1625.  
  1626. $rewardinfo->type = $data['rewardinfo']['type'];
  1627. $rewardinfo->deal_id = $data['rewardinfo']['deal_id'];
  1628. $rewardinfo->auto_redeem = ($data['rewardinfo']['auto_redeem']) ? true : false;
  1629. $rewardinfo->self_redeem = ($data['rewardinfo']['self_redeem']) ? true : false;
  1630. } elseif ($data['rewardinfo']['type'] == "rolechange") {
  1631. $this->rewardtype = $data['rewardinfo']['type'];
  1632. $this->role_id = $data['rewardinfo']['role_id'];
  1633.  
  1634. $rewardinfo->type = $data['rewardinfo']['type'];
  1635. $rewardinfo->role_id = intval($data['rewardinfo']['role_id']);
  1636. $rewardinfo->auto_redeem = ($data['rewardinfo']['auto_redeem']) ? true : false;
  1637. $rewardinfo->self_redeem = ($data['rewardinfo']['self_redeem']) ? true : false;
  1638. } elseif ($data['rewardinfo']['type'] == "other") {
  1639. $this->rewardtype = $data['rewardinfo']['type'];
  1640. $this->other_reward = $data['rewardinfo']['other_reward'];
  1641. $this->validatorList->add(CValidator::createValidator('required', $this, 'other_reward'));
  1642.  
  1643. $rewardinfo->type = $data['rewardinfo']['type'];
  1644. $rewardinfo->other_reward = $data['rewardinfo']['other_reward'];
  1645. $rewardinfo->auto_redeem = ($data['rewardinfo']['auto_redeem']) ? true : false;
  1646. $rewardinfo->self_redeem = ($data['rewardinfo']['self_redeem']) ? true : false;
  1647. } else {
  1648. $rewardinfo->type = "none";
  1649. $rewardinfo->auto_redeem = ($data['rewardinfo']['auto_redeem']) ? true : false;
  1650. $rewardinfo->self_redeem = ($data['rewardinfo']['self_redeem']) ? true : false;
  1651. }
  1652. $update->rewardinfo = $rewardinfo;
  1653. }
  1654. if ($data['limits']) {
  1655. $limit = array(
  1656. //limits array
  1657. 'max_global_limit' => intval($data['limits']['max_global_limit']),
  1658. 'max_limit_per_day' => intval($data['limits']["max_limit_per_day"]),
  1659. 'max_limit_per_user' => intval($data['limits']['max_limit_per_user']));
  1660. $update->limits = $limit;
  1661. }
  1662. if ($data['share_for_reward']) {
  1663. $share_for_reward = array();
  1664. if ($data['share_for_reward']['amount']) {
  1665. $share_for_reward['amount'] = intval($data['share_for_reward']['amount']);
  1666. } else {
  1667. $share_for_reward['amount'] = intval($deal['share_for_reward']['amount']);
  1668. }
  1669. if ($data['share_for_reward']['type']) {
  1670. $share_for_reward['type'] = $data['share_for_reward']['type'];
  1671. } else {
  1672. $share_for_reward['type'] = $deal['share_for_reward']['type'];
  1673. }
  1674.  
  1675. $update->share_for_reward = $share_for_reward;
  1676. }
  1677. if ($data['cost_per_view']) {
  1678. $cost_per_view = new stdClass();
  1679. $cost_per_view->amount = $data['cost_per_view']['amount'];
  1680. $cost_per_view->type = 'wallet';
  1681. $cost_per_view->wallet_id = $data['cost_per_view']['wallet_id'];
  1682. if (!$deal['cost_per_view']['limit_spend'] || $deal['cost_per_view']['limit_spend'] <= 0) {
  1683. $cost_per_view->limit_spend = $data['cost_per_view']['limit_spend'];
  1684. } else {
  1685. $cost_per_view->limit_spend = $deal['cost_per_view']['limit_spend'];
  1686. }
  1687. $cost_per_view->ad_balance = $deal['cost_per_view']['ad_balance'] > 0 ? $deal['cost_per_view']['ad_balance'] : 0;
  1688. //update spend_ad_limit in mongo
  1689. //now the ad spend cannot be updated
  1690. //$cost_per_view->limit_spend = $data['cost_per_view']['limit_spend'];
  1691. //$cost_per_view->ad_balance = $deal->cost_per_view['ad_balance'] + $cost_per_view->limit_spend;
  1692.  
  1693. $update->cost_per_view = $cost_per_view;
  1694. }
  1695.  
  1696. //category
  1697. if ($data['category_id'] > 0) {
  1698. $category = new stdClass();
  1699. $category_name = Categories::getCategoryName($data['category_id']);
  1700. if ($category_name) {
  1701. $category->id = $data['category_id'];
  1702. $category->name = $category_name;
  1703. $update->category = $category;
  1704. }
  1705. }
  1706.  
  1707. if (isset($data['catalog_items']) && Common::isJson($data['catalog_items'])) {
  1708. $catalog_items = json_decode($data['catalog_items'], true);
  1709. $details = array();
  1710. $i = 0;
  1711. foreach ($catalog_items as $item) {
  1712. //get complete list of items and store inside items details
  1713. $details[$i]['id'] = intval($item);
  1714. $query = Yii::app()->db->createCommand()
  1715. ->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')
  1716. ->from('catalog c')
  1717. ->leftJoin("catalog_category cc", "cc.id = c.category_id")
  1718. ->leftJoin("wallet_types wt", "wt.id = c.price_wallet")
  1719. ->where('c.id = ' . $item . ' AND c.community_id = ' . $this->communityId);
  1720. $result = $query->queryAll();
  1721. if (!$result)
  1722. continue;
  1723. $result = $result[0];
  1724. $details[$i]['catalog_name'] = $result['catalog_name'];
  1725. $details[$i]['category'] = $result['category_name'] ? array('id' => $result['category_id'], 'name' => $result['category_name']) : array();
  1726. $details[$i]['description'] = $result['description'];
  1727. $details[$i]['price'] = array('amount' => $result['price'], 'wallet_id' => $result['price_wallet'], 'wallet_name' => $result['currency_code']);
  1728. $details[$i]['weight'] = $result['weight'];
  1729. $size = array();
  1730. $color = array();
  1731. if ($result['sizes']) {
  1732. $size = explode(',', $result['sizes']);
  1733. }
  1734. if ($result['colors']) {
  1735. $color = explode(',', $result['colors']);
  1736. }
  1737. if ($result['other']) {
  1738. $other = explode(',', $result['other']);
  1739. }
  1740. $details[$i]['sizes'] = $size;
  1741. $details[$i]['colors'] = $color;
  1742. $details[$i]['other'] = $other;
  1743. $details[$i]['hashtags'] = $result['hashtags'] ? explode(',', $result['hashtags']) : array();
  1744. $details[$i]['stock'] = intval($result['stock']);
  1745. $details[$i]['time_to_ship'] = $result['time_to_ship'];
  1746.  
  1747. $i++;
  1748. }
  1749. $update->items = $details;
  1750. }
  1751.  
  1752. //delivery option
  1753. if (isset($data['delivery_options']) && is_array($data['delivery_options'])) {
  1754. if ($data['delivery_options']['type'] == 'xend')
  1755. $update->delivery_options = $data['delivery_options'];
  1756. else if ($data['delivery_options']['amount'] > 0 && $data['delivery_options']['wallet_id'] > 0) {
  1757. $update->delivery_options = $data['delivery_options'];
  1758. } else
  1759. $update->delivery_options = array();
  1760. }
  1761.  
  1762. if (isset($data['url'])) {
  1763. $update->url = $data['url'];
  1764. }
  1765.  
  1766. if(isset($data['status'])){
  1767. $update->status = $data['status'];
  1768. }
  1769.  
  1770. $stat = $collection->update(array(
  1771. "_id" => new MongoID($dealId),
  1772. "owner.id" => intval($this->communityId),
  1773. "owner.type" => "community"
  1774. ), array('$set' => $update));
  1775. $statLive = $liveCollection->update(array(
  1776. "deal_id" => new MongoID($dealId),
  1777. "owner.id" => intval($this->communityId),
  1778. "owner.type" => "community"
  1779. ), array('$set' => $update));
  1780.  
  1781. if ($stat && $statLive)
  1782. return true;
  1783. else
  1784. return false;
  1785. }
  1786.  
  1787. public static function extendDeal($dealId, $days = NULL, $id, $type, $date = NULL) {
  1788.  
  1789. if (!TagMongo::isValidId($dealId)) {
  1790. throw new CHttpException(404, invalid_deal_id);
  1791. }
  1792.  
  1793. $collection = Yii::app()->edmsMongoCollection('deals');
  1794. $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
  1795. $deal = $collection->findOne(array(
  1796. "_id" => new MongoID($dealId)
  1797. ));
  1798. if (!$deal) {
  1799. throw new CHttpException(404, 'invalid_deal');
  1800. }
  1801. if ($days > 0) {
  1802. $endDate = $deal['end_date'];
  1803. $newEndDate = date('Y-m-d', strtotime($endDate . ' + ' . $days . ' days'));
  1804. } else if ($date) {
  1805. $newEndDate = $date;
  1806. } else {
  1807. throw new CHttpException(403, "invalid_extend_period");
  1808. }
  1809. if ($type == "community") {
  1810. $collection->update(array(
  1811. "_id" => new MongoID($dealId),
  1812. "owner.id" => intval($id),
  1813. "owner.type" => "community"
  1814. ), array('$set' => array("end_date" => $newEndDate, 'status' => 1)));
  1815.  
  1816. $liveCollection->update(array(
  1817. "deal_id" => new MongoID($dealId),
  1818. "owner.id" => intval($id),
  1819. "owner.type" => "community"
  1820. ), array('$set' => array("end_date" => $newEndDate, 'status' => 1)));
  1821.  
  1822. return true;
  1823. //to be checked : credit transfers section.
  1824. /* if(Deals::countAllDealsOfACommunity($id) > 1){
  1825. //If the community already has a deal, then this deal is a paid deal
  1826. $dealcharge = $days * Yii::app()->params['dealPricePerDay'];
  1827.  
  1828. $creditTransfers = new CreditTransfers('system');
  1829. $creditTransfers->transfer_from_id = $id;
  1830. $creditTransfers->transfer_from_type = 2;
  1831. $creditTransfers->transfer_amount = $dealcharge;
  1832. $creditTransfers->transfer_narration = "Payment for extending deal : #".$dealId;
  1833.  
  1834. if($creditTransfers->transferCredits()){
  1835. $collection->update(array(
  1836. "_id" => new MongoID($dealId),
  1837. "owner.id" => intval($id),
  1838. "owner.type" => "community"
  1839. ), array('$set' => array("end_date" => $newEndDate, 'status'=>1)));
  1840.  
  1841. $liveCollection->update(array(
  1842. "deal_id" => new MongoID($dealId),
  1843. "owner.id" => intval($id),
  1844. "owner.type" => "community"
  1845. ), array('$set' => array("end_date" => $newEndDate, 'status'=>1)));
  1846.  
  1847. return true;
  1848. }
  1849. else{
  1850. return false;
  1851. }
  1852.  
  1853. // comission to reseller
  1854. $modelCommunity = Communities::model()->findByPk($id);
  1855. $fee = floor($dealcharge * Yii::app()->params['resellerFeeForDeals']/100);
  1856. if($modelCommunity && $modelCommunity->community_resellerid && $fee>=1){
  1857. $modelCreditTransfers = new CreditTransfers('system');
  1858. $modelCreditTransfers->transfer_to_id = $modelCommunity->community_resellerid;
  1859. $modelCreditTransfers->transfer_to_type = 1;
  1860. $modelCreditTransfers->transfer_amount = $fee;
  1861. $modelCreditTransfers->transfer_narration = "comission to the reseller for deal";
  1862. if(!$modelCreditTransfers->transferCredits()){
  1863. throw new CHttpException(403, "payment_failed");
  1864. }
  1865. }
  1866. }
  1867. else{
  1868. $collection->update(array(
  1869. "_id" => new MongoID($dealId),
  1870. "owner.id" => intval($id),
  1871. "owner.type" => "community"
  1872. ), array('$set' => array("end_date" => $newEndDate, 'status'=>1)));
  1873.  
  1874. $liveCollection->update(array(
  1875. "deal_id" => new MongoID($dealId),
  1876. "owner.id" => intval($id),
  1877. "owner.type" => "community"
  1878. ), array('$set' => array("end_date" => $newEndDate, 'status'=>1)));
  1879. } */
  1880. } elseif ($type == "user") { //disabled for the time being
  1881. if (Deals::countAllDealsOfAUser($id) > 1) {
  1882. //If the user already has a deal, then this deal is a paid deal
  1883. $dealcharge = $days * Yii::app()->params['dealPricePerDay'];
  1884.  
  1885. $creditTransfers = new CreditTransfers('system');
  1886. $creditTransfers->transfer_from_id = $id;
  1887. $creditTransfers->transfer_from_type = 1;
  1888. $creditTransfers->transfer_amount = $dealcharge;
  1889. $creditTransfers->transfer_narration = "Payment for extending deal : #" . $dealId;
  1890.  
  1891. if ($creditTransfers->transferCredits()) {
  1892. $collection->update(array(
  1893. "_id" => new MongoID($dealId),
  1894. "owner.id" => intval($id),
  1895. "owner.type" => "user"
  1896. ), array('$set' => array("end_date" => $newEndDate, 'status' => 1)));
  1897.  
  1898. $liveCollection->update(array(
  1899. "deal_id" => new MongoID($dealId),
  1900. "owner.id" => intval($id),
  1901. "owner.type" => "user"
  1902. ), array('$set' => array("end_date" => $newEndDate, 'status' => 1)));
  1903.  
  1904. return true;
  1905. } else {
  1906. return false;
  1907. }
  1908. } else {
  1909. $collection->update(array(
  1910. "_id" => new MongoID($dealId),
  1911. "owner.id" => intval($id),
  1912. "owner.type" => "user"
  1913. ), array('$set' => array("end_date" => $newEndDate, 'status' => 1)));
  1914.  
  1915. $liveCollection->update(array(
  1916. "deal_id" => new MongoID($dealId),
  1917. "owner.id" => intval($id),
  1918. "owner.type" => "user"
  1919. ), array('$set' => array("end_date" => $newEndDate, 'status' => 1)));
  1920.  
  1921. return true;
  1922. }
  1923. }
  1924. }
  1925.  
  1926. // end of extendDeal
  1927.  
  1928. /*
  1929. * * end of Create and Extend
  1930. */
  1931.  
  1932. /*
  1933. * * deals - remove, expired and history
  1934. */
  1935.  
  1936. public function removeDeal() {
  1937. //dealId, $userId, (if community perspective) $communityId, $role
  1938.  
  1939. if ($this->communityId) {
  1940. $collection = Yii::app()->edmsMongoCollection('deals');
  1941. $deal = $collection->findOne(array(
  1942. "_id" => new MongoID($this->dealId),
  1943. "owner.id" => intval($this->communityId),
  1944. "status" => array('$ne' => 1)
  1945. ));
  1946.  
  1947. if ($deal) {
  1948. $collection->update(
  1949. array("_id" => new MongoID($this->dealId)), array('$set' => array("status" => 2,
  1950. "end_date" => ''))
  1951. );
  1952.  
  1953. return true;
  1954. }
  1955. } else {
  1956. $collection = Yii::app()->edmsMongoCollection('deals_live');
  1957. $deal = $collection->findOne(array(
  1958. "deal_id" => new MongoID($this->dealId),
  1959. "user_id" => intval($this->userId)
  1960. ));
  1961.  
  1962. if ($deal) {
  1963. $this->updatePromised($deal, true);
  1964. $this->moveLiveDealToHistory($deal);
  1965. return true;
  1966. }
  1967. }
  1968.  
  1969. return false;
  1970. }
  1971.  
  1972. public function moveLiveDealToHistory($deal, $redeem = null) {
  1973. $historyDeal = new stdClass();
  1974. $historyDeal->deal_id = $deal['deal_id'];
  1975. //$historyDeal->deal_id = new MongoID($dealId);
  1976. $historyDeal->taken_date = date("Y-m-d H:i:s", $deal['_id']->getTimestamp());
  1977. $historyDeal->type = $deal['type'];
  1978. $historyDeal->owner = $deal['owner'];
  1979. $historyDeal->title = $deal['title'];
  1980. $historyDeal->description = $deal['description'];
  1981. $historyDeal->start_date = $deal['start_date'];
  1982. $historyDeal->end_date = $deal['end_date'];
  1983. $historyDeal->price = $deal['price'];
  1984. $historyDeal->city = $deal['city'];
  1985. $historyDeal->country = $deal['country'];
  1986. $historyDeal->visibility = $deal['visibility'];
  1987. $historyDeal->tags = $deal['tags'];
  1988. $historyDeal->dealinfo = $deal['dealinfo'];
  1989. $historyDeal->roles = $deal['roles'];
  1990. $historyDeal->rewardinfo = $deal['rewardinfo'];
  1991. $historyDeal->limits = $deal['limits'];
  1992. $historyDeal->status = 3;
  1993. $historyDeal->user_id = $deal['user_id'];
  1994. $historyDeal->assigner_id = $deal['assigner_id'];
  1995. $historyDeal->redeemer_id = intval($this->userId);
  1996. $historyDeal->userinfo = $deal['userinfo'];
  1997. $historyDeal->pay_per_take = $deal['pay_per_take'];
  1998. $historyDeal->pay_per_click = $deal['pay_per_click'];
  1999. if ($redeem == true) {
  2000. $historyDeal->date_redeemed = date('Y-m-d');
  2001. $redeemer_info = array();
  2002. $redeemer_info['user_id'] = intval($this->userId);
  2003. $user = Users::model()->findByPk($this->userId);
  2004. $redeemer_info['user_firstname'] = $user->user_firstname;
  2005. $redeemer_info['user_lastname'] = $user->user_lastname;
  2006. $historyDeal->redeemer_info = $redeemer_info;
  2007. }
  2008. //Insert into the history collection
  2009. $historyCollection = Yii::app()->edmsMongoCollection('deals_history');
  2010. $historyCollection->insert($historyDeal);
  2011.  
  2012. //Remove document from the live deals collection
  2013. $collection = Yii::app()->edmsMongoCollection('deals_live');
  2014. $collection->remove(array(
  2015. "_id" => $deal['_id']
  2016. ));
  2017. }
  2018.  
  2019. public function moveDealToHistory($deal) {
  2020. $historyDeal = (object) $deal;
  2021.  
  2022. //Insert into the history collection
  2023. $historyCollection = Yii::app()->edmsMongoCollection('deals_history');
  2024. $historyCollection->insert($historyDeal);
  2025.  
  2026. //Remove document from the live deals collection
  2027. $collection = Yii::app()->edmsMongoCollection('deals');
  2028. $collection->remove(array(
  2029. "_id" => $deal['_id']
  2030. ));
  2031. }
  2032.  
  2033. public static function getHistoryDeals($userId, $communityId = NULL) {
  2034. $collection = Yii::app()->edmsMongoCollection('deals_history');
  2035. if ($communityId) {
  2036. $deals = $collection->find(array(
  2037. "user_id" => intval($userId),
  2038. "owner.id" => intval($communityId),
  2039. "owner.type" => "community"
  2040. ));
  2041. } else {
  2042. $deals = $collection->find(array("user_id" => intval($userId)));
  2043. }
  2044.  
  2045. $parsedDeals = array();
  2046. if ($deals) {
  2047. foreach ($deals as $deal) {
  2048. $object = new stdClass;
  2049. $object->id = $deal['_id']->__toString();
  2050. $object->deal_id = $deal['deal_id']->__toString();
  2051. $object->taken_date = $deal['taken_date'];
  2052. $object->redeem_date = date("Y-m-d H:i:s", $deal['_id']->getTimestamp());
  2053. $object->title = $deal['title'];
  2054. $object->type = $deal['type'];
  2055. $object->dealinfo = $deal['dealinfo'];
  2056. $object->userinfo = $deal['userinfo'];
  2057.  
  2058. $object->owner = self::formatOwner($deal['owner']);
  2059. $object->status = self::formatStatus($deal['status']);
  2060.  
  2061. $parsedDeals[] = $object;
  2062. }
  2063. }
  2064.  
  2065. return $parsedDeals;
  2066. }
  2067.  
  2068. public static function getHistoryDealsOfACommunity($communityId, $params = array()) {
  2069. // pagination
  2070. if (isset($params['pageOffset']) && !is_numeric($params['pageOffset'])) {
  2071. $params['pageOffset'] = 0;
  2072. }
  2073.  
  2074. if (isset($params['pageCount']) && !is_numeric($params['pageCount'])) {
  2075. $params['pageCount'] = 100;
  2076. }
  2077. $collection = Yii::app()->edmsMongoCollection('deals_history');
  2078. $deals = $collection->find(array(
  2079. "owner.id" => intval($communityId),
  2080. "owner.type" => "community"
  2081. ))->skip($params['pageOffset'])
  2082. ->limit($params['pageCount']);
  2083.  
  2084. $parsedDeals = array();
  2085. if ($deals) {
  2086. foreach ($deals as $deal) {
  2087. $object = new stdClass;
  2088. $object->id = $deal['_id']->__toString();
  2089. $object->deal_id = $deal['deal_id']->__toString();
  2090. $object->taken_date = $deal['taken_date'];
  2091. $object->redeem_date = date("Y-m-d H:i:s", $deal['_id']->getTimestamp());
  2092. $object->title = $deal['title'];
  2093. $object->type = $deal['type'];
  2094. $object->dealinfo = $deal['dealinfo'];
  2095. $object->userinfo = $deal['userinfo'];
  2096. $object->status = self::formatStatus($deal['status']);
  2097.  
  2098. $parsedDeals[] = $object;
  2099. }
  2100. }
  2101.  
  2102. return $parsedDeals;
  2103. }
  2104.  
  2105. public static function getDealsHistoryOfATemplate($dealId, $userId = NULL) {
  2106. $query['deal_id'] = new MongoID($dealId);
  2107.  
  2108. if ($userId) {
  2109. //Get the history of a specific user if the user id is supplied
  2110. $query['user_id'] = intval($userId);
  2111. }
  2112.  
  2113. $collection = Yii::app()->edmsMongoCollection('deals_history');
  2114. $deals = $collection->find($query);
  2115.  
  2116. $parsedDeals = array();
  2117. if ($deals) {
  2118. foreach ($deals as $deal) {
  2119. $object = new stdClass;
  2120. $object->id = $deal['_id']->__toString();
  2121. $object->deal_id = $deal['deal_id']->__toString();
  2122. $object->taken_date = $deal['taken_date'];
  2123. $object->redeem_date = date("Y-m-d H:i:s", $deal['_id']->getTimestamp());
  2124. $object->title = $deal['title'];
  2125. $object->type = $deal['type'];
  2126. $object->dealinfo = $deal['dealinfo'];
  2127. $object->userinfo = $deal['userinfo'];
  2128. $object->status = self::formatStatus($deal['status']);
  2129.  
  2130. $parsedDeals[] = $object;
  2131. }
  2132. }
  2133.  
  2134. return $parsedDeals;
  2135. }
  2136.  
  2137. /*
  2138. * * deals - enof of remove, expired and history
  2139. */
  2140.  
  2141. /*
  2142. * * deals - take and assign
  2143. */
  2144.  
  2145. public function assignDeal($dealId, $assigneeId) {
  2146. if (!TagMongo::isValidId($dealId)) {
  2147. throw new CHttpException(404, "invalid_deal_id");
  2148. }
  2149.  
  2150. $userId = $this->userId;
  2151.  
  2152. $collection = Yii::app()->edmsMongoCollection('deals');
  2153. $deal = (object) $collection->findOne(array("_id" => new MongoID($dealId)));
  2154.  
  2155. //check deal validity
  2156. if (!$deal) {
  2157. throw new CHttpException(404, "invalid_deal");
  2158. } else if ($deal->status != 1) {
  2159. throw new CHttpException(403, "deal_unavailable");
  2160. }
  2161.  
  2162. $checkMember = CommunityUsers::model()->findByAttributes(array("user_id" => $assigneeId, "community_id" => $deal->owner['id']));
  2163. //if not member; automatically adds
  2164. if (!$checkMember) {
  2165. $role = CommunityRoles::model()->findByAttributes(array('community_id' => $deal->owner['id'], 'role_default' => '1'));
  2166. $roleId = $role->id;
  2167. $modelUsers = new CommunityUsers;
  2168. $modelUsers->user_id = $assigneeId;
  2169. $modelUsers->community_id = $deal->owner['id'];
  2170. $modelUsers->role_id = $roleId;
  2171. $modelUsers->communityuser_status = 1;
  2172. $modelUsers->communityuser_relation = 1;
  2173. $modelUsers->save();
  2174. }
  2175.  
  2176. //check deal taken
  2177. if (self::checkIfUserHasTakenDealBefore($assigneeId, $dealId)) {
  2178. //If the user has taken the deal before. He should not be able to take it again
  2179. throw new CHttpException(403, "already_taken");
  2180. }
  2181.  
  2182. //check permissions
  2183. if (!$this->isPermission('assign', $deal)) {
  2184. return false;
  2185. }
  2186.  
  2187.  
  2188. $liveDeal = new stdClass();
  2189. $liveDeal->deal_id = new MongoID($dealId);
  2190. $liveDeal->type = $deal->type;
  2191. $liveDeal->owner = $deal->owner;
  2192. $liveDeal->title = $deal->title;
  2193. $liveDeal->description = $deal->description;
  2194. $liveDeal->hiddenDescription = $deal->hiddenDescription;
  2195. $liveDeal->start_date = $deal->start_date;
  2196. $liveDeal->end_date = $deal->end_date;
  2197. $liveDeal->city = $deal->city;
  2198. $liveDeal->town = $deal->town;
  2199. $liveDeal->zipCode = $deal->zipCode;
  2200. $liveDeal->date_taken = date('Y-m-d');
  2201. $liveDeal->date_redeemed = "";
  2202. $liveDeal->auto = $deal->auto;
  2203. $liveDeal->country = $deal->country;
  2204. $liveDeal->visibility = $deal->visibility;
  2205. $liveDeal->tags = $deal->tags;
  2206. $liveDeal->dealinfo = $deal->dealinfo;
  2207. $liveDeal->roles = $deal->roles;
  2208. $liveDeal->limits = $deal->limits;
  2209. $liveDeal->total_value = $deal->total_value;
  2210. $liveDeal->credit_type = $deal->credit_type;
  2211. if ($deal->methodOfPayment) {
  2212. $liveDeal->methodOfPayment = $deal->methodOfPayment;
  2213. }
  2214. if ($deal->digitalDelivery) {
  2215. $liveDeal->digitalDelivery = $deal->digitalDelivery;
  2216. }
  2217. if ($deal->pickUpAddress) {
  2218. $liveDeal->pickUpAddress = $deal->pickUpAddress;
  2219. }
  2220. if ($deal->price) {
  2221. $liveDeal->price = $deal->price;
  2222. }
  2223. if ($deal->affiliate_fee) {
  2224. $liveDeal->affiliate_fee = $deal->affiliate_fee;
  2225. }
  2226. if ($deal->rewardinfo) {
  2227. $liveDeal->rewardinfo = $deal->rewardinfo;
  2228. }
  2229.  
  2230. if ($deal->pay_per_take)
  2231. $liveDeal->pay_per_take = $deal->pay_per_take;
  2232. if ($deal->pay_per_click)
  2233. $liveDeal->pay_per_click = $deal->pay_per_click;
  2234.  
  2235. if ($deal->collection)
  2236. $liveDeal->collection = $deal->collection;
  2237.  
  2238. $liveDeal->module = $deal->module;
  2239.  
  2240. if ($deal->module == "ecommerce") {
  2241. $liveDeal->status = 9;
  2242. } else {
  2243. $liveDeal->status = 8;
  2244. }
  2245.  
  2246. $liveDeal->user_id = intval($assigneeId);
  2247. $liveDeal->assigner_id = intval($userId);
  2248.  
  2249. $user = Users::model()->findByPk($assigneeId);
  2250.  
  2251. if (!$user) {
  2252. throw new CHttpException(403, "user_doesnt_exist");
  2253. }
  2254.  
  2255. if ($deal->type == "stamp") {
  2256. $userinfo = new stdClass;
  2257. $userinfo->id = intval($user->id);
  2258. $userinfo->user_firstname = $user->user_firstname;
  2259. $userinfo->user_lastname = $user->user_lastname;
  2260. $liveDeal->stamp_log = array();
  2261. $liveDeal->stamp_notes = array();
  2262. } else {
  2263. $userinfo = new stdClass;
  2264. $userinfo->id = intval($user->id);
  2265. $userinfo->user_firstname = $user->user_firstname;
  2266. $userinfo->user_lastname = $user->user_lastname;
  2267. }
  2268.  
  2269. //ticket
  2270. if ($deal->type == "ticket" && $deal->module == "ecommerce") {
  2271. $purchasedTickets = array('history' => array(), 'tickets' => array());
  2272. $liveDeal->purchasedTickets = $purchasedTickets;
  2273. } elseif ($deal->type == "promo") {
  2274. //Need to update the template also
  2275. //Find an available coupon from the deal
  2276. $parsedPromocodes = array();
  2277. if ($deal->dealinfo['promo_codes']) {
  2278. foreach ($deal->dealinfo['promo_codes'] as $promoCode) {
  2279. if ($promoCode['status'] == 0) {
  2280. //If an available promo code is found
  2281. $availableCode = $promoCode['code'];
  2282. $promoCode['status'] = 1;
  2283. $promoCode['userId'] = intval($user->id);
  2284.  
  2285. $parsedPromocodes[] = $promoCode;
  2286. } else {
  2287. $parsedPromocodes[] = $promoCode;
  2288. }
  2289. }
  2290. }
  2291. $total_available = intval($deal->total_available);
  2292. $total_available--;
  2293.  
  2294. $update['total_available'] = intval($total_available);
  2295. $update['dealinfo.promo_codes'] = $parsedPromocodes;
  2296. $stat = $collection->update(array('_id' => new MongoID($dealId)), array('$set' => $update));
  2297. if ($stat['ok'])
  2298. $liveDeal->dealinfo['promo_codes'] = $availableCode;
  2299. }elseif ($deal->type == "coupon") {
  2300. $total_available = intval($deal->total_available);
  2301. $total_available--;
  2302.  
  2303. $update['total_available'] = intval($total_available);
  2304. $collection->update(array('_id' => new MongoID($dealId)), array('$set' => $update));
  2305. }
  2306. $liveDeal->userinfo = $userinfo;
  2307. $liveDeal->orderedDate = date("Y-m-d H:i:s");
  2308. $liveDeal->paid = "yes";
  2309. $liveDeal->paidUsing = $deal->price['type'];
  2310. $liveDeal->orderItemCount = 1;
  2311.  
  2312. //update promised credits
  2313. if (!$this->updatePromised($liveDeal)) {
  2314. return false;
  2315. }
  2316.  
  2317. $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
  2318. $liveCollection->insert($liveDeal);
  2319. return true;
  2320. }
  2321.  
  2322. // end of assignDeal
  2323. //Deal assign to all
  2324. public function assignDealToAll($dealId, $assignees = NULL) {
  2325.  
  2326. if (!TagMongo::isValidId($dealId)) {
  2327. throw new CHttpException(404, "invalid_deal_id");
  2328. }
  2329.  
  2330. $collection = Yii::app()->edmsMongoCollection('deals');
  2331.  
  2332. $deal = $collection->findOne(array("_id" => new MongoID($dealId)));
  2333.  
  2334. //check deal validity
  2335. if (!$deal) {
  2336. throw new CHttpException(404, "invalid_deal");
  2337. } else if ($deal['status'] != 1) {
  2338. throw new CHttpException(403, "deal_unavailable");
  2339. }
  2340. if (count($assignees) == 0) {
  2341. $query = Yii::app()->db->createCommand()
  2342. ->select('user_id')
  2343. ->from('community_users com_usr')
  2344. ->leftJoin("community_roles comm_roles", "com_usr.role_id = comm_roles.id")
  2345. ->where('com_usr.community_id = :comId AND com_usr.communityuser_status = 1', array(':comId' => $this->communityId))
  2346. ->andWhere("com_usr.communityuser_status = 1
  2347. AND comm_roles.role_type = :roleType", array(':roleType' => 3));
  2348. //->queryScalar(array(':comId'=>$this->communityId));
  2349. $members = $query->queryAll();
  2350. } else {
  2351. foreach ($assignees as $assignee) {
  2352. $members[]['user_id'] = $assignee;
  2353. }
  2354. }
  2355.  
  2356. foreach ($members as $member) {
  2357. $assigneeUserId = $member['user_id'];
  2358.  
  2359. if ($assigneeUserId) {
  2360. $user = Users::model()->findByPk($assigneeUserId);
  2361. if ($user) {
  2362. $userId = $assigneeUserId;
  2363. } else {
  2364. $status_message['invalid_user'][] = $assigneeUserId;
  2365. continue;
  2366. }
  2367. }
  2368.  
  2369. //check whether user can take deal.
  2370. if (!Deals::checkIfUserCanTakeDeal($deal, $userId, $affiliateId)) {
  2371. $status_message['user_cannot_take_deal'][] = $assigneeUserId;
  2372. continue;
  2373. }
  2374. //check already taken and exists
  2375. if (self::checkIfUserHasTakenDealBefore($userId, $dealId)) {
  2376. //If the user has taken the deal before. He should not be able to take it again
  2377. $status_message['already_taken'][] = $assigneeUserId;
  2378. continue;
  2379. }
  2380. //permissions
  2381. if ($deal['owner']['type'] == "community") {
  2382. if (!CommunityUsers::isMemberOf($userId, $deal['owner']['id'])) {
  2383. $status_message['permission_denied'][] = $assigneeUserId;
  2384. continue;
  2385. }
  2386.  
  2387. $roleId = CommunityUsers::getRoleOfUser($userId, $deal['owner']['id'])->role_id;
  2388.  
  2389. if ($deal['roles']['take']) {
  2390. if (!in_array($roleId, $deal['roles']['take'])) {
  2391. $status_message['permission_denied'][] = $assigneeUserId;
  2392. continue;
  2393. }
  2394. } else {
  2395. $status_message['permission_denied'][] = $assigneeUserId;
  2396. continue;
  2397. }
  2398. } else {
  2399. //future
  2400. if (!Contacts::checkIfAlreadyAContact($userId, $deal['owner']['id'])) {
  2401. $status_message['permission_denied'][] = $assigneeUserId;
  2402. continue;
  2403. }
  2404. }
  2405.  
  2406. //price
  2407. if ($deal['price'] && ($deal['price']['amount'] > 0)) {
  2408. //If this is a paid deal
  2409. if ($deal['owner']['type'] == "community") {
  2410. //reward
  2411. if (!$deal['price']['type'] || ($deal['price']['type'] != 'wallet' && $deal['price']['type'] != 'wallets')) {
  2412. $rewardAllowance = RewardAllowances::model()->findByPk(array(
  2413. "user_id" => $userId,
  2414. "community_id" => $deal['owner']['id']
  2415. ));
  2416. if (!$rewardAllowance || !$rewardAllowance->checkCreditBalance($deal['price']['amount'])) {
  2417. $status_message['insufficient_amount'][] = $assigneeUserId;
  2418. continue;
  2419. }
  2420.  
  2421. $transfers = new RewardTransfers();
  2422. }
  2423. //wallet
  2424. else {
  2425. $walletBalance = WalletBalances::model()->findByAttributes(array(
  2426. 'balance_id' => $userId,
  2427. 'balance_type' => 1,
  2428. 'wallet_type_id' => $deal['price']['wallet_id'],
  2429. ));
  2430.  
  2431. if (!$walletBalance || !$walletBalance->checkWalletBalance($deal['price']['amount'])) {
  2432. $status_message['insufficient_amount'][] = $assigneeUserId;
  2433. continue;
  2434. }
  2435.  
  2436. $transfers = new WalletTransfers();
  2437. $transfers->transfer_from_wallet_id = $deal['price']['wallet_id'];
  2438. }
  2439. }
  2440. $transfers->transfer_amount = $deal['price']['amount'];
  2441. $transfers->transfer_from_id = $userId;
  2442. $transfers->transfer_from_type = 1;
  2443. $transfers->transfer_to_id = $deal['owner']['id'];
  2444. $transfers->transfer_to_type = ($deal['owner']['type'] == 'user') ? '1' : '2';
  2445. $transfers->transfer_narration = 'Payment for taking deal #' . $dealId;
  2446.  
  2447. if (!$transfers->transfer()) {
  2448. $status_message['payment_failed'][] = $assigneeUserId;
  2449. continue;
  2450. }
  2451. }
  2452.  
  2453. $liveDeal = new stdClass();
  2454. $liveDeal->deal_id = new MongoID($dealId);
  2455. $liveDeal->type = $deal['type'];
  2456. $liveDeal->owner = $deal['owner'];
  2457. $liveDeal->title = $deal['title'];
  2458. $liveDeal->description = $deal['description'];
  2459. $liveDeal->start_date = $deal['start_date'];
  2460. $liveDeal->end_date = $deal['end_date'];
  2461. $liveDeal->date_taken = date('Y-m-d');
  2462. $liveDeal->price = $deal['price'];
  2463. $liveDeal->city = $deal['city'];
  2464. $liveDeal->town = $deal['town'];
  2465. $liveDeal->zipCode = $deal['zipCode'];
  2466. $liveDeal->country = $deal['country'];
  2467. $liveDeal->visibility = $deal['visibility'];
  2468. $liveDeal->tags = $deal['tags'];
  2469. $liveDeal->dealinfo = $deal['dealinfo'];
  2470. $liveDeal->roles = $deal['roles'];
  2471. $liveDeal->rewardinfo = $deal['rewardinfo'];
  2472. $liveDeal->limits = $deal['limits'];
  2473. $liveDeal->total_value = $deal['total_value'];
  2474. $liveDeal->pay_per_take = $deal['pay_per_take'];
  2475. $liveDeal->pay_per_click = $deal['pay_per_click'];
  2476.  
  2477. if ($deal['type'] == "coupon") {
  2478. $liveDeal->status = 3;
  2479. } else {
  2480. $liveDeal->status = 1;
  2481. }
  2482.  
  2483. $liveDeal->user_id = intval($userId);
  2484. $liveDeal->assigner_id = NULL;
  2485.  
  2486. //affiliate
  2487. if ($deal['affiliate_fee'] && is_array($deal['affiliate_fee']) && $affiliateId && ($affiliateId != $userId)) {
  2488. $liveDeal->affiliate_fee = $deal['affiliate_fee'];
  2489. $liveDeal->affiliate_id = intval($affiliateId);
  2490. }
  2491.  
  2492. $userinfo = new stdClass;
  2493. $userinfo->id = intval($user->id);
  2494. $userinfo->user_firstname = $user->user_firstname;
  2495. $userinfo->user_lastname = $user->user_lastname;
  2496.  
  2497. if ($deal['type'] == "stamp") {
  2498. $userinfo->current_stamps = intval($deal['dealinfo']['starting_stamps']);
  2499. $stamp_log = array();
  2500.  
  2501. for ($i = 0; $i < $deal['dealinfo']['starting_stamps']; $i++) {
  2502. $object = new stdClass;
  2503. $object->timestamp = time();
  2504. $stamp_log[] = $object;
  2505. }
  2506. }
  2507.  
  2508. $liveDeal->userinfo = $userinfo;
  2509.  
  2510. if ($deal['type'] == "stamp") {
  2511. $liveDeal->stamp_log = $stamp_log;
  2512. }
  2513.  
  2514. //update promised credits
  2515. if (!$this->updatePromised($deal)) {
  2516. return false;
  2517. }
  2518.  
  2519. //commit
  2520. $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
  2521. $liveCollection->insert($liveDeal);
  2522.  
  2523. //PPT transaction for sharer and tagbond
  2524. if ($this->sharer) {
  2525. $sitesettings = SiteSettings::model()->find(array("select" => "ppt_percentage,admin_id"));
  2526.  
  2527. $ppt_valid = Deals::checkPPTValidity($dealId);
  2528. if ($ppt_valid) {
  2529. $user_ppt_amount = ($ppt_valid['amount'] * $sitesettings['ppt_percentage']) / 100;
  2530. $tagbond_ppt_amount = $ppt_valid['amount'] - $user_ppt_amount;
  2531.  
  2532. $transfer_sharer = new WalletTransfers;
  2533. $transfer_sharer->transfer_from_id = $ppt_valid['community_id'];
  2534. $transfer_sharer->transfer_from_type = 2;
  2535. $transfer_sharer->transfer_from_wallet_id = $ppt_valid['wallet_id'];
  2536. $transfer_sharer->transfer_from_amount = $user_ppt_amount;
  2537. $transfer_sharer->transfer_to_id = $this->sharer;
  2538. $transfer_sharer->transfer_to_type = 1;
  2539. $transfer_sharer->transfer_to_wallet_id = $ppt_valid['wallet_id'];
  2540. $transfer_sharer->transfer_narration = 'Payment for PayPerShare deal #' . $dealId;
  2541. if (!$transfer_sharer->transfer()) {
  2542. throw new CHttpException(403, 'reward_transfer_failed');
  2543. }
  2544.  
  2545. $transfer_tagbond = new WalletTransfers;
  2546. $transfer_tagbond->scenario = 'system';
  2547. $transfer_tagbond->transfer_from_id = $ppt_valid['community_id'];
  2548. $transfer_tagbond->transfer_from_type = 2;
  2549. $transfer_tagbond->transfer_from_wallet_id = $ppt_valid['wallet_id'];
  2550. $transfer_tagbond->transfer_from_amount = $tagbond_ppt_amount;
  2551. $transfer_tagbond->transfer_to_id = $sitesettings['admin_id'];
  2552. $transfer_tagbond->transfer_to_type = 3;
  2553. $transfer_tagbond->transfer_to_wallet_id = $ppt_valid['wallet_id'];
  2554. $transfer_tagbond->transfer_narration = 'Commission for PayPerShare deal #' . $dealId;
  2555. if (!$transfer_tagbond->transfer()) {
  2556. throw new CHttpException(403, 'reward_transfer_failed');
  2557. }
  2558. }
  2559. }
  2560. }
  2561. if (count($status_message) == 0)
  2562. return "success";
  2563. else
  2564. return $status_message;
  2565. }
  2566.  
  2567. public function takeDeal($dealId, $affiliateId = NULL, $assigneeUserId = NULL, $data = NULL) {
  2568.  
  2569. if ($assigneeUserId) {
  2570. $user = Users::model()->findByPk($assigneeUserId);
  2571. if ($user) {
  2572. $userId = $assigneeUserId;
  2573. } else {
  2574. throw new CHttpException(404, "invalid_deal_id");
  2575. }
  2576. }
  2577.  
  2578. $userId = $this->userId;
  2579.  
  2580. if (!TagMongo::isValidId($dealId)) {
  2581. throw new CHttpException(404, "invalid_deal_id");
  2582. }
  2583.  
  2584. $collection = Yii::app()->edmsMongoCollection('deals');
  2585. $deal = $collection->findOne(array("_id" => new MongoID($dealId)));
  2586.  
  2587. if (!$deal) {
  2588. throw new CHttpException(403, "invalid_deal_id");
  2589. } else if ($deal['type'] == 'ticket') {
  2590. throw new CHttpException(403, "please_purchase_ticket");
  2591. }
  2592.  
  2593. if ($deal['status'] != 1) {
  2594. throw new CHttpException(403, "deal_unavailable");
  2595. }
  2596.  
  2597. if ($deal['type'] != 'catalog') {
  2598. $can_take = Deals::checkIfUserCanTakeDeal($deal, $userId, $affiliateId);
  2599. if (!$can_take || $can_take->can_take == false) {
  2600. throw new CHttpException(403, "user_cannot_take_deal");
  2601. }
  2602.  
  2603. //check already taken and exists
  2604. if (self::checkIfUserHasTakenDealBefore($userId, $dealId)) {
  2605. //If the user has taken the deal before. He should not be able to take it again
  2606. throw new CHttpException(403, "already_taken");
  2607. }
  2608.  
  2609. //permissions
  2610. if ($deal['owner']['type'] == "community") {
  2611. if (!CommunityUsers::isMemberOf($userId, $deal['owner']['id'])) {
  2612. throw new CHttpException(403, "not_member");
  2613. }
  2614.  
  2615. $roleId = CommunityUsers::getRoleOfUser($userId, $deal['owner']['id'])->role_id;
  2616.  
  2617. if ($deal['roles']['take']) {
  2618. if (!in_array($roleId, $deal['roles']['take'])) {
  2619. throw new CHttpException(403, "permission_denied");
  2620. }
  2621. } else {
  2622. throw new CHttpException(403, "permission_denied");
  2623. }
  2624. } else {
  2625. //future
  2626. if (!Contacts::checkIfAlreadyAContact($userId, $deal['owner']['id'])) {
  2627. throw new CHttpException(403, "not_contact");
  2628. }
  2629. }
  2630.  
  2631. //price
  2632. if ($deal['price'] && ($deal['price']['amount'] > 0)) {
  2633. //If this is a paid deal
  2634. if ($deal['owner']['type'] == "community") {
  2635. //reward
  2636. if (!$deal['price']['type'] || ($deal['price']['type'] != 'wallet' && $deal['price']['type'] != 'wallets')) {
  2637. $rewardAllowance = RewardAllowances::model()->findByPk(array(
  2638. "user_id" => $userId,
  2639. "community_id" => $deal['owner']['id']
  2640. ));
  2641. if (!$rewardAllowance || !$rewardAllowance->checkCreditBalance($deal['price']['amount'])) {
  2642. throw new CHttpException(403, "insufficient_amount");
  2643. }
  2644.  
  2645. $transfers = new RewardTransfers();
  2646. }
  2647. //wallet
  2648. else {
  2649. $walletBalance = WalletBalances::model()->findByAttributes(array(
  2650. 'balance_id' => $userId,
  2651. 'balance_type' => 1,
  2652. 'wallet_type_id' => $deal['price']['wallet_id'],
  2653. ));
  2654.  
  2655. if (!$walletBalance || !$walletBalance->checkWalletBalance($deal['price']['amount'])) {
  2656. throw new CHttpException(403, "insufficient_amount");
  2657. }
  2658.  
  2659. $transfers = new WalletTransfers();
  2660. $transfers->transfer_from_wallet_id = $deal['price']['wallet_id'];
  2661. $transfers->transfer_to_wallet_id = $deal['price']['wallet_id'];
  2662. }
  2663. }
  2664. $transfers->settings = SiteSettings::getSettings();
  2665. $transfers->userId = $userId;
  2666. $transfers->user = $this->user;
  2667. $transfers->transfer_amount = $deal['price']['amount'];
  2668. $transfers->transfer_from_amount = $deal['price']['amount'];
  2669. $transfers->transfer_from_id = $userId;
  2670. $transfers->transfer_from_type = 1;
  2671. $transfers->transfer_to_id = $deal['owner']['id'];
  2672. $transfers->transfer_to_type = ($deal['owner']['type'] == 'user') ? '1' : '2';
  2673. $transfers->transfer_narration = 'Payment for taking deal #' . $dealId;
  2674.  
  2675. if (!$transfers->transfer()) {
  2676. throw new CHttpException(403, "payment_failed");
  2677. }
  2678.  
  2679. /* //update promised community credits
  2680. if(is_array($deal['rewardinfo']) && $deal['rewardinfo']['type'] == 'credits'){
  2681. $communtiy = new Communities();
  2682. if(!$community->updatePromisedCredits($deal['owner']['id'],$deal['rewardinfo']['amount'])){
  2683. throw new CHttpException(403, "update_promised_failed");
  2684. }
  2685. } */
  2686. }
  2687. }
  2688. $liveDeal = new stdClass();
  2689. $liveDeal->deal_id = new MongoID($dealId);
  2690. $liveDeal->type = $deal['type'];
  2691. $liveDeal->owner = $deal['owner'];
  2692. $liveDeal->title = $deal['title'];
  2693. $liveDeal->description = $deal['description'];
  2694. $liveDeal->start_date = $deal['start_date'];
  2695. $liveDeal->end_date = $deal['end_date'];
  2696. $liveDeal->date_taken = date('Y-m-d H:i:s');
  2697. $liveDeal->price = $deal['price'];
  2698. $liveDeal->city = $deal['city'];
  2699. $liveDeal->town = $deal['town'];
  2700. $liveDeal->zipCode = $deal['zipCode'];
  2701. $liveDeal->country = $deal['country'];
  2702. $liveDeal->visibility = $deal['visibility'];
  2703. $liveDeal->tags = $deal['tags'];
  2704. $liveDeal->dealinfo = $deal['dealinfo'];
  2705. $liveDeal->roles = $deal['roles'];
  2706. $liveDeal->rewardinfo = $deal['rewardinfo'];
  2707. $liveDeal->limits = $deal['limits'];
  2708. $liveDeal->total_value = $deal['total_value'];
  2709. $liveDeal->pay_per_take = $deal['pay_per_take'];
  2710. $liveDeal->pay_per_click = $deal['pay_per_click'];
  2711.  
  2712. if ($deal['type'] == "coupon") {
  2713. $liveDeal->status = 3;
  2714. } else {
  2715. $liveDeal->status = 1;
  2716. }
  2717.  
  2718. $liveDeal->user_id = intval($userId);
  2719. $liveDeal->assigner_id = NULL;
  2720.  
  2721. $user = Users::model()->findByPk($userId);
  2722.  
  2723. if (!$user) {
  2724. throw new CHttpException(403, "user_doesnt_exist");
  2725. }
  2726.  
  2727. //affiliate
  2728. if ($deal['affiliate_fee'] && is_array($deal['affiliate_fee']) && $affiliateId && ($affiliateId != $userId)) {
  2729. $liveDeal->affiliate_fee = $deal['affiliate_fee'];
  2730. $liveDeal->affiliate_id = intval($affiliateId);
  2731. }
  2732.  
  2733. $userinfo = new stdClass;
  2734. $userinfo->id = intval($user->id);
  2735. $userinfo->user_firstname = $user->user_firstname;
  2736. $userinfo->user_lastname = $user->user_lastname;
  2737.  
  2738. if ($deal['type'] == "stamp") {
  2739. $userinfo->current_stamps = intval($deal['dealinfo']['starting_stamps']);
  2740. $stamp_log = array();
  2741.  
  2742. for ($i = 0; $i < $deal['dealinfo']['starting_stamps']; $i++) {
  2743. $object = new stdClass;
  2744. $object->timestamp = time();
  2745. $stamp_log[] = $object;
  2746. }
  2747. }
  2748.  
  2749. if ($deal['type'] == "catalog") {
  2750. $liveDeal->priority = 0;
  2751. $liveDeal->delivery_options = $deal['delivery_options'];
  2752. if ($data != NULL) {
  2753. $i = 0;
  2754. foreach ($data['purchased_items'] as $pitem) {
  2755. foreach ($deal['items'] as $item) {
  2756. if ($item['id'] == $pitem->item) {
  2757. $count = $pitem->count;
  2758. if ($pitem->size)
  2759. $size = $pitem->size;
  2760. if ($pitem->color)
  2761. $color = $pitem->color;
  2762. if ($pitem->other)
  2763. $other = $pitem->other;
  2764.  
  2765. $item_list[$i] = $item;
  2766. $item_list[$i]['count'] = $count;
  2767. if ($size)
  2768. $item_list[$i]['sizes'] = $size;
  2769.  
  2770. if ($color)
  2771. $item_list[$i]['colors'] = $color;
  2772.  
  2773. if ($other)
  2774. $item_list[$i]['other'] = $other;
  2775.  
  2776. $i++;
  2777. }
  2778. }
  2779. }
  2780. $liveDeal->purchase_details['order_id'] = $data['order_id'];
  2781. $liveDeal->purchase_details['items'] = $item_list;
  2782. $liveDeal->purchase_details['delivery_address'] = $data['delivery_address'];
  2783. $liveDeal->purchase_details['order_date'] = date('Y-m-d H:i:s');
  2784. $liveDeal->purchase_details['delivery_method'] = array();
  2785. if ($data['delivery_method']) {
  2786. $liveDeal->purchase_details['delivery_method']['method'] = $data['delivery_method'];
  2787. }
  2788. $liveDeal->purchase_details['payment_details']['total_amount'] = $data['amount'];
  2789. $liveDeal->purchase_details['payment_details']['wallet_id'] = $data['wallet_id'];
  2790. $liveDeal->purchase_details['payment_details']['paid_using'] = $data['payment_method'];
  2791. $liveDeal->purchase_details['payment_details']['transaction_id'] = $data['transaction_id'];
  2792. }
  2793. }
  2794. if ($deal['type'] == "bus_reservation") {
  2795. $liveDeal->dealinfo['passengers'] = $data;
  2796. }
  2797. if ($deal['type'] == "promo") {
  2798. //Need to update the template also
  2799. //Find an available coupon from the deal
  2800. $parsedPromocodes = array();
  2801. if ($deal['dealinfo']['promo_codes']) {
  2802. foreach ($deal['dealinfo']['promo_codes'] as $promoCode) {
  2803. if ($promoCode['status'] == 0) {
  2804. //If an available promo code is found
  2805. $availableCode = $promoCode['code'];
  2806. $promoCode['status'] = 1;
  2807. $promoCode['userId'] = intval($user->id);
  2808.  
  2809. $parsedPromocodes[] = $promoCode;
  2810. } else {
  2811. $parsedPromocodes[] = $promoCode;
  2812. }
  2813. }
  2814. }
  2815. $total_available = intval($deal['total_available']);
  2816. $total_available--;
  2817.  
  2818. $update['total_available'] = intval($total_available);
  2819. $update['dealinfo.promo_codes'] = $parsedPromocodes;
  2820. $stat = $collection->update(array('_id' => new MongoID($dealId)), array('$set' => $update));
  2821. if ($stat['ok'])
  2822. $liveDeal->dealinfo['promo_codes'] = $availableCode;
  2823. }
  2824. if ($deal['type'] == "coupon") {
  2825. $total_available = intval($deal['total_available']);
  2826. $total_available--;
  2827.  
  2828. $update['total_available'] = intval($total_available);
  2829. $collection->update(array('_id' => new MongoID($dealId)), array('$set' => $update));
  2830. }
  2831. $liveDeal->userinfo = $userinfo;
  2832.  
  2833. if ($deal['type'] == "stamp") {
  2834. $liveDeal->stamp_log = $stamp_log;
  2835. }
  2836.  
  2837. //update promised credits
  2838. if (!$this->updatePromised($deal)) {
  2839. return false;
  2840. }
  2841. //commit
  2842. $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
  2843. $liveCollection->insert($liveDeal);
  2844.  
  2845. //PPT transaction for sharer and tagbond
  2846. if ($this->sharer) {
  2847. $sitesettings = SiteSettings::model()->find(array("select" => "ppt_percentage,admin_id"));
  2848.  
  2849. $ppt_valid = Deals::checkPPTValidity($dealId);
  2850. if ($ppt_valid) {
  2851. $user_ppt_amount = ($ppt_valid['amount'] * $sitesettings['ppt_percentage']) / 100;
  2852. $tagbond_ppt_amount = $ppt_valid['amount'] - $user_ppt_amount;
  2853.  
  2854. $transfer_sharer = new WalletTransfers;
  2855. $transfer_sharer->transfer_from_id = $ppt_valid['community_id'];
  2856. $transfer_sharer->transfer_from_type = 2;
  2857. $transfer_sharer->transfer_from_wallet_id = $ppt_valid['wallet_id'];
  2858. $transfer_sharer->transfer_from_amount = $user_ppt_amount;
  2859. $transfer_sharer->transfer_to_id = $this->sharer;
  2860. $transfer_sharer->transfer_to_type = 1;
  2861. $transfer_sharer->transfer_to_wallet_id = $ppt_valid['wallet_id'];
  2862. $transfer_sharer->transfer_narration = 'Payment for PayPerTake deal #' . $dealId;
  2863. if (!$transfer_sharer->transfer()) {
  2864. throw new CHttpException(403, 'reward_transfer_failed');
  2865. }
  2866.  
  2867. $transfer_tagbond = new WalletTransfers;
  2868. $transfer_tagbond->scenario = 'system';
  2869. $transfer_tagbond->transfer_from_id = $ppt_valid['community_id'];
  2870. $transfer_tagbond->transfer_from_type = 2;
  2871. $transfer_tagbond->transfer_from_wallet_id = $ppt_valid['wallet_id'];
  2872. $transfer_tagbond->transfer_from_amount = $tagbond_ppt_amount;
  2873. $transfer_tagbond->transfer_to_id = $sitesettings['admin_id'];
  2874. $transfer_tagbond->transfer_to_type = 3;
  2875. $transfer_tagbond->transfer_to_wallet_id = $ppt_valid['wallet_id'];
  2876. $transfer_tagbond->transfer_narration = 'Commission for PayPerTake deal #' . $dealId;
  2877. if (!$transfer_tagbond->transfer()) {
  2878. throw new CHttpException(403, 'reward_transfer_failed');
  2879. }
  2880. }
  2881. }
  2882.  
  2883. return true;
  2884. }
  2885.  
  2886. // end of takeDeal
  2887.  
  2888. public static function getAssignableDeals($communityId, $userId, $params) {
  2889. if (!is_numeric($params['count']) || $params['count'] > 100) {
  2890. $params['count'] = 100;
  2891. }
  2892.  
  2893. if (!is_numeric($params['offset'])) {
  2894. $params['offset'] = 0;
  2895. }
  2896.  
  2897. $role = CommunityUsers::model()->with('role')->findByAttributes(array('user_id' => $userId, 'community_id' => $communityId));
  2898.  
  2899. if ($role) {
  2900. $collection = Yii::app()->edmsMongoCollection('deals');
  2901.  
  2902. if ($role->role->role_type == 1) {
  2903. //If Owner, show all deals in the community
  2904. $deals = $collection->find(array(
  2905. "owner.id" => intval($communityId),
  2906. "owner.type" => "community",
  2907. "status" => 1))
  2908. ->skip($params['offset'])
  2909. ->limit($params['count']);
  2910. } elseif ($role->role->role_type == 2) {
  2911. //Staff
  2912. $deals = $collection->find(array(
  2913. "owner.id" => intval($communityId),
  2914. "owner.type" => "community",
  2915. "roles.assign" => $roleId,
  2916. "status" => 1))
  2917. ->skip($params['offset'])
  2918. ->limit($params['count']);
  2919. } else {
  2920. //If member
  2921. throw new CHttpException(403, "permission_denied");
  2922. }
  2923.  
  2924. $parsedDeals = array();
  2925. if ($deals) {
  2926. foreach ($deals as $deal) {
  2927. $parsedDeals[] = self::formatDeal($deal);
  2928. }
  2929. }
  2930.  
  2931. return $parsedDeals;
  2932. } else {
  2933. throw new CHttpException(403, "permission_denied");
  2934. }
  2935. }
  2936.  
  2937. public static function checkIfUserHasTakenDealBefore($userId, $dealId) {
  2938. if (self::countTimesTaken($dealId, false, $userId)) {
  2939. return true;
  2940. } else {
  2941. return false;
  2942. }
  2943. }
  2944.  
  2945. /* Intelligent :) function to check whether the user can take deal */
  2946.  
  2947. public static function checkIfUserCanTakeDeal($deal, $userId, $affiliateId = NULL) {
  2948. //userId = takerId
  2949. $object = new stdClass;
  2950. $object->can_take = true;
  2951. $object->errors = array();
  2952.  
  2953. $modelUsers = Users::model()->findByPk($userId);
  2954. $modelCommunity = Communities::model()->findByPk($deal['owner']['id']);
  2955. if (!$modelUsers || !$modelCommunity)
  2956. return false;
  2957. $role = CommunityUsers::getRoleOfUser($userId, $deal['owner']['id']);
  2958.  
  2959. if ($deal['owner']['type'] == "community") {
  2960.  
  2961. $dealId = $deal['_id'];
  2962.  
  2963. //limits - Per User, Per Day and Global Limit
  2964. if ($deal['limits']['max_global_limit']) {
  2965.  
  2966. if (Deals::countTimesTaken($dealId, true) >= $deal['limits']['max_global_limit']) {
  2967. $object->errors[] = 'limit_exceeded';
  2968. }
  2969. } else {
  2970. if ($deal['limits']['max_limit_per_day']) {
  2971. if (Deals::countTimesTakenPerDay($dealId) >= $deal['limits']['max_limit_per_day']) {
  2972. $object->errors[] = 'limit_per_day_exceeded';
  2973. }
  2974. } else {
  2975. if ($deal['limits']['max_limit_per_user']) {
  2976. if (Deals::countTimesTaken($dealId, true, $userId) >= $deal['limits']['max_limit_per_user']) {
  2977. $object->errors[] = 'limit_per_user_exceeded';
  2978. }
  2979. }
  2980. }
  2981. }
  2982.  
  2983. $object->community_roles = CommunityRoles::getNameOfRoles($deal['roles']['take']);
  2984.  
  2985. if ($role) {
  2986. if ($role->communityuser_status == 1) {
  2987. $object->communityuser_status = true;
  2988. //If the user is a part of the community
  2989. if ($role->role_type == 3) {
  2990. //If he is a member
  2991. $object->community_relation = "member";
  2992.  
  2993. //checking roles
  2994. if (!in_array($role->role_id, $deal['roles']['take'])) {
  2995. //Means this user doesnt have the permission to take this deal
  2996. $object->errors[] = 'invalid_community_role';
  2997. }
  2998. } else {
  2999. $object->community_relation = "staff";
  3000. $object->errors[] = 'invalid_community_role_type';
  3001. }
  3002. } else {
  3003. $object->communityuser_status = false;
  3004. $object->errors[] = 'pending_community_request';
  3005. }
  3006. } else {
  3007. $object->can_join = true;
  3008. $object->community_relation = "non_member";
  3009.  
  3010. //checking community type, autojoin, join
  3011. if ($modelCommunity->community_type == 1) { //private
  3012. $object->community_type = "private";
  3013. $object->can_join = false;
  3014. $object->errors[] = 'private_community';
  3015. } else {
  3016. //check if user eligible to join
  3017. $eligibility = Communities::checkIfUserIsEligibleToJoin($modelUsers, $modelCommunity);
  3018. if (!$eligibility->eligible) {
  3019. $object->can_join = false;
  3020. $object->errors[] = array('community_eligibility' => $eligibility->errors);
  3021. } else {
  3022. if ($modelCommunity->community_type == 0) { //public
  3023. $object->community_type = "public";
  3024.  
  3025. if ($modelCommunity->community_autojoin) {
  3026. $object->community_autojoin = true;
  3027. } else {
  3028. $object->community_autojoin = false;
  3029. $object->errors[] = 'invalid_community_autojoin';
  3030. }
  3031. } else if ($modelCommunity->community_type == 2) { //paid
  3032. $object->community_type = "paid";
  3033. $object->community_fee = intval($modelCommunity->community_fee);
  3034. }
  3035. }
  3036.  
  3037. //checking roles
  3038. $defaultRole = CommunityRoles::getDefaultRole($deal['owner']['id']);
  3039. if (!in_array($defaultRole->id, $deal['roles']['take'])) {
  3040. //Means this user doesnt have the role permission to take this deal if joined
  3041. $object->errors[] = 'invalid_community_role';
  3042. }
  3043. }
  3044. }
  3045. }
  3046.  
  3047. //credits needed for taking the deal
  3048. $total_credits = 0;
  3049.  
  3050. //check credit balance over community price
  3051. if (!$role && $modelCommunity->community_type == 2) {
  3052. $object->can_join = true;
  3053. // need to do community fee
  3054. }
  3055.  
  3056. // check deal price
  3057. if ($deal['price'] && ($deal['price']['amount'] > 0)) {
  3058. // check allowance balance over deal price
  3059. if (!$deal['price']['type'] || ($deal['price']['type'] != 'wallet' && $deal['price']['type'] != 'wallets')) {
  3060. $rewardAllowance = RewardAllowances::model()->findByPk(array(
  3061. 'user_id' => $userId,
  3062. 'community_id' => $deal['owner']['id']
  3063. ));
  3064.  
  3065. if (!$rewardAllowance || !$rewardAllowance->checkCreditBalance($deal['price']['amount'])) {
  3066. $object->errors[] = 'insufficient_amount';
  3067. }
  3068. } else {
  3069. $walletBalance = WalletBalances::model()->findByAttributes(array(
  3070. 'balance_id' => $userId,
  3071. 'balance_type' => 1,
  3072. 'wallet_type_id' => $deal['price']['wallet_id'],
  3073. ));
  3074.  
  3075. if (!$walletBalance || !$walletBalance->checkWalletBalance($deal['price']['amount'])) {
  3076. $object->errors[] = 'insufficient_amount';
  3077. }
  3078. }
  3079. }
  3080.  
  3081. //need to update and fix
  3082. //promised credits
  3083. $promisedCredits = 0;
  3084. //check promised credits - reward
  3085. if (is_array($deal['rewardinfo']) && $deal['rewardinfo']['type'] == 'reward') {
  3086. if ($modelCommunity->community_credits < ($modelCommunity->community_promised_credits + $deal['rewardinfo']['amount'])) {
  3087. $object->errors[] = 'insufficient_community_credits_for_deal_reward';
  3088. }
  3089. }
  3090.  
  3091. //check promised credits - total_value
  3092. if (($deal['owner']['type'] == "community") && $deal['total_value']) {
  3093. $promisedCredits += $deal['total_value'];
  3094. }
  3095.  
  3096. //check promised credits - affiliate fee
  3097. if ($deal['affiliate_fee']) {
  3098. $object->affiliate_fee = $deal['affiliate_fee'];
  3099. if ($affiliateId && ($affiliateId != $userId)) {
  3100. $promisedCredits += $deal['affiliate_fee'];
  3101. }
  3102. }
  3103. /*
  3104. if($promisedCredits){
  3105. if(!$modelCommunity->checkIfEnoughPromisedCreditsAreThere($promisedCredits)){
  3106. $object->errors[] = 'insufficient_community_credits_to_promise';
  3107. }
  3108. } */
  3109.  
  3110. if (count($object->errors)) {
  3111. $object->can_take = false;
  3112. }
  3113. return $object;
  3114. }
  3115.  
  3116. //checkIfUserCanTakeDeal
  3117.  
  3118. /*
  3119. * * deals - end of take and assign
  3120. */
  3121.  
  3122. /*
  3123. * * deals - take action
  3124. */
  3125.  
  3126. public function takeAction($dealId, $userId, $staffId = NULL, $communityId = NULL) {
  3127. if (!TagMongo::isValidId($dealId)) {
  3128. throw new CHttpException(404, "invalid_deal_id");
  3129. }
  3130.  
  3131. $collection = Yii::app()->edmsMongoCollection('deals_live');
  3132. $deal = $collection->findOne(array(
  3133. "deal_id" => new MongoID($dealId),
  3134. "user_id" => intval($userId)
  3135. ));
  3136.  
  3137. if ($deal) {
  3138. if ($deal['owner']['type'] == "community") {
  3139. //If the owner of the deal is a community
  3140. if ($staffId) {
  3141. //If a staff member is trying to take action
  3142. $roleDetails = CommunityUsers::getRoleOfUser($staffId, $deal['owner']['id']);
  3143. if ($roleDetails->role_type != 1) {
  3144. if (!in_array($roleDetails->role_id, $deal['roles']['redeem'])) {
  3145. throw new CHttpException(403, "permission_denied");
  3146. }
  3147. }
  3148. } else {
  3149. if ($userId != $deal['user_id'] || ($communityId == NULL && !$deal['dealinfo']['take_action'])) {
  3150. throw new CHttpException(403, "permission_denied");
  3151. }
  3152. }
  3153. } else {
  3154. //If the owner of the deal is a user
  3155. //the staffId will mean the user who created the deal
  3156. if ($staffId) {
  3157. if ($staffId != $deal['owner']['id']) {
  3158. throw new CHttpException(403, "permission_denied");
  3159. }
  3160. } else {
  3161. if ($userId != $deal['user_id'] || !$deal['take_action']) {
  3162. throw new CHttpException(403, "permission_denied");
  3163. }
  3164. }
  3165. }
  3166.  
  3167.  
  3168. if ($deal['type'] == "stamp") {
  3169. if ($deal['dealinfo']['total_stamps'] == $deal['userinfo']['current_stamps']) {
  3170. return "no_more_stamps_to_add";
  3171. }
  3172. $userinfo = $this->addStamp($deal);
  3173. $collection->update(array(
  3174. "_id" => $deal['_id']
  3175. ), array('$set' => array("userinfo" => $userinfo)));
  3176. $dealinfo['current_stamps'] = $deal['userinfo']['current_stamps'] + 1;
  3177. $dealinfo['total_stamps'] = $deal['dealinfo']['total_stamps'];
  3178. return $dealinfo;
  3179. } else {
  3180. throw new CHttpException(403, "no_action_for_this_deal");
  3181. }
  3182.  
  3183.  
  3184. if (Deals::checkIfComplete($deal)) {
  3185. if ($deal['rewardinfo']['auto_redeem']) {
  3186. $transaction = Yii::app()->db->beginTransaction();
  3187. try {
  3188. //If this deal can be auto redeemed
  3189. $this->updatePromised($deal, true);
  3190. $this->rewardUser($deal);
  3191. $this->payAffiliate($deal);
  3192. $this->moveLiveDealToHistory($deal);
  3193.  
  3194. //committing
  3195. $transaction->commit();
  3196. } catch (Exception $e) {
  3197. $transaction->rollback();
  3198. $this->response['error'] = $e->getMessage();
  3199. $this->response['status'] = 'falied';
  3200. Rest::sendResponse(403, json_encode($this->response, JSON_NUMERIC_CHECK));
  3201. }
  3202.  
  3203. return true;
  3204. } else {
  3205. //If the deal cannot be auto redeemed, set it's status as complete
  3206. //so that the staff can redeem it later
  3207. $collection->update(array(
  3208. "_id" => $deal['_id']
  3209. ), array('$set' => array("status" => 3)));
  3210. }
  3211. }
  3212.  
  3213. return true;
  3214. } else {
  3215. throw new CHttpException(403, "invalid_dealid");
  3216. }
  3217. }
  3218.  
  3219. private function addStamp($deal) {
  3220. $stamp_log = $deal['userinfo']['stamp_log'];
  3221. if ($deal['dealinfo']['limit_per_day']) {
  3222. $timestampLastday = time() - (60 * 60 * 24);
  3223. if ($stamp_log) {
  3224. $count = 0;
  3225. foreach ($stamp_log as $stamp) {
  3226. if ($stamp['timestamp'] > $timestampLastday) {
  3227. $count++;
  3228. }
  3229.  
  3230. if ($count >= $deal['dealinfo']['limit_per_day']) {
  3231. $f = 1;
  3232. break;
  3233. }
  3234. }
  3235.  
  3236. if ($f) {
  3237. throw new CHttpException(403, "stamp_limit_reached");
  3238. }
  3239. }
  3240. }
  3241. $object = new stdClass;
  3242. $object->timestamp = time();
  3243. if ($this->notes)
  3244. $object->notes = $this->notes;
  3245. $stamp_log[] = $object;
  3246.  
  3247. $deal['userinfo']['current_stamps'] = intval($deal['userinfo']['current_stamps'] + 1);
  3248. $deal['userinfo']['stamp_log'] = $stamp_log;
  3249. return $deal['userinfo'];
  3250. }
  3251.  
  3252. /*
  3253. * * deals - end of take action
  3254. */
  3255.  
  3256.  
  3257. /*
  3258. * * deals - redeem
  3259. */
  3260.  
  3261. public function redeemDeal($dealId, $dealUserId = NULL) {
  3262. if (!$dealUserId) {
  3263. $dealUserId = $this->userId;
  3264. }
  3265.  
  3266. $collection = Yii::app()->edmsMongoCollection('deals_live');
  3267. $deal = $collection->findOne(array(
  3268. "deal_id" => new MongoID($dealId),
  3269. "user_id" => intval($dealUserId)
  3270. ));
  3271.  
  3272. //check permissions
  3273. if (!$this->isPermission('redeem', $deal)) {
  3274. return false;
  3275. }
  3276.  
  3277. //check deal complete
  3278. if (!Deals::checkIfComplete($deal)) {
  3279. throw new CHttpException(403, "deal_incomplete");
  3280. }
  3281.  
  3282. $dealRedeemed = true;
  3283. $transaction = Yii::app()->db->beginTransaction();
  3284. try {
  3285. $this->updatePromised($deal, true);
  3286. $this->payAffiliate($deal);
  3287.  
  3288. if ($this->rewardUser($deal))
  3289. $this->moveLiveDealToHistory($deal, $redeem = true);
  3290. else
  3291. $dealRedeemed = false;
  3292. //committing
  3293. $transaction->commit();
  3294. } catch (Exception $e) {
  3295. $transaction->rollback();
  3296. $this->response['error'] = $e->getMessage();
  3297. $this->response['status'] = 'falied';
  3298. Rest::sendResponse(403, json_encode($this->response, JSON_NUMERIC_CHECK));
  3299. }
  3300.  
  3301. if ($dealRedeemed) {
  3302. if (($deal['type'] == 'promo') && ($deal['dealinfo']['promo_codes'])) {
  3303. $redeemer = Users::model()->findByPk($dealUserId);
  3304.  
  3305. //send promocode via email
  3306. $mail = new YiiMailer();
  3307. $mail->IsSMTP();
  3308. $mail->Host = 'smtp.gmail.com';
  3309. $mail->Port = 465;
  3310. $mail->SMTPAuth = true;
  3311. $mail->SMTPSecure = 'ssl';
  3312. $mail->Username = Yii::app()->params['adminEmail'];
  3313. $mail->Password = Yii::app()->params['adminEmailPassword'];
  3314. $mail->setView('promocodeactivate');
  3315. $mail->setData(array(
  3316. 'dealTitle' => $deal['title'],
  3317. 'description' => $deal['description']
  3318. ));
  3319. $mail->render();
  3320. $mail->From = Yii::app()->params['adminEmail'];
  3321. $mail->FromName = Yii::app()->name;
  3322. $mail->Subject = Yii::t('labels', Yii::t("labels", "Tagwild gift coupon received"));
  3323. $mail->AddAddress($redeemer->user_email);
  3324. $mail->Send();
  3325.  
  3326. return array('status' => 'success', 'type' => $deal['type'], 'title' => $deal['title'], 'description' => $deal['description'], 'promo_code' => $deal['dealinfo']['promo_codes']);
  3327. } elseif (($deal['type'] == 'load') && ($deal['share_for_reward']['amount'])) {
  3328.  
  3329. $dealowner = array('owner_type' => 1, 'owner_id' => $deal['share_for_reward']['owner_id']);
  3330.  
  3331. return array('status' => 'success', 'type' => $deal['type'], 'title' => $deal['title'], 'description' => $deal['description'], 'load_amount' => $deal['share_for_reward']['amount'], 'owner' => $dealowner);
  3332. }
  3333. return array('status' => 'success', 'type' => $deal['type'], 'title' => $deal['title'], 'description' => $deal['description']);
  3334. } else
  3335. return array('status' => 'falied');
  3336. }
  3337.  
  3338. public function rewardUser($deal) {
  3339. if ($deal['rewardinfo']['type'] == "reward" || $deal['rewardinfo']['type'] == "points") {
  3340. $rewardPoints = new RewardTransfers();
  3341. $rewardPoints->transfer_from_id = $deal['owner']['id'];
  3342. $rewardPoints->transfer_from_type = ($deal['owner']['type'] == "community") ? "2" : "1";
  3343. $rewardPoints->transfer_to_id = $deal['user_id'];
  3344. $rewardPoints->transfer_to_type = 1;
  3345. $rewardPoints->transfer_narration = 'Reward for the deal : #' . $deal['deal_id'];
  3346. $rewardPoints->transfer_amount = $deal['rewardinfo']['amount'];
  3347.  
  3348. if (!$rewardPoints->transfer()) {
  3349. //Common::pre($rewardPoints->getErrors(), true);
  3350. throw new CHttpException(403, 'reward_transfer_failed');
  3351. }
  3352. } else if ($deal['rewardinfo']['type'] == "wallet") {
  3353. $rewardWallet = new WalletTransfers;
  3354. $rewardWallet->transfer_from_id = $deal['owner']['id'];
  3355. $rewardWallet->transfer_from_type = $deal['owner']['type'];
  3356. $rewardWallet->transfer_from_wallet_id = $deal['rewardinfo']['wallet_id'];
  3357. $rewardWallet->transfer_from_amount = $deal['rewardinfo']['amount'];
  3358. $rewardWallet->transfer_to_id = $deal['user_id'];
  3359. $rewardWallet->transfer_to_type = 1;
  3360. $rewardWallet->transfer_to_wallet_id = $deal['rewardinfo']['wallet_id'];
  3361. $rewardWallet->transfer_narration = "Reward for the deal : #" . $deal['deal_id'];
  3362.  
  3363. if (!$rewardWallet->transfer()) {
  3364. //Common::pre($rewardWallet->getErrors(), true);
  3365. throw new CHttpException(403, 'reward_transfer_failed');
  3366. }
  3367. } elseif ($deal['rewardinfo']['type'] == "rolechange") {
  3368. $userRole = CommunityUsers::model()->findByAttributes(array(
  3369. "user_id" => $deal['user_id'],
  3370. "community_id" => $deal['owner']['id']
  3371. ));
  3372.  
  3373. $userRole->role_id = $deal['rewardinfo']['role_id'];
  3374. $userRole->save();
  3375. } elseif ($deal['rewardinfo']['type'] == "deal") {
  3376. //If a deal is the reward
  3377. $collection = Yii::app()->edmsMongoCollection('deals');
  3378. $newDeal = $collection->findOne(array("_id" => $deal['rewardinfo']['dealId']));
  3379.  
  3380. $liveDeal = new stdClass();
  3381. $liveDeal->deal_id = $newDeal['_id'];
  3382. $liveDeal->type = $newDeal['type'];
  3383. $liveDeal->owner = $newDeal['owner'];
  3384. $liveDeal->title = $newDeal['title'];
  3385. $liveDeal->description = $newDeal['description'];
  3386. $liveDeal->start_date = $newDeal['start_date'];
  3387. $liveDeal->end_date = $newDeal['end_date'];
  3388. $liveDeal->price = $newDeal['price'];
  3389. $liveDeal->city = $newDeal['city'];
  3390. $liveDeal->country = $newDeal['country'];
  3391. $liveDeal->visibility = $newDeal['visibility'];
  3392. $liveDeal->tags = $newDeal['tags'];
  3393. $liveDeal->dealinfo = $newDeal['dealinfo'];
  3394. $liveDeal->roles = $newDeal['roles'];
  3395. $liveDeal->rewardinfo = $newDeal['rewardinfo'];
  3396. $liveDeal->limits = $newDeal['limits'];
  3397. $liveDeal->total_value = $newDeal['total_value'];
  3398. $liveDeal->status = 1;
  3399. $liveDeal->user_id = intval($deal['user_id']);
  3400. $liveDeal->assigner_id = intval($deal['assigner_id']);
  3401.  
  3402. $user = Users::model()->findByPk($deal['user_id']);
  3403.  
  3404. if ($newDeal['type'] == "stamp") {
  3405. $userinfo = new stdClass;
  3406. $userinfo->id = intval($user->id);
  3407. $userinfo->user_firstname = $user->user_firstname;
  3408. $userinfo->user_lastname = $user->user_lastname;
  3409. $userinfo->current_stamps = intval($newDeal['dealinfo']['starting_stamps']);
  3410. $userinfo->stamp_log = array();
  3411. } else {
  3412. $userinfo = new stdClass;
  3413. $userinfo->id = intval($user->id);
  3414. $userinfo->user_firstname = $user->user_firstname;
  3415. $userinfo->user_lastname = $user->user_lastname;
  3416. }
  3417.  
  3418.  
  3419. $liveDeal->userinfo = $userinfo;
  3420.  
  3421. $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
  3422. $liveCollection->insert($liveDeal);
  3423. } elseif ($deal['share_for_reward']['type'] == "bonus") {
  3424. $fromUser = $deal['share_for_reward']['owner_id'];
  3425. $toUser = $deal['user_id'];
  3426. $amount = $deal['share_for_reward']['amount'];
  3427.  
  3428. $walletBalance = WalletBalances::model()->findByAttributes(array(
  3429. 'balance_id' => $fromUser,
  3430. 'balance_type' => 1,
  3431. 'wallet_type_id' => $this->walletId,
  3432. ));
  3433. if (!$walletBalance->checkWalletBalance($amount)) {
  3434. $subject = "Insufficient TEP balance";
  3435. $settings = array(
  3436. 'view' => 'insufficientBalance',
  3437. 'subject' => $subject
  3438. );
  3439. $data = array(
  3440. 'name' => $user->user_firstname . ' ' . $user->user_lastname,
  3441. 'user_email' => $user->user_email,
  3442. 'walletName' => 'TEP'
  3443. );
  3444.  
  3445. $mail = new TagbondMail();
  3446. $mail->sendTagbondMail($settings, $data, $response);
  3447.  
  3448. return false;
  3449. }
  3450.  
  3451. $TagEnergyPoints = new TagEnergyPoints();
  3452.  
  3453. $chargeBonus = $TagEnergyPoints->walletTransfer(intval($fromUser), 1, $deal['share_for_reward']['amount'], 'charging', $this->thisObj, 'Charged for giving gift bonus points');
  3454. if ($chargeBonus['status'] == 'success') {
  3455.  
  3456. $transfer = $TagEnergyPoints->walletTransfer(intval($toUser), 1, $deal['share_for_reward']['amount'], 'debit', $this->thisObj, 'Gift bonus points');
  3457. if ($transfer['status'] == 'success') {
  3458. return true;
  3459. } else {
  3460. return false;
  3461. }
  3462. } else {
  3463. return false;
  3464. }
  3465. }
  3466.  
  3467. return true;
  3468. }
  3469.  
  3470. public function payAffiliate($deal) {
  3471. if ($deal['affiliate_id'] && $deal['affiliate_fee']) {
  3472. $modelCreditTransfers = new CreditTransfers();
  3473. $modelCreditTransfers->transfer_from_id = $deal['owner']['id'];
  3474. $modelCreditTransfers->transfer_from_type = ($deal['owner']['type'] == "community") ? "2" : "1";
  3475. $modelCreditTransfers->transfer_to_id = $deal['affiliate_id'];
  3476. $modelCreditTransfers->transfer_to_type = 1;
  3477. $modelCreditTransfers->transfer_amount = $deal['affiliate_fee'];
  3478. $modelCreditTransfers->transfer_narration = "Affiliate Fee";
  3479.  
  3480. //Common::pre($deal, true);
  3481. $modelCreditTransfers->transferCredits();
  3482. }
  3483. }
  3484.  
  3485. public static function checkIfComplete($dealData) {
  3486. if ($dealData['type'] == "stamp") {
  3487. if ($dealData['userinfo']['current_stamps'] == $dealData['dealinfo']['total_stamps']) {
  3488. //Means the deal has finished and can be redeemed
  3489. return true;
  3490. } else {
  3491. return false;
  3492. }
  3493. } else {
  3494. return true;
  3495. }
  3496. }
  3497.  
  3498. /*
  3499. * * deals - end of redeem
  3500. */
  3501.  
  3502. /*
  3503. * * deals - list
  3504. */
  3505.  
  3506. public function searchDeals($filter = array(), $params = array()) {
  3507. $parsedDeals = array();
  3508. $query = array();
  3509. $query1 = array();
  3510. $deal_type_master_list = array();
  3511. //sorting ( by cost_per_view) descending order
  3512. $sort = array("status" => 1, "cost_per_view.amount" => -1, "end_date" => 1);
  3513.  
  3514. if ($filter['loc']) {
  3515. $location['long'] = $filter['loc']['long'];
  3516. $location['lat'] = $filter['loc']['lat'];
  3517. }
  3518. if ($this->communityId) {
  3519. $deal_type_master_list = array('coupon', 'digital', 'pointsale', 'promo', 'ticket', 'stamp', 'passport', 'catalog', 'sticker', 'food', 'jobs', 'book_spa', 'bus_reservation', 'load', 'bonus');
  3520. } else {
  3521. $deal_type_master_list = array('coupon', 'stamp', 'catalog', 'jobs', 'ticket', 'load', 'bonus');
  3522. if ($filter['type'] != 'jobs') {
  3523. //this is a custom code for :
  3524. // discard showing tagverts if, the owner have insufficient balance for cost_per_view
  3525. $query['$or'] = array(
  3526. 0 => array(
  3527. '$and' => array(
  3528. 0 => array(
  3529. 'cost_per_view.amount' => array(
  3530. '$gt' => 0
  3531. )
  3532. ),
  3533. 1 => array(
  3534. '$where' => "this.cost_per_view.amount <= this.cost_per_view.ad_balance"
  3535. )
  3536. )
  3537. ),
  3538. 1 => array(
  3539. 'cost_per_view' => null
  3540. ),
  3541. 2 => array(
  3542. 'cost_per_view' => array(
  3543. '$exists' => false
  3544. )
  3545. )
  3546. );
  3547. }
  3548. }
  3549.  
  3550. //searching deal templates
  3551. //copied from getAllDealsOfACommunity()
  3552. $collection = Yii::app()->edmsMongoCollection('deals');
  3553.  
  3554. // pagination
  3555. if (isset($this->pageOffset) && (!is_numeric($this->pageOffset) || $this->pageOffset < 0)) {
  3556. $this->pageOffset = 0;
  3557. }
  3558.  
  3559. if (isset($this->pageCount) && (!is_numeric($this->pageCount) || $this->pageCount < 0)) {
  3560. $this->pageCount = 100;
  3561. }
  3562.  
  3563. if ($filter['type']) {
  3564. if (is_array($filter['type'])) {
  3565. //add book_spa if specified in filter explicitely
  3566. if (in_array('book_spa', $filter['type']))
  3567. $deal_type_master_list[] = 'book_spa';
  3568.  
  3569. //add sticker if specified in filter explicitely
  3570. if (in_array('sticker', $filter['type']))
  3571. $deal_type_master_list[] = 'sticker';
  3572.  
  3573. //datapage exception
  3574. if (in_array('datapage', $filter['type'])) {
  3575. $deal_type_master_list[] = 'datapage';
  3576. }
  3577.  
  3578. //skip empty catalog tagverts
  3579. //if(in_array('catalog', $filter['type']))
  3580. //$query['items'] = array('$exists'=>true, '$ne'=>null, '$not'=>array('$size'=> 0));
  3581.  
  3582. foreach ($filter['type'] as $type) {
  3583. if (!in_array($type, $deal_type_master_list)) {
  3584. continue;
  3585. }
  3586. $types[] = $type;
  3587. }
  3588. if ($types)
  3589. $query['type'] = array('$in' => $types);
  3590. else
  3591. return $parsedDeals;
  3592. }
  3593. else {
  3594. //add book_spa if specified in filter explicitely
  3595. if ($filter['type'] == 'book_spa')
  3596. $deal_type_master_list[] = 'book_spa';
  3597.  
  3598. //sticker exception
  3599. if ($filter['type'] == 'sticker') {
  3600. $deal_type_master_list[] = 'sticker';
  3601. }
  3602.  
  3603. //datapage exception
  3604. if ($filter['type'] == 'datapage') {
  3605. $deal_type_master_list[] = 'datapage';
  3606. }
  3607.  
  3608. //skip empty catalog tagverts
  3609. if ($filter['type'] == 'catalog')
  3610. $query['items'] = array('$exists' => true, '$ne' => null, '$not' => array('$size' => 0));
  3611.  
  3612. if (!in_array($filter['type'], $deal_type_master_list)) {
  3613. //no displayable deals
  3614. return $parsedDeals;
  3615. } else
  3616. $query['type'] = $filter['type'];
  3617. }
  3618. }
  3619.  
  3620. if ($filter['status']) {
  3621. if ($filter['status'] == 'active') {
  3622. $query['status'] = 1;
  3623. $query["end_date"] = array('$gte' => date('Y-m-d'));
  3624. } else if ($filter['status'] == 'expired') {
  3625. $query['status'] = 2;
  3626. } else if ($filter['status'] == 'disabled') {
  3627. $query['status'] = 4;
  3628. } else {
  3629. $query['status'] = intval($filter['status']);
  3630. }
  3631. }
  3632.  
  3633. if ($filter['credit_type']) {
  3634. $query['credit_type'] = $filter['credit_type'];
  3635. }
  3636.  
  3637. if ($filter['food_type']) {
  3638. $query['food_type'] = $filter['food_type'];
  3639. }
  3640.  
  3641. if ($filter['title']) {
  3642. $query['title'] = array('$regex' => $filter['title'], '$options' => 'i');
  3643. }
  3644.  
  3645. if ($filter['city']) {
  3646. $query['city'] = array('$regex' => $filter['city'], '$options' => 'i');
  3647. }
  3648.  
  3649. if ($filter['country_id']) {
  3650. $query['country.id'] = intval($filter['country_id']);
  3651. }
  3652.  
  3653. if (is_array($filter['tags'])) {
  3654. $query['tags'] = array('$all' => $filter['tags']);
  3655. }
  3656.  
  3657. if (is_array($filter['hashtags'])) {
  3658. $query['items.hashtags'] = array('$all' => $filter['hashtags']);
  3659. }
  3660.  
  3661. //filter by owner
  3662. if ($filter['community_id']) {
  3663. $query['owner.id'] = intval($filter['community_id']);
  3664. $query['owner.type'] = 'community';
  3665.  
  3666. if ($filter['community_id'] == $this->communityId ||
  3667. CommunityUsers::isMemberOf($this->userId, $filter['community_id'])) {
  3668. $sort = array("status" => 1, "start_date" => -1);
  3669. if ($filter['visibility']) {
  3670. $query['visibility'] = $filter['visibility'];
  3671. }
  3672. } else {
  3673. $query['visibility'] = 'public';
  3674. }
  3675. } else if ($filter['role_type']) {
  3676. $filterCommunities = array(
  3677. 'role_type' => $filter['role_type'],
  3678. );
  3679. $modelCommunities = new Communities;
  3680. $modelCommunities->setIdentity($this);
  3681.  
  3682. $communities = $modelCommunities->searchCommunities($filterCommunities);
  3683. $communityIds = array();
  3684. if ($communities) {
  3685. foreach ($communities as $community) {
  3686. $communityIds[] = intval($community->id);
  3687. }
  3688. }
  3689.  
  3690. $query['owner.id'] = array('$in' => $communityIds);
  3691. $query['owner.type'] = 'community';
  3692. }
  3693. //no filter by owner
  3694. else {
  3695. $query['visibility'] = 'public';
  3696. }
  3697. $query['switch'] = array('$ne' => intval(0));
  3698. if (!$this->communityId) {
  3699. if ($location['long'] && $location['lat']) {
  3700. $long = $location['long'];
  3701. $lat = $location['lat'];
  3702. if ($filter['distance'])
  3703. $distance = $filter['distance'];
  3704. else
  3705. $distance = 2; // default 2km
  3706.  
  3707. $query["location"] = array('$near' => array(floatval($long), floatval($lat)), '$maxDistance' => floatval($distance / 111.12));
  3708.  
  3709. unset($query['$or']); // or wont work with $near geospacial
  3710. $sort = array(); //no need of sort- automatically sorting via distance
  3711. $this->pageOffset = 0; //no pagination
  3712. $this->pageCount = 100;
  3713. }
  3714. }
  3715. // search for price type = none
  3716. if ($filter['price'] == 'none') {
  3717. $query['price.type'] = 'none';
  3718. }
  3719.  
  3720. //filter by category
  3721. if ($filter['category']) {
  3722. $query['category.id'] = $filter['category'];
  3723. }
  3724.  
  3725. //filter by catalog item category
  3726. if ($filter['item_category'] > 0) {
  3727. $query['type'] = 'catalog';
  3728. $query['items.category.id'] = $filter['item_category'];
  3729. }
  3730. //$query['owner']['verified'] == 1;
  3731. // executing query
  3732. $deals = $collection->find($query)
  3733. ->skip($this->pageOffset)
  3734. ->limit($this->pageCount)
  3735. ->sort($sort);
  3736.  
  3737. // parsing the result
  3738. if ($deals) {
  3739. foreach ($deals as $deal) {
  3740. if ($deal['type']) {
  3741. if ($query["location"] && !in_array($deal['type'], $deal_type_master_list))
  3742. continue;
  3743. }
  3744. if ($filter['status'] == 'active' && $deal['type'] == 'ticket') {
  3745. if ($deal['dealinfo']['end_event_date'] && $deal['dealinfo']['end_event_date'] < date('Y-m-d'))
  3746. continue;
  3747. if ($deal['dealinfo']['event_date'] != NULL && $deal['dealinfo']['event_date'] < date('Y-m-d'))
  3748. continue;
  3749. }
  3750. $items = array();
  3751. $image = array();
  3752. $catalogImages = new CatalogImages;
  3753. if (is_array($deal['items'])) {
  3754. foreach ($deal['items'] as $item) {
  3755. if ($filter['item_category'] > 0) {
  3756. if ($item['category']['id'] != $filter['item_category'])
  3757. continue;
  3758. }
  3759. if ($filter['hashtags'] && is_array($filter['hashtags'])) {
  3760. if (empty(array_intersect($item['hashtags'], $filter['hashtags'])))
  3761. continue;
  3762. }
  3763. $item['image'] = $catalogImages->getCatalogImages($item['id']) ? $catalogImages->getCatalogImages($item['id']) : $image;
  3764. $items[] = $item;
  3765. }
  3766. $deal['items'] = $items;
  3767. }
  3768.  
  3769. $parsedDeals[] = self::formatDeal($deal, NULL, $this->communityId, $this->userId);
  3770. }
  3771. }
  3772. return $parsedDeals;
  3773. }
  3774.  
  3775. public static function getAllDealsOfAUser($userId, $status = NULL, $publicOnly = false) {
  3776. $collection = Yii::app()->edmsMongoCollection('deals_live');
  3777. if ($publicOnly) {
  3778. $query = array("user_id" => intval($userId), "owner.type" => "community", "visibility" => "public");
  3779. } else {
  3780. $query = array("user_id" => intval($userId), "owner.type" => "community");
  3781. }
  3782.  
  3783.  
  3784. if ($status) {
  3785. $query['status'] = $status;
  3786. }
  3787.  
  3788. $deals = $collection->find($query);
  3789.  
  3790. $parsedDeals = array();
  3791. if ($deals) {
  3792. foreach ($deals as $deal) {
  3793. $object = new stdClass();
  3794. $object->id = $deal['_id']->__toString();
  3795. $object->title = $deal['title'];
  3796. $object->description = $deal['description'];
  3797. $object->start_date = $deal['start_date'];
  3798. $object->end_date = $deal['end_date'];
  3799. $object->country = $deal['country'];
  3800. $object->city = $deal['city'];
  3801. $object->visibility = $deal['visibility'];
  3802.  
  3803. $object->status = self::formatStatus($deal['status']);
  3804.  
  3805.  
  3806. $parsedDeals[] = $object;
  3807. }
  3808. }
  3809. return $parsedDeals;
  3810. }
  3811.  
  3812. public function getLiveDeals($userId = NULL, $communityId = NULL, $filter = array()) {
  3813. // pagination
  3814. if (!is_numeric($this->pageCount) || $this->pageCount > 100) {
  3815. $this->pageCount = 100;
  3816. }
  3817. if (!is_numeric($this->pageOffset)) {
  3818. $this->pageOffset = 0;
  3819. }
  3820. $params = array();
  3821. $sort = array();
  3822. //$sort['priority'] = 1;
  3823. $filter['type'] = json_decode($filter['type'], true);
  3824. if (is_array($filter['type'])) {
  3825. if (in_array('catalog', $filter['type'])) {
  3826. $sort['purchase_details.order_date'] = -1;
  3827. }
  3828. $params['type'] = array('$in' => $filter['type']);
  3829. } else {
  3830. $sort['purchase_details.order_date'] = -1;
  3831. $sort['date_taken'] = -1;
  3832. $sort['taken_date'] = -1;
  3833. }
  3834.  
  3835.  
  3836. if ($communityId) {
  3837. $params["owner.id"] = intval($communityId);
  3838. $params["owner.type"] = "community";
  3839. if ($filter["priority"] == 'urgent') {
  3840. $params["priority"] = 0;
  3841. }
  3842. if ($filter["priority"] == 'noturgent') {
  3843. $params["priority"] = array('$ne' => 0);
  3844. }
  3845. }
  3846.  
  3847. if ($userId) {
  3848. $params['user_id'] = intval($userId);
  3849. }
  3850. if ($this->title) {
  3851. $params['title'] = array('$regex' => $this->title, '$options' => 'i');
  3852. }
  3853.  
  3854. //inuse and inbox
  3855. if ($this->status == 'inuse') {
  3856. $params['status'] = intval(8);
  3857. }
  3858. if ($this->status == 'inbox') {
  3859. $params['status'] = intval(9);
  3860. }
  3861. if ($this->type)
  3862. $params['type'] = $this->type;
  3863. //$params["end_date"] = array('$gte' => date('Y-m-d'));
  3864. $collection = Yii::app()->edmsMongoCollection('deals_live');
  3865. $deals = $collection->find($params)
  3866. ->skip($this->pageOffset)->limit($this->pageCount)
  3867. ->sort($sort);
  3868.  
  3869. $parsedDeals = array();
  3870. if ($deals) {
  3871. $i = 0;
  3872. foreach ($deals as $deal) {
  3873. echo $deal['purchase_details']['order_date'];
  3874. if ($deal['type'] == 'ticket') { //skip showing deprecated mongo format tickets
  3875. if (is_array($deal['purchasedTickets']['tickets']) == false)
  3876. continue;
  3877. }
  3878. //non bookmarked tagverts
  3879. if ($option == "non_bookmarked" && $deal['status'] == 7) {
  3880. continue;
  3881. }
  3882.  
  3883. $i++;
  3884. $object = new stdClass;
  3885. $object->live_id = $deal['_id']->__toString();
  3886. $object->id = $deal['deal_id']->__toString();
  3887. $object->taken_date = date("Y-m-d H:i:s", $deal['_id']->getTimestamp());
  3888. $object->title = $deal['title'];
  3889. $object->description = $deal['description'];
  3890. $object->type = $deal['type'];
  3891. $object->start_date = $deal['start_date'];
  3892. $object->end_date = $deal['end_date'];
  3893. $object->userinfo = $deal['userinfo'];
  3894. $object->dealinfo = $deal['dealinfo'];
  3895. if ($deal['method']) {
  3896. $object->method = $deal['method'];
  3897. } else {
  3898. switch ($deal['paidUsing']) {
  3899. case 'gameslotaward':
  3900. $object->method = 'won game slot';
  3901. break;
  3902. case 'none':
  3903. $object->method = 'assign';
  3904. break;
  3905. default:
  3906. $object->method = 'purchase';
  3907. break;
  3908. }
  3909. }
  3910.  
  3911. if ($deal['price'])
  3912. $object->price = $deal['price'];
  3913.  
  3914. $member_details = Communities::getMemberRoleType($communityId, $deal['userinfo']['id']);
  3915. if (count($member_details) > 0 && count($object->userinfo) > 0) {
  3916. $object->userinfo = array_merge($object->userinfo, $member_details);
  3917. }
  3918. $object->visibility = $deal['visibility'];
  3919. if (strtotime(date('Y-m-d')) > strtotime($deal['end_date']))
  3920. $object->status = self::formatStatus(2);
  3921. else
  3922. $object->status = self::formatStatus($deal['status']);
  3923.  
  3924. // ticket details
  3925. if ($deal['type'] == 'ticket') {
  3926. if ($deal['price']) {
  3927. $total_category = count($deal['price']['options']);
  3928. }
  3929.  
  3930. if ($deal['purchasedTickets']) {
  3931. $price_type = $deal['price']['type'];
  3932. if ($deal['price']['type'] == 'tPoints') {
  3933. $price_type = 'TAG Points';
  3934. } else {
  3935. $price_type = WalletTypes::getWalletName($deal['price']['wallet_id'], true);
  3936. }
  3937. if ($deal['purchasedTickets']['tickets']) {
  3938. $i = 0;
  3939. foreach ($deal['purchasedTickets']['tickets'] as $ticket) {
  3940. $index = $deal['purchasedTickets']['tickets'][$i]['index'];
  3941. $deal['purchasedTickets']['tickets'][$i]['price'] = $deal['price']['options'][$index]['price'] . " " . $price_type;
  3942. unset($deal['purchasedTickets']['tickets'][$i]['index']);
  3943. $i++;
  3944. }
  3945. }
  3946. $object->tickets = $deal['purchasedTickets'];
  3947. }
  3948. }
  3949.  
  3950. if ($deal['type'] == 'catalog') {
  3951. $catImg = new CatalogImages;
  3952. $i = 0;
  3953. if ($deal['purchase_details']) {
  3954. foreach ($deal['purchase_details'] as $purchaseditems) {
  3955. if (isset($purchaseditems['id']))
  3956. $deal['purchase_details']['items']['image'] = $catImg->getCatalogImages($purchaseditems['id']);
  3957. $i++;
  3958. }
  3959. }
  3960. $object->purchase_details = $deal['purchase_details'];
  3961. if ($deal['delivery_options'])
  3962. $object->delivery_options = $deal['delivery_options'];
  3963. }
  3964.  
  3965. if ($deal['owner']['type'] == "community") {
  3966. $community = Communities::model()->findByPk($deal['owner']['id']);
  3967. if ($community) {
  3968. $owner = new stdClass;
  3969. $owner->id = $community->id;
  3970. $owner->name = $community->community_name;
  3971. $owner->type = "community";
  3972. }
  3973. } else {
  3974. $user = Users::model()->findByPk($deal['owner']['id']);
  3975. if ($user) {
  3976. $owner = new stdClass;
  3977. $owner->id = $user->id;
  3978. $owner->name = $user->user_firstname . " " . $user->user_lastname;
  3979. $owner->type = "user";
  3980. }
  3981. }
  3982.  
  3983. $object->owner = $owner;
  3984. $object->image = SELF::getAvatar($object->id, true);
  3985. $parsedDeals[] = $object;
  3986. }
  3987. }
  3988. return $parsedDeals;
  3989. }
  3990.  
  3991. public static function getAvatar($dealId, $thumbnail = false) {
  3992. if ($thumbnail == true) {
  3993. $filePath = 'uploads/tagverts/thumbnail_1';
  3994. $baseUrl = '.s3.amazonaws.com/uploads/tagverts/thumbnail_1/';
  3995. } else {
  3996. $filePath = 'uploads/tagverts';
  3997. $baseUrl = '.s3.amazonaws.com/uploads/tagverts/';
  3998. }
  3999. $fileName = 'd_' . $dealId . '.png';
  4000. $resultS3 = Yii::app()->tamazon->isObjectExist($filePath, $fileName);
  4001. if (!$resultS3) {
  4002. $fileName = 'd_' . $dealId . '.jpg';
  4003. $resultS3 = Yii::app()->tamazon->isObjectExist($filePath, $fileName);
  4004. if (!$resultS3)
  4005. $image = sprintf('https://%s%s%s', Yii::app()->tamazon->bucketRoot, $baseUrl, 'default.png');
  4006. else
  4007. $image = sprintf('https://%s%s%s', Yii::app()->tamazon->bucketRoot, $baseUrl, $fileName);
  4008. } else
  4009. $image = sprintf('https://%s%s%s', Yii::app()->tamazon->bucketRoot, $baseUrl, $fileName);
  4010. return $image;
  4011. }
  4012.  
  4013. public static function searchLiveDeals($params) {
  4014. if (!is_numeric($params['count']) || $params['count'] > 100) {
  4015. $params['count'] = 100;
  4016. }
  4017.  
  4018. if (!is_numeric($params['offset'])) {
  4019. $params['offset'] = 0;
  4020. }
  4021.  
  4022. if ($params['deal_id']) {
  4023. $query['deal_id'] = new MongoID($params['deal_id']);
  4024. }
  4025.  
  4026.  
  4027. $collection = Yii::app()->edmsMongoCollection('deals_live');
  4028.  
  4029. if ($params['count'] && $params['offset']) {
  4030. $liveDeals = $collection->find($query)->skip($params['offset'])->limit($params['count']);
  4031. } else {
  4032. $deals = $collection->find($query);
  4033. //print_r($deals); exit;
  4034. }
  4035.  
  4036. $parsedDeals = array();
  4037. if ($deals) {
  4038. foreach ($deals as $deal) {
  4039. $object = new stdClass;
  4040. $object->live_id = $deal['_id']->__toString();
  4041. $object->id = $deal['deal_id']->__toString();
  4042. $object->type = $deal['type'];
  4043. $object->title = $deal['title'];
  4044. $object->description = $deal['description'];
  4045. $object->start_date = $deal['start_date'];
  4046. $object->end_date = $deal['end_date'];
  4047. $object->visibility = $deal['visibility'];
  4048. $object->status = self::formatStatus($deal['status']);
  4049.  
  4050. if ($deal['owner']['type'] == "community") {
  4051. $community = Communities::model()->findByPk($deal['owner']['id']);
  4052. if ($community) {
  4053. $owner = new stdClass;
  4054. $owner->id = $community->id;
  4055. $owner->name = $community->community_name;
  4056. $owner->type = "community";
  4057. }
  4058. } else {
  4059. $user = Users::model()->findByPk($deal['owner']['id']);
  4060. if ($user) {
  4061. $owner = new stdClass;
  4062. $owner->id = $user->id;
  4063. $owner->name = $user->user_firstname . " " . $user->user_lastname;
  4064. $owner->type = "user";
  4065. }
  4066. }
  4067. $object->owner = $owner;
  4068.  
  4069. $object->userinfo = $deal['userinfo'];
  4070. $object->dealinfo = $deal['dealinfo'];
  4071. $member_details = Communities::getMemberRoleType($deal['owner']['id'], $deal['userinfo']['id']);
  4072. if (count($member_details) > 0 && count($object->userinfo) > 0) {
  4073. $object->userinfo = array_merge($object->userinfo, $member_details);
  4074. }
  4075. $object->taken_date = date("Y-m-d H:i:s", $deal['_id']->getTimestamp());
  4076.  
  4077. $parsedDeals[] = $object;
  4078. }
  4079. }
  4080.  
  4081. return $parsedDeals;
  4082. }
  4083.  
  4084. public static function searchInLiveDeals($params) {
  4085. if (!is_numeric($params['count']) || $params['count'] > 100) {
  4086. $params['count'] = 100;
  4087. }
  4088.  
  4089. if (!is_numeric($params['offset'])) {
  4090. $params['offset'] = 0;
  4091. }
  4092.  
  4093. if ($params['id']) {
  4094. $query['_id'] = new MongoID($params['id']);
  4095. }
  4096.  
  4097. if ($params['user_id']) {
  4098. $query['user_id'] = intval($params['user_id']);
  4099. }
  4100.  
  4101. if ($params['owner_id']) {
  4102. $query['owner.id'] = intval($params['owner_id']);
  4103. }
  4104.  
  4105. $collection = Yii::app()->edmsMongoCollection('deals_live');
  4106.  
  4107. if ($params['count'] && $params['offset']) {
  4108. $liveDeals = $collection->find($query)->skip($params['offset'])->limit($params['count']);
  4109. } else {
  4110. $deals = $collection->find($query);
  4111. //print_r($deals); exit;
  4112. }
  4113.  
  4114. $parsedDeals = array();
  4115. if ($deals) {
  4116. foreach ($deals as $deal) {
  4117. $object = new stdClass;
  4118. $object->live_id = $deal['_id']->__toString();
  4119. $object->id = $deal['deal_id']->__toString();
  4120. $object->type = $deal['type'];
  4121. $object->title = $deal['title'];
  4122. $object->description = $deal['description'];
  4123. $object->start_date = $deal['start_date'];
  4124. $object->end_date = $deal['end_date'];
  4125. $object->visibility = $deal['visibility'];
  4126. $object->status = self::formatStatus($deal['status']);
  4127. // ticket details
  4128. if ($deal['type'] == 'ticket') {
  4129. if ($deal['price']) {
  4130. $total_category = count($deal['price']['options']);
  4131. }
  4132.  
  4133. if ($deal['purchasedTickets']) {
  4134. $price_type = $deal['price']['type'];
  4135. if ($deal['price']['type'] == 'tPoints') {
  4136. $price_type = 'TAG Points';
  4137. } else {
  4138. $price_type = WalletTypes::getWalletName($deal['price']['wallet_id'], true);
  4139. }
  4140. if ($deal['purchasedTickets']['tickets']) {
  4141. $i = 0;
  4142. foreach ($deal['purchasedTickets']['tickets'] as $ticket) {
  4143. $index = $deal['purchasedTickets']['tickets'][$i]['index'];
  4144. $deal['purchasedTickets']['tickets'][$i]['price'] = $deal['price']['options'][$index]['price'] . " " . $price_type;
  4145. unset($deal['purchasedTickets']['tickets'][$i]['index']);
  4146. $i++;
  4147. }
  4148. }
  4149. $object->tickets = $deal['purchasedTickets'];
  4150. }
  4151. }
  4152. if ($deal['owner']['type'] == "community") {
  4153. $community = Communities::model()->findByPk($deal['owner']['id']);
  4154. if ($community) {
  4155. $owner = new stdClass;
  4156. $owner->id = $community->id;
  4157. $owner->name = $community->community_name;
  4158. $owner->type = "community";
  4159. }
  4160. } else {
  4161. $user = Users::model()->findByPk($deal['owner']['id']);
  4162. if ($user) {
  4163. $owner = new stdClass;
  4164. $owner->id = $user->id;
  4165. $owner->name = $user->user_firstname . " " . $user->user_lastname;
  4166. $owner->type = "user";
  4167. }
  4168. }
  4169. $object->owner = $owner;
  4170.  
  4171. $object->userinfo = $deal['userinfo'];
  4172. $object->dealinfo = $deal['dealinfo'];
  4173. $object->rewardinfo = $deal['rewardinfo'];
  4174. $member_details = Communities::getMemberRoleType($deal['owner']['id'], $deal['userinfo']['id']);
  4175. if (count($member_details) > 0 && count($object->userinfo) > 0) {
  4176. $object->userinfo = array_merge($object->userinfo, $member_details);
  4177. }
  4178. $object->taken_date = date("Y-m-d H:i:s", $deal['_id']->getTimestamp());
  4179.  
  4180. $parsedDeals[] = $object;
  4181. }
  4182. }
  4183.  
  4184. return $parsedDeals;
  4185. }
  4186.  
  4187. public static function getDealsOfAllCommunities($params) {
  4188. $communities = $params['userObj']->getCommunitiesUserIsMemberOf();
  4189. $communityIds = array();
  4190.  
  4191. if ($communities) {
  4192. foreach ($communities as $community) {
  4193. $communityIds[] = intval($community['community_id']);
  4194. }
  4195. }
  4196.  
  4197. if (!is_numeric($params['count']) || $params['count'] > 100) {
  4198. $params['count'] = 100;
  4199. }
  4200.  
  4201. if (!is_numeric($params['offset'])) {
  4202. $params['offset'] = 0;
  4203. }
  4204.  
  4205. $query['owner.id'] = array('$in' => $communityIds);
  4206. $query['owner.type'] = "community";
  4207. $query['status'] = 1;
  4208.  
  4209. //search
  4210. if ($params['title']) {
  4211. $query['title'] = array('$regex' => $params['title'], '$options' => 'i');
  4212. }
  4213.  
  4214. $collection = Yii::app()->edmsMongoCollection('deals');
  4215. $deals = $collection->find($query)->skip($params['offset'])->limit($params['count']);
  4216.  
  4217. $parsedDeals = array();
  4218. if ($deals) {
  4219. foreach ($deals as $deal) {
  4220. $parsedDeals[] = self::formatDeal($deal);
  4221. }
  4222. }
  4223. return $parsedDeals;
  4224. }
  4225.  
  4226. /*
  4227. * * deals - end of list
  4228. */
  4229.  
  4230. /*
  4231. * * deals - details
  4232. */
  4233.  
  4234. public function getDealDetails($dealId, $isStaff = false, $affiliateId = NULL) {
  4235. $collection = Yii::app()->edmsMongoCollection('deals');
  4236. $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
  4237. $update = false;
  4238. if ($isStaff) {
  4239. if ($this->communityId) {
  4240. $deal = $collection->findOne(array(
  4241. "_id" => new MongoID($dealId),
  4242. "owner.id" => intval($this->communityId),
  4243. "owner.type" => "community"
  4244. ));
  4245.  
  4246. $role = CommunityUsers::getRoleOfUser($this->userId, $this->communityId);
  4247. } else {
  4248. //future development
  4249. $deal = $collection->findOne(array(
  4250. "_id" => new MongoID($dealId),
  4251. "owner.id" => intval($this->userId),
  4252. "owner.type" => "community"
  4253. ));
  4254. }
  4255. } else {
  4256. $deal = $collection->findOne(array(
  4257. "_id" => new MongoID($dealId),
  4258. ));
  4259. //check whether the user is permitted view the details
  4260. $views = array();
  4261. if ($views = $deal['roles']['view']) {
  4262. if (sizeof($views) > 0) {
  4263. $role_id = CommunityUsers::getRoleOfUser($this->userId, $deal['owner']['id'])->role_id;
  4264. if (!in_array($role_id, $views)) {
  4265. throw new CHttpException(403, "permission_denied");
  4266. }
  4267. }
  4268. }
  4269. }
  4270.  
  4271. if ($deal) {
  4272. if (CommunityUsers::isStaffOf($this->userId, $deal['owner']['id']))
  4273. $isStaff = true;
  4274. $object = self::formatDeal($deal, $isStaff);
  4275.  
  4276. if ($isStaff) {
  4277. $object->can_assign = false;
  4278. if ($deal['status'] == 1 &&
  4279. ( ($role->role_type == 1) ||
  4280. (in_array($role->role_id, $deal['roles']['assign'])) )) {
  4281. $object->can_assign = true;
  4282. }
  4283.  
  4284. $object->live_deals_count = $liveCollection->find(array(
  4285. "deal_id" => new MongoID($dealId)
  4286. ))->count();
  4287. } else {
  4288. //check for cost_per_view. if exists, and if user not visited
  4289. //earlier then deduct cost_per_view from merchants account and add user_id in deal_info
  4290. $liveDeal = $liveCollection->findOne(array(
  4291. "deal_id" => new MongoID($dealId),
  4292. "user_id" => intval($this->userId)
  4293. ));
  4294. if ($deal['cost_per_view']['amount'] > 0) {
  4295. if (!is_array($deal['dealinfo']['visitors'])) {
  4296. $deal['dealinfo']['visitors'] = array();
  4297. }
  4298. if (!in_array($this->userId, $deal['dealinfo']['visitors']) && !$liveDeal) {
  4299.  
  4300. if ($deal['cost_per_view']['amount'] > 0 && $deal['cost_per_view']['ad_balance'] < $deal['cost_per_view']['amount'])
  4301. throw new CHttpException(403, "tagvert_no_longer_valid");
  4302.  
  4303. //deduct cost_per_view from ad_balance
  4304. $update = true;
  4305. $ad_balance = $deal['cost_per_view']['ad_balance'] - $deal['cost_per_view']['amount'];
  4306. $ad_balance = $ad_balance > 0 ? $ad_balance : 0;
  4307. $updateArray = array("cost_per_view.ad_balance" => $ad_balance);
  4308. //add switch to 0 if balance becomes 0
  4309. if ($ad_balance == 0 || $ad_balance < $deal['cost_per_view']['amount']) {
  4310. $updateArray['switch'] = 0;
  4311. }
  4312. }
  4313. }
  4314.  
  4315.  
  4316. if ($liveDeal) {
  4317. $object->userinfo = $liveDeal['userinfo'];
  4318. $object->userinfo['status'] = self::formatStatus($liveDeal['status']);
  4319. $object->userinfo['taken_date'] = date("Y-m-d H:i:s", $liveDeal['_id']->getTimestamp());
  4320.  
  4321. //can take_action (add stamp)
  4322. if ($liveDeal['type'] == "stamp") {
  4323. $object->can_take_action = false;
  4324.  
  4325. if (($liveDeal['status'] == 1) && ($liveDeal['dealinfo']['take_action'])) {
  4326. $object->can_take_action = true;
  4327. }
  4328. }
  4329.  
  4330. //can redeem
  4331. $object->can_redeem = false;
  4332. if (($liveDeal['status'] == 3) && ($liveDeal['rewardinfo']['self_redeem'])) {
  4333. $object->can_redeem = true;
  4334. }
  4335.  
  4336. if ($liveDeal['type'] == "ticket") {
  4337. if ($liveDeal['purchasedTickets'])
  4338. $object->purchasedTickets = $liveDeal['purchasedTickets'];
  4339. }
  4340. }
  4341. else {
  4342. $object->take = Deals::checkIfUserCanTakeDeal($deal, $this->userId, $affiliateId);
  4343. }
  4344. }
  4345. $object->user_deal_details = $this->getCurrentDealStatus($dealId, $affiliateId);
  4346. //update ad balance if any (cost_per_view)
  4347. if ($update) {
  4348. $deal['dealinfo']['visitors'][] = $this->userId;
  4349. $updateArray['dealinfo']['visitors'] = $deal['dealinfo']['visitors'];
  4350.  
  4351. $collection->update(
  4352. array("_id" => new MongoID($dealId)), array('$set' => $updateArray)
  4353. );
  4354. }
  4355. return $object;
  4356. } else {
  4357. throw new CHttpException(403, "invalid_dealid");
  4358. }
  4359. }
  4360.  
  4361. public function getLiveDealDetails($dealId = NULL, $dealUserId = NULL) {
  4362. if (!$dealId) {
  4363. $dealId = $this->dealId;
  4364. }
  4365.  
  4366. if (!$dealUserId) {
  4367. $dealUserId = $this->userId;
  4368. }
  4369. $roleDetails = CommunityUsers::getRoleOfUser($dealUserId, $this->communityId);
  4370.  
  4371. $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
  4372.  
  4373. $liveDeal = $liveCollection->findOne(array(
  4374. "deal_id" => new MongoID($dealId),
  4375. "user_id" => intval($dealUserId)
  4376. ));
  4377.  
  4378.  
  4379. if ($liveDeal) {
  4380. $object = new stdClass;
  4381. $object->deal_id = $liveDeal['deal_id']->__toString();
  4382. $object->userinfo = $liveDeal['userinfo'];
  4383. $object->dealinfo = $liveDeal['dealinfo'];
  4384. $object->roles = $liveDeal['roles'];
  4385. if (strtotime(date('Y-m-d')) > strtotime($liveDeal['end_date']))
  4386. $object->status = self::formatStatus(2);
  4387. else
  4388. $object->status = self::formatStatus($liveDeal['status']);
  4389.  
  4390. $object->userinfo['status'] = self::formatStatus($liveDeal['status']);
  4391.  
  4392. $object->userinfo['taken_date'] = date("Y-m-d H:i:s", $liveDeal['_id']->getTimestamp());
  4393.  
  4394. //can take action (add stamp)
  4395. if ($liveDeal['type'] == "stamp") {
  4396. $object->can_take_action = false;
  4397.  
  4398. if ($liveDeal['status'] == 1) {
  4399. if ($roleDetails->role_type == 1) {
  4400. //if owner
  4401. $object->can_take_action = true;
  4402. } else if ($roleDetails->role_type == 2) {
  4403. //If a staff member is trying to take action
  4404. if (in_array($roleDetails->role_id, $liveDeal['roles']['redeem'])) {
  4405. $object->can_take_action = true;
  4406. }
  4407. } else {
  4408. //if member
  4409. if ($liveDeal['dealinfo']['take_action']) {
  4410. $object->can_take_action = true;
  4411. }
  4412. }
  4413. }
  4414. }
  4415.  
  4416. //show ticket and transaction details
  4417. if ($liveDeal['type'] == "ticket") {
  4418. if ($liveDeal['price']) {
  4419. $object->price = $liveDeal['price'];
  4420. }
  4421. if ($liveDeal['purchasedTickets']) {
  4422. $object->purchasedTickets = $liveDeal['purchasedTickets'];
  4423. }
  4424. if ($liveDeal['scanCount']) {
  4425. $object->scanCount = $liveDeal['scanCount'];
  4426. }
  4427. if ($liveDeal['scanSchedule']) {
  4428. $object->scanSchedule = $liveDeal['scanSchedule'];
  4429. }
  4430. }
  4431.  
  4432. if ($liveDeal['price']) {
  4433. $object->price = $liveDeal['price'];
  4434. }
  4435.  
  4436. $object->owner = $liveDeal['owner'];
  4437. //can redeem
  4438. $object->can_redeem = false;
  4439. if ($liveDeal['status'] == 3) {
  4440. if ($roleDetails->role_type == 1) {
  4441. //if owner
  4442. $object->can_redeem = true;
  4443. } else if ($roleDetails->role_type == 2) {
  4444. //if staff
  4445. if (in_array($roleDetails->role_id, $liveDeal['roles']['redeem'])) {
  4446. $object->can_redeem = true;
  4447. }
  4448. } else {
  4449. //if member
  4450. if ($liveDeal['rewardinfo']['self_redeem']) {
  4451. $object->can_redeem = true;
  4452. }
  4453. }
  4454. }
  4455.  
  4456. return $object;
  4457. } else {
  4458. return false;
  4459. }
  4460. }
  4461.  
  4462. /*
  4463. * * deals - end of details
  4464. */
  4465.  
  4466. /*
  4467. * * deals - sub functions
  4468. */
  4469.  
  4470. //live deal info of a user: for updates
  4471. public static function liveDealInfo($dealId, $userId) {
  4472. $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
  4473. $dealDetails = $liveCollection->findOne(array("deal_id" => new MongoID($dealId), "user_id" => intval($userId)));
  4474.  
  4475. if ($dealDetails) {
  4476.  
  4477. $object = new stdClass;
  4478. $object->_id = $dealDetails['_id'];
  4479. $object->deal_id = $dealDetails['deal_id'];
  4480. $object->type = $dealDetails['type'];
  4481. $object->status = $dealDetails['status'];
  4482. $object->title = $dealDetails['title'];
  4483. $object->description = $dealDetails['description'];
  4484. $object->hiddenDescription = $dealDetails['hiddenDescription'];
  4485. $object->town = $dealDetails['town'];
  4486. $object->city = $dealDetails['city'];
  4487. $object->zipCode = $dealDetails['zipCode'];
  4488. $object->country = $dealDetails['country'];
  4489. $object->tags = $dealDetails['tags'];
  4490. $object->auto = $dealDetails['auto'];
  4491. $object->visibility = $dealDetails['visibility'];
  4492. $object->dealinfo = $dealDetails['dealinfo'];
  4493. $object->owner = $dealDetails['owner'];
  4494. $object->start_date = $dealDetails['start_date'];
  4495. $object->end_date = $dealDetails['end_date'];
  4496. $object->total_value = $dealDetails['total_value'];
  4497. $object->credit_type = $dealDetails['credit_type'];
  4498. $object->date_taken = $dealDetails['date_taken'];
  4499. $object->date_redeemed = $dealDetails['date_redeemed'];
  4500. $object->module = $dealDetails['module'];
  4501. $object->limits = $dealDetails['limits'];
  4502. $object->roles = $dealDetails['roles'];
  4503. $object->user_id = $dealDetails['user_id'];
  4504. $object->userinfo = $dealDetails['userinfo'];
  4505.  
  4506. if ($dealDetails['scanCount']) {
  4507. $object->scanCount = $dealDetails['scanCount'];
  4508. }
  4509. if ($dealDetails['scanSchedule']) {
  4510. $object->scanSchedule = $dealDetails['scanSchedule'];
  4511. }
  4512. if ($dealDetails['pickupAddress']) {
  4513. $object->pickUpAddress = $dealDetails['pickupAddress'];
  4514. }
  4515. if ($dealDetails['methodOfPayment']) {
  4516. $object->methodOfPayment = $dealDetails['methodOfPayment'];
  4517. }
  4518. if ($dealDetails['assigner_id']) {
  4519. $object->assigner_id = $dealDetails['assigner_id'];
  4520. }
  4521. if ($dealDetails['price']) {
  4522. $object->price = $dealDetails['price'];
  4523. }
  4524. if ($dealDetails['affiliate_fee']) {
  4525. $object->affiliate_fee = $dealDetails['affiliate_fee'];
  4526. }
  4527. if ($dealDetails['rewardinfo']) {
  4528. $object->rewardinfo = $dealDetails['rewardinfo'];
  4529. }
  4530. if ($dealDetails['purchasedTickets']) {
  4531. $object->purchasedTickets = $dealDetails['purchasedTickets'];
  4532. }
  4533. if ($dealDetails['affiliate_info']) {
  4534. $object->affiliate_info = $dealDetails['affiliate_info'];
  4535. }
  4536. if ($dealDetails['type'] == "ticket" && $dealDetails['dealinfo']['ticket_type'] == 2) {
  4537. $object->rsvp = $dealDetails['rsvp'];
  4538. }
  4539.  
  4540. return $object;
  4541. }
  4542. }
  4543.  
  4544. //deal info: for various updates
  4545. public static function dealInfo($dealId) {
  4546. $collection = Yii::app()->edmsMongoCollection('deals');
  4547. $dealDetails = $collection->findOne(array("_id" => new MongoID($dealId)));
  4548. if ($dealDetails) {
  4549. if ($dealDetails['dealinfo']['event_type']) {
  4550. //expired deals
  4551. if ($dealDetails['status'] != 4 && $dealDetails['status'] != 5 && $dealDetails['status'] != 6) {
  4552. $event_date = ($dealDetails['dealinfo']['event_type'] == 1) ? $dealDetails['dealinfo']['event_date'] : $dealDetails['dealinfo']['end_event_date'];
  4553. if (strtotime($event_date) < strtotime(date('Y-m-d'))) {
  4554. $collection->update(
  4555. array("_id" => new MongoID($dealId)), array('$set' => array("status" => 2))
  4556. );
  4557. }
  4558. }
  4559. }
  4560.  
  4561.  
  4562. $dealDetails = $collection->findOne(array("_id" => new MongoID($dealId)));
  4563.  
  4564. $object = new stdClass;
  4565.  
  4566. $object->id = $dealId;
  4567. $object->status = $dealDetails['status'];
  4568. $object->type = $dealDetails['type'];
  4569. $object->title = $dealDetails['title'];
  4570. $object->description = $dealDetails['description'];
  4571. $object->hiddenDescription = $dealDetails['hiddenDescription'];
  4572. $object->town = $dealDetails['town'];
  4573. $object->city = $dealDetails['city'];
  4574. $object->zipCode = $dealDetails['zipCode'];
  4575. $object->country = $dealDetails['country'];
  4576. $object->tags = $dealDetails['tags'];
  4577. $object->auto = $dealDetails['auto'];
  4578. $object->visibility = $dealDetails['visibility'];
  4579. $object->dealinfo = $dealDetails['dealinfo'];
  4580. $object->owner = $dealDetails['owner'];
  4581. $object->start_date = $dealDetails['start_date'];
  4582. $object->end_date = $dealDetails['end_date'];
  4583. $object->total_value = $dealDetails['total_value'];
  4584. $object->credit_type = $dealDetails['credit_type'];
  4585. $object->module = $dealDetails['module'];
  4586. $object->limits = $dealDetails['limits'];
  4587. $object->roles = $dealDetails['roles'];
  4588.  
  4589.  
  4590. $tracker = ($dealDetails['tracker']) ? $dealDetails['tracker'] : uniqid() . rand(10 * 45, 100 * 98);
  4591.  
  4592. if (!$dealDetails['tracker']) {
  4593. $collection->update(
  4594. array("_id" => new MongoID($dealId),), array('$set' => array("tracker" => $tracker))
  4595. );
  4596. }
  4597.  
  4598. $object->tracker = $tracker;
  4599.  
  4600. if ($dealDetails['reportDeactivated'])
  4601. $object->reportDeactivated = $dealDetails['reportDeactivated'];
  4602.  
  4603. if ($dealDetails['methodOfPayment'])
  4604. $object->methodOfPayment = $dealDetails['methodOfPayment'];
  4605.  
  4606. if ($dealDetails['digitalDelivery'])
  4607. $object->digitalDelivery = $dealDetails['digitalDelivery'];
  4608.  
  4609. if ($dealDetails['pickUpAddress'])
  4610. $object->pickUpAddress = $dealDetails['pickUpAddress'];
  4611.  
  4612. if ($dealDetails['price'])
  4613. $object->price = $dealDetails['price'];
  4614.  
  4615. if ($dealDetails['multiDelivery'])
  4616. $object->multiDelivery = $dealDetails['multiDelivery'];
  4617.  
  4618. if ($dealDetails['referralTypeOption'])
  4619. $object->referralTypeOption = $dealDetails['referralTypeOption'];
  4620.  
  4621. if ($dealDetails['affiliate_fee'])
  4622. $object->affiliate_fee = $dealDetails['affiliate_fee'];
  4623.  
  4624. if ($dealDetails['rewardinfo'])
  4625. $object->rewardinfo = $dealDetails['rewardinfo'];
  4626.  
  4627. if ($dealDetails['gallery'])
  4628. $object->gallery = $dealDetails['gallery'];
  4629.  
  4630. if ($dealDetails['sharedVisitCount'])
  4631. $object->sharedVisitCount = $dealDetails['sharedVisitCount'];
  4632.  
  4633. if ($dealDetails['sharedBookmarkCount'])
  4634. $object->sharedBookmarkCount = $dealDetails['sharedBookmarkCount'];
  4635.  
  4636. if ($dealDetails['sharedDiscardCount'])
  4637. $object->sharedDiscardCount = $dealDetails['sharedDiscardCount'];
  4638.  
  4639. if ($dealDetails['sharedTakeCount'])
  4640. $object->sharedTakeCount = $dealDetails['sharedTakeCount'];
  4641.  
  4642. if ($dealDetails['sharedRedeemCount'])
  4643. $object->sharedRedeemCount = $dealDetails['sharedRedeemCount'];
  4644.  
  4645. if ($dealDetails['sharedReferral'])
  4646. $object->sharedReferral = $dealDetails['sharedReferral'];
  4647.  
  4648. if ($dealDetails['bankDeposit'])
  4649. $object->bankDeposit = $dealDetails['bankDeposit'];
  4650.  
  4651. if ($dealDetails['sharedSales'])
  4652. $object->sharedSales = $dealDetails['sharedSales'];
  4653.  
  4654. if ($dealDetails['scanCount'])
  4655. $object->scanCount = $dealDetails['scanCount'];
  4656.  
  4657. if ($dealDetails['scanSchedule'])
  4658. $object->scanSchedule = $dealDetails['scanSchedule'];
  4659.  
  4660. return $object;
  4661. }
  4662. }
  4663.  
  4664. public static function getValueOfDeal($dealId = NULL, $deal = NULL) {
  4665. $collection = Yii::app()->edmsMongoCollection('deals');
  4666. if (!$deal) {
  4667. $deal = $collection->findOne(array("_id" => new MongoID($dealId)));
  4668. }
  4669.  
  4670. if (!$deal) {
  4671. return false;
  4672. } else {
  4673. $result = array(
  4674. 'amount' => 0.00,
  4675. 'type' => '',
  4676. );
  4677. if ($deal['rewardinfo']['type'] == 'reward' || $deal['rewardinfo']['type'] == 'points') {
  4678. $result['type'] = 'reward';
  4679. $result['amount'] = $data['rewardinfo']['amount'];
  4680. } else if ($deal['rewardinfo']['type'] == 'wallet') {
  4681. $result['type'] = 'wallet';
  4682. $result['amount'] = $data['rewardinfo']['amount'];
  4683. }
  4684.  
  4685. $result;
  4686. }
  4687. }
  4688.  
  4689. public static function countAllDealsOfACommunity($communityId) {
  4690. $collection = Yii::app()->edmsMongoCollection('deals');
  4691. $dealCount = $collection->find(array("owner.id" => intval($communityId), "owner.type" => "community", "status" => intval(1)))->count();
  4692.  
  4693. return $dealCount;
  4694. }
  4695.  
  4696. public static function countAllDealsOfAUser($userId) {
  4697. $collection = Yii::app()->edmsMongoCollection('deals');
  4698. $dealCount = $collection->find(array("owner.id" => intval($userId), "owner.type" => "user"))->count();
  4699. return $dealCount;
  4700. }
  4701.  
  4702. public static function countTimesTaken($dealId, $includeHistory = false, $userId = NULL) {
  4703. $collection = Yii::app()->edmsMongoCollection('deals_live');
  4704. $historyCollection = Yii::app()->edmsMongoCollection('deals_history');
  4705.  
  4706. if ($userId) {
  4707. $dealCount = $collection->find(array('deal_id' => new MongoID($dealId), 'user_id' => intval($userId)))->count();
  4708.  
  4709. if ($includeHistory) {
  4710. $dealCount += $historyCollection->find(array('deal_id' => new MongoID($dealId), 'user_id' => intval($userId)))->count();
  4711. }
  4712. } else {
  4713. $dealCount = $collection->find(array('deal_id' => new MongoID($dealId)))->count();
  4714.  
  4715. if ($includeHistory) {
  4716. $dealCount += $historyCollection->find(array('deal_id' => new MongoID($dealId)))->count();
  4717. }
  4718. }
  4719.  
  4720. return $dealCount;
  4721. }
  4722.  
  4723. public static function countTimesTakenPerDay($dealId) {
  4724. $collection = Yii::app()->edmsMongoCollection('deals_live');
  4725. $historyCollection = Yii::app()->edmsMongoCollection('deals_history');
  4726.  
  4727. $dealCount = $collection->find(array("deal_id" => new MongoID($dealId), 'date_taken' => date('Y-m-d')))->count();
  4728.  
  4729. if ($includeHistory) {
  4730. $dealCount += $historyCollection->find(array('deal_id' => new MongoID($dealId), 'date_taken' => date('Y-m-d')))->count();
  4731. }
  4732. return $dealCount;
  4733. }
  4734.  
  4735. public function validateMongoId() {
  4736. $regex = '/^[0-9a-z]{24}$/';
  4737. if (preg_match($regex, $this->dealId)) {
  4738. return true;
  4739. }
  4740. return false;
  4741. }
  4742.  
  4743. public function updatePromised($deal, $minus = false) {
  4744.  
  4745. //convert object to array
  4746. if (is_object($deal)) {
  4747. $deal = (array) $deal;
  4748. }
  4749.  
  4750. if ($deal['owner']['id']) {
  4751. $comunityid = $deal['owner']['id'];
  4752. } else if ($this->communityId) {
  4753. $comunityid = $this->communityId;
  4754. }
  4755.  
  4756. //fetching for affiliate
  4757. $query = array();
  4758. $balanceForAffiliate = NULL;
  4759.  
  4760. if ($deal['affiliate_fee'] && is_array($deal['affiliate_fee'])) {
  4761. if ($deal['affiliate_fee']['type'] == 'reward' && $deal['affiliate_fee']['amount'] && $deal['affiliate_fee']['wallet_id']) {
  4762. //fetching query
  4763. $query['balance_id'] = $deal['owner']['id'];
  4764. if ($deal['owner']['type'] == 'community') {
  4765. $query['balance_type'] = 2;
  4766. } else if ($deal['owner']['type'] == 'user') {
  4767. $query['balance_type'] = 1;
  4768. } else {
  4769. $this->internalError('pay affiliate fee', NULL, 'affiliate');
  4770. }
  4771. $query['wallet_type_id'] = $deal['affiliate_fee']['wallet_id'];
  4772.  
  4773. //fetching balance
  4774. $balanceForAffiliate = WalletBalances::model()->findByAttributes($query);
  4775.  
  4776. //validating
  4777. if (!$minus) {
  4778. if (!$balanceForAffiliate) {
  4779. throw new CHttpException(403, "insufficient_balance");
  4780. }
  4781.  
  4782. $balanceForAffiliate->balance_promised += $deal['affiliate_fee']['amount'];
  4783.  
  4784. if (!$balanceForAffiliate->validate()) {
  4785. throw new CHttpException(403, "insufficient_balance");
  4786. }
  4787. } else {
  4788. if (!$balanceForAffiliate) {
  4789. $this->internalError('pay affiliate fee', $balanceForAffiliate, 'affiliate');
  4790. }
  4791.  
  4792. $balanceForAffiliate->balance_promised -= $deal['affiliate_fee']['amount'];
  4793.  
  4794. if (!$balanceForAffiliate->validate()) {
  4795. $this->internalError('pay affiliate fee', $balanceForAffiliate, 'affiliate');
  4796. }
  4797. }
  4798. }
  4799. /* if($deal['affiliate_fee']['type'] == 'reward'
  4800. && $deal['affiliate_fee']['amount']){
  4801.  
  4802. $balanceForAffiliate = Communities::model()->findByPk($comunityid);
  4803.  
  4804. if(!$minus){
  4805. if(($balanceForAffiliate->community_credits-$balanceForAffiliate->community_promised_credits)<$deal['affiliate_fee']['amount']){
  4806. throw new CHttpException(403,"insufficient_balance");
  4807. }
  4808. else{
  4809. $balanceForAffiliate->community_promised_credits += $deal['affiliate_fee']['amount'];
  4810. }
  4811. }
  4812. else{
  4813. $balanceForAffiliate->community_promised_credits -= $deal['affiliate_fee']['amount'];
  4814. }
  4815. } */
  4816. }
  4817.  
  4818. //fetching for reward
  4819. $query = array();
  4820. $balanceForReward = NULL;
  4821. if ($deal['rewardinfo']['type'] == 'wallet' && $deal['rewardinfo']['amount'] && $deal['rewardinfo']['wallet_id']) {
  4822. //fetching query
  4823. $query = array();
  4824. $query['balance_id'] = $deal['owner']['id'];
  4825. if ($deal['owner']['type'] == 'community') {
  4826. $query['balance_type'] = 2;
  4827. } else if ($deal['owner']['type'] == 'user') {
  4828. $query['balance_type'] = 1;
  4829. } else {
  4830. $this->internalError('reward using wallet', NULL, 'reward');
  4831. }
  4832. $query['wallet_type_id'] = $deal['rewardinfo']['wallet_id'];
  4833.  
  4834. //fetching balance
  4835. if ($balanceForAffiliate && $balanceForAffiliate->wallet_type_id == $query['wallet_type_id']) {
  4836. $balanceForReward = $balanceForAffiliate;
  4837. } else {
  4838. $balanceForReward = WalletBalances::model()->findByAttributes($query);
  4839. }
  4840.  
  4841. //validating
  4842. if (!$minus) {
  4843. if (!$balanceForReward) {
  4844. throw new CHttpException(403, "insufficient_balance");
  4845. }
  4846.  
  4847. $balanceForReward->balance_promised += $deal['rewardinfo']['amount'];
  4848.  
  4849. if (!$balanceForReward->validate()) {
  4850. throw new CHttpException(403, "insufficient_balance");
  4851. }
  4852. } else {
  4853. if (!$balanceForReward) {
  4854. $this->internalError('reward using wallet', $balanceForReward, 'reward');
  4855. }
  4856.  
  4857. $balanceForReward->balance_promised -= $deal['rewardinfo']['amount'];
  4858.  
  4859. if (!$balanceForReward->validate()) {
  4860. $this->internalError('reward using wallet', $balanceForReward, 'reward');
  4861. }
  4862. }
  4863.  
  4864. //Common::pre($deal['rewardinfo'], true);
  4865. } else if ($deal['rewardinfo']['type'] == 'reward' && $deal['rewardinfo']['amount']) {
  4866. $balanceForReward = Communities::model()->findByPk($comunityid);
  4867.  
  4868. if (!$minus) {
  4869. if (($balanceForReward->community_credits - $balanceForReward->community_promised_credits) < $deal['rewardinfo']['amount']) {
  4870. throw new CHttpException(403, "insufficient_balance");
  4871. } else {
  4872. $balanceForReward->community_promised_credits += $deal['rewardinfo']['amount'];
  4873. }
  4874. } else {
  4875. $balanceForReward->community_promised_credits -= $deal['rewardinfo']['amount'];
  4876. }
  4877. }
  4878. //committing
  4879. if ($balanceForAffiliate) {
  4880. $balanceForAffiliate->save();
  4881. }
  4882.  
  4883. if ($balanceForReward) {
  4884. if ($deal['rewardinfo']['type'] == 'wallet') {
  4885. if ($balanceForAffiliate &&
  4886. ($balanceForAffiliate->wallet_type_id == $balanceForReward->wallet_type_id)) {
  4887. //return true;
  4888. } else {
  4889. $balanceForReward->save();
  4890. }
  4891. } else if ($deal['rewardinfo']['type'] == 'reward') {
  4892. $balanceForReward->save();
  4893. }
  4894. }
  4895.  
  4896. //Common::pre($deal, true);
  4897. return true;
  4898. }
  4899.  
  4900. // depreciated
  4901.  
  4902. public static function getAllDealsOfACommunity($communityId, $status = NULL, $publicOnly = false) {
  4903. $deal = new Deals;
  4904. $filter = array();
  4905. $filter['communityId'] = $communityId;
  4906.  
  4907. if ($status) {
  4908. $filter['status'] = $status;
  4909. }
  4910.  
  4911. if ($publicOnly) {
  4912. $filter['visibility'] = 'public';
  4913. }
  4914.  
  4915. //print_r($filter);exit;
  4916. return $deal->searchDeals($filter);
  4917. }
  4918.  
  4919. // need to organise below
  4920.  
  4921. public static function userAccess($live_deal_id, $mode, $date, $time) {
  4922.  
  4923. $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
  4924. $liveDeal = $liveCollection->findOne(array("_id" => new MongoId($live_deal_id)));
  4925. $accessList = $liveDeal['access_info'];
  4926. $accessList[count($liveDeal['access_info'])] = array($mode, $date, $time);
  4927. $liveCollection->update(array(
  4928. "_id" => new MongoID($live_deal_id)
  4929. ), array('$set' => array("access_info" => $accessList)));
  4930.  
  4931. return "transaction_saved";
  4932. }
  4933.  
  4934. public static function listAccess($live_deal_id, $user) {
  4935. $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
  4936. $liveDeal = $liveCollection->findOne(array("_id" => new MongoId($live_deal_id), "user_id" => intval($user)));
  4937. //count access data
  4938. $count = count($liveDeal['access_info']);
  4939. if ($count > 0) {
  4940. $liveDeal['access_info'] = array_reverse($liveDeal['access_info']);
  4941. $object = new stdClass;
  4942. $object->access_data = $liveDeal['access_info'];
  4943.  
  4944. return $object;
  4945. } else {
  4946. return "access_info_empty";
  4947. }
  4948. }
  4949.  
  4950. public static function listAccessTagverts($user_id, $communityId) {
  4951. $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
  4952. $liveDeals = $liveCollection->find(array("user_id" => intval($user_id), "type" => "access", "owner.id" => intval($communityId)));
  4953.  
  4954.  
  4955. $parsedDeals = array();
  4956.  
  4957. foreach ($liveDeals as $key => $deal) {
  4958. $object = new stdClass;
  4959. $object->id = $deal['_id']->__toString();
  4960. $object->title = $deal['title'];
  4961.  
  4962. $parsedDeals[] = $object;
  4963. }
  4964.  
  4965.  
  4966. return $parsedDeals;
  4967. }
  4968.  
  4969. public static function validateTransfer($live_deal_id, $target, $sender) {
  4970. $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
  4971. $deal_to_transfer = $liveCollection->findOne(array("_id" => new MongoID($live_deal_id)));
  4972. if (is_numeric($target) == 1) {
  4973. $user = Users::model()->findByPk($target);
  4974. if ($user) {
  4975. $email = $user->user_email;
  4976. $member = CommunityUsers::model()->findByAttributes(array("user_id" => $user->id, "community_id" => $deal_to_transfer['owner']['id']));
  4977. if ($member) {
  4978. $checkIfMemberRole = CommunityUsers::getRoleOfUser($user->id, $deal_to_transfer['owner']['id']);
  4979. if ($checkIfMemberRole->role_type == 3) {
  4980. $checkIfAlreadyTaken = $liveCollection->findOne(array("deal_id" => new MongoID($deal_to_transfer['deal_id']), "user_id" => intval($user->id)));
  4981. if ($checkIfAlreadyTaken) {
  4982. if (((string) $checkIfAlreadyTaken['_id']) != ((string) $live_deal_id)) {
  4983. return "user_already_own_this_reward";
  4984. } else {
  4985. return "tagvert_already_taken";
  4986. }
  4987. } else {
  4988. $transfer_info = array(
  4989. "user_email" => $email
  4990. );
  4991.  
  4992. $liveCollection->update(array(
  4993. "_id" => new MongoID($live_deal_id)
  4994. ), array('$set' => array("tagvert_transfer_info" => $transfer_info)));
  4995.  
  4996. return "transfer_to_member_ok";
  4997. }
  4998. } else {
  4999. return "not_member_role";
  5000. }
  5001. } else {
  5002. $transfer_info = array(
  5003. "user_email" => $email
  5004. );
  5005.  
  5006. $stat = $liveCollection->update(array(
  5007. "_id" => new MongoID($live_deal_id)
  5008. ), array('$set' => array("tagvert_transfer_info" => $transfer_info)));
  5009.  
  5010. return "transfer_to_non_member_ok";
  5011. }
  5012. } else {
  5013. return "invalid_id";
  5014. }
  5015. } else {
  5016. $user = Users::model()->findByAttributes(array("user_email" => $target));
  5017. if ($user) {
  5018. $email = $user->user_email;
  5019. $member = CommunityUsers::model()->findByAttributes(array("user_id" => $user->id, "community_id" => $deal_to_transfer['owner']['id']));
  5020. if ($member) {
  5021. $checkIfMemberRole = CommunityUsers::getRoleOfUser($user->id, $deal_to_transfer['owner']['id']);
  5022.  
  5023. if ($checkIfMemberRole->role_type == 3) {
  5024. $checkIfAlreadyTaken = $liveCollection->findOne(array("deal_id" => new MongoID($deal_to_transfer['deal_id']), "user_id" => intval($user->id)));
  5025. if ($checkIfAlreadyTaken) {
  5026. return "tagvert_already_taken";
  5027. } else {
  5028. $transfer_info = array(
  5029. "user_email" => $email
  5030. );
  5031.  
  5032. $liveCollection->update(array(
  5033. "_id" => new MongoID($live_deal_id)
  5034. ), array('$set' => array("tagvert_transfer_info" => $transfer_info)));
  5035.  
  5036. return "transfer_to_member_ok";
  5037. }
  5038. } else {
  5039. return "not_member_role";
  5040. }
  5041. } else {
  5042. $transfer_info = array(
  5043. "user_email" => $email
  5044. );
  5045.  
  5046. $liveCollection->update(array(
  5047. "_id" => new MongoID($live_deal_id)
  5048. ), array('$set' => array("tagvert_transfer_info" => $transfer_info)));
  5049.  
  5050. return "transfer_to_non_member_ok";
  5051. }
  5052. } else {
  5053. $email_transfer = Deals::sendTagvertTransfer($target, $live_deal_id, $sender);
  5054. return $email_transfer;
  5055. }
  5056. }
  5057. }
  5058.  
  5059. public static function sendTagvertTransfer($email, $liveTagvert, $user_id) {
  5060. $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
  5061. $settings = array(
  5062. 'view' => 'tagvertTransfer',
  5063. 'subject' => "Someone wants to give a tagvert to you!",
  5064. );
  5065.  
  5066. $sender = Users::model()->findByPk($user_id);
  5067. $dealData = $liveCollection->findOne(array("_id" => new MongoID($liveTagvert)));
  5068.  
  5069. $mail = new YiiMailer();
  5070. $mail->IsSMTP();
  5071. $mail->Host = 'smtp.gmail.com';
  5072. $mail->Port = 465;
  5073. $mail->SMTPAuth = true;
  5074. $mail->SMTPSecure = 'ssl';
  5075. $mail->Username = Yii::app()->params['adminEmail'];
  5076. $mail->Password = Yii::app()->params['adminEmailPassword'];
  5077. $mail->setView('dealtransfer');
  5078. $mail->setData(array(
  5079. 'dealTitle' => $dealData['title'],
  5080. 'sender' => $sender->user_firstname . ' ' . $sender->user_lastname,
  5081. 'email' => $email
  5082. ));
  5083. $mail->render();
  5084. $mail->From = Yii::app()->params['adminEmail'];
  5085. $mail->FromName = Yii::app()->name;
  5086. $mail->Subject = Yii::t('labels', Yii::t("labels", "Tagbond tagvert transfer"));
  5087. $mail->AddAddress($contact->user_email);
  5088.  
  5089. if ($mail->Send()) {
  5090. $transfer_info = array(
  5091. "user_email" => $email
  5092. );
  5093.  
  5094. $liveCollection->update(array(
  5095. "_id" => new MongoID($liveTagvert)
  5096. ), array('$set' => array("tagvert_transfer_info" => $transfer_info)));
  5097.  
  5098. return "email_request_sent";
  5099. } else {
  5100. return "email_request_failed";
  5101. }
  5102. }
  5103.  
  5104. public static function pendingTransfer($user_id) {
  5105. $user = Users::model()->findByPk($user_id);
  5106. $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
  5107. $pending = $liveCollection->find(array("tagvert_transfer_info.user_email" => $user->user_email));
  5108. $pending_deals = array();
  5109. foreach ($pending as $key => $value) {
  5110. $deal_id = $value['deal_id']->__toString();
  5111. $deal_live_id = $value['_id']->__toString();
  5112. $deal_title = $value['title'];
  5113. $deal_owner_id = $value['user_id'];
  5114. $deal_owner_name = $value['userinfo']['user_firstname'] . " " . $value['userinfo']['user_lastname'];
  5115. 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));
  5116. }
  5117. return $pending_deals;
  5118. }
  5119.  
  5120. public static function acceptTransfer($liveDeal, $user_id) {
  5121.  
  5122. $user = Users::model()->findByPk($user_id);
  5123. $new_user_info = array('id' => intval($user_id), 'user_firstname' => $user->user_firstname, 'user_lastname' => $user->user_lastname);
  5124. $transfer_info = array();
  5125.  
  5126. $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
  5127. $liveCollection->update(array(
  5128. "_id" => new MongoID($liveDeal)
  5129. ), array('$set' => array("tagvert_transfer_info" => $transfer_info, "user_id" => $user_id, "userinfo" => $new_user_info)));
  5130.  
  5131. return "transfer_ok";
  5132. }
  5133.  
  5134. public static function removeTransfer($liveDeal) {
  5135. $transfer_info = array();
  5136. $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
  5137. $liveCollection->update(array(
  5138. "_id" => new MongoID($liveDeal)
  5139. ), array('$set' => array("tagvert_transfer_info" => $transfer_info)));
  5140.  
  5141. return "transfer_removed";
  5142. }
  5143.  
  5144. public function deactivateDeal() {
  5145. if (!TagMongo::isValidId($this->dealId)) {
  5146. throw new CHttpException(404, "invalid_deal_id");
  5147. }
  5148. $collection = Yii::app()->edmsMongoCollection('deals');
  5149. $deal = $collection->findOne(array("_id" => new MongoID($this->dealId)));
  5150. if ($deal) {
  5151.  
  5152. if ($deal['status'] == 1) {
  5153. $collection->update(
  5154. array("_id" => new MongoID($this->dealId)), array('$set' => array("status" => 4))
  5155. );
  5156. return true;
  5157. }
  5158. return false;
  5159. } else {
  5160. throw new CHttpException(404, "invalid_deal_id");
  5161. }
  5162. }
  5163.  
  5164. public function activateDeal() {
  5165. if (!TagMongo::isValidId($this->dealId)) {
  5166. throw new CHttpException(404, "invalid_deal_id");
  5167. }
  5168. $collection = Yii::app()->edmsMongoCollection('deals');
  5169. $deal = $collection->findOne(array("_id" => new MongoID($this->dealId)));
  5170. if ($deal) {
  5171.  
  5172. if ($deal['status'] == 4) {
  5173. $collection->update(
  5174. array("_id" => new MongoID($this->dealId)), array('$set' => array("status" => 1))
  5175. );
  5176. return true;
  5177. }
  5178. return false;
  5179. } else {
  5180. throw new CHttpException(404, "invalid_deal_id");
  5181. }
  5182. }
  5183.  
  5184. public function getCurrentDealStatus($dealId, $affiliateId = NULL) {
  5185.  
  5186. $collection = Yii::app()->edmsMongoCollection('deals');
  5187. $deal = $collection->findOne(array(
  5188. "_id" => new MongoID($dealId),
  5189. ));
  5190.  
  5191. if ($deal) {
  5192. $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
  5193.  
  5194. $liveDeal = $liveCollection->findOne(array(
  5195. "deal_id" => new MongoID($dealId),
  5196. "user_id" => intval($this->userId)
  5197. ));
  5198.  
  5199. if ($liveDeal) {
  5200.  
  5201. //can take_action (add stamp)
  5202. if ($liveDeal['type'] == "stamp") {
  5203. $user_deal_details['deal_status'] = 'can_not_take_action';
  5204. $user_deal_details['message'] = '';
  5205.  
  5206. if (($liveDeal['status'] == 1) && ($liveDeal['dealinfo']['take_action'])) {
  5207. $user_deal_details['deal_status'] = 'can_take_action';
  5208. $user_deal_details['message'] = '';
  5209. }
  5210. }
  5211.  
  5212. //can redeem
  5213. if (($liveDeal['status'] == 3) && ($liveDeal['rewardinfo']['self_redeem'])) {
  5214. $user_deal_details['deal_status'] = 'can_redeem';
  5215. }
  5216. } else {
  5217. $user_details = Deals::checkIfUserCanTakeDeal($deal, $this->userId, $affiliateId);
  5218. if ($user_details->can_take == 1) {
  5219. $user_deal_details['deal_status'] = 'can_take';
  5220. } else {
  5221. $user_deal_details['deal_status'] = 'can_not_take';
  5222. $user_deal_details['message'] = $user_details->errors;
  5223. }
  5224. }
  5225. $user_deal_details['deal_type'] = $deal['type'];
  5226. return $user_deal_details;
  5227. } else {
  5228. return false;
  5229. }
  5230. }
  5231.  
  5232. public function dealQRCodeAction($qr_code, $action_auto = false) {
  5233.  
  5234. $collection = Yii::app()->edmsMongoCollection('deals_live');
  5235. $deal = $collection->findOne(array("dealinfo.code" => intval($qr_code)));
  5236.  
  5237. if ($deal) {
  5238. $data['dealid'] = $deal['deal_id']->__toString();
  5239. $data['type'] = $deal['type'];
  5240. if ($deal['type'] == 'stamp') {
  5241. if ($action_auto == 'auto') {
  5242. $result = $this->takeAction($data['dealid'], $this->userId, NULL, $this->communityId);
  5243. if ($result) {
  5244. $data['status'] = $result;
  5245. }
  5246. }
  5247. return $data;
  5248. }
  5249. throw new CHttpException(403, 'no_action_associated_for_this_tagvert');
  5250. }
  5251. throw new CHttpException(403, 'invalid_code');
  5252. }
  5253.  
  5254. public function getTypes() {
  5255. $collection = Yii::app()->edmsMongoCollection('deals');
  5256. $deal = $collection->distinct("type");
  5257. return $deal;
  5258. }
  5259.  
  5260. public function getAdvertList($filter = array(), $params = array()) {
  5261.  
  5262. $collection = Yii::app()->edmsMongoCollection('deals');
  5263.  
  5264. // pagination
  5265. if (isset($this->pageOffset) && (!is_numeric($this->pageOffset) || $this->pageOffset < 0)) {
  5266. $this->pageOffset = 0;
  5267. }
  5268.  
  5269. if (isset($this->pageCount) && (!is_numeric($this->pageCount) || $this->pageCount < 0)) {
  5270. $this->pageCount = 100;
  5271. }
  5272.  
  5273. //sorting
  5274. if ($params['sort']) {
  5275. $params['sort'] = intval($params['sort']);
  5276. } else {
  5277. $params['sort'] = -1;
  5278. }
  5279.  
  5280. $query = array();
  5281. $query['visibility'] = 'public';
  5282. if (is_array($filter['type'])) {
  5283. //$query['type'] = $filter['type'];
  5284. $query['type'] = array('$in' => $filter['type']);
  5285. }
  5286.  
  5287. if ($filter['status']) {
  5288. if ($filter['status'] == 'expired') {
  5289. $query['status'] = 2;
  5290. } else if ($filter['status'] == 'disabled') {
  5291. $query['status'] = 4;
  5292. } else {
  5293. $query['status'] = 1;
  5294. }
  5295. }
  5296.  
  5297. if (is_array($filter['title'])) {
  5298. //$query['title'] = array('$regex' => $filter['title'], '$options' => 'i');
  5299. $query['title'] = array('$in' => $filter['title']);
  5300. }
  5301.  
  5302. if (is_array($filter['city'])) {
  5303. //$query['city'] = array('$regex' => $filter['city'], '$options' => 'i');
  5304. $query['city'] = array('$in' => $filter['city']);
  5305. }
  5306.  
  5307. if ($filter['country_id']) {
  5308. $countryIds = array();
  5309. foreach ($filter['country_id'] as $country) {
  5310. $countryIds[] = intval($country);
  5311. }
  5312. $query['owner.id'] = array('$in' => $countryIds);
  5313.  
  5314. //$query['country.id'] = intval($filter['country_id']);
  5315. }
  5316.  
  5317. if (is_array($filter['tags'])) {
  5318. foreach ($filter['tags'] as $tag) {
  5319. $tags[] = ucwords($tag);
  5320. }
  5321. $filter['tags'] = array_merge($filter['tags'], $tags);
  5322. $query['tags'] = array('$in' => $filter['tags']);
  5323. }
  5324.  
  5325. //filter by owner
  5326. if ($filter['community_id']) {
  5327. $communityIds = array();
  5328. foreach ($filter['community_id'] as $community) {
  5329. $communityId[] = intval($community);
  5330. }
  5331. $query['owner.id'] = array('$in' => $communityId);
  5332. $query['owner.type'] = 'community';
  5333. }
  5334.  
  5335. // executing query
  5336. $deals = $collection->find($query)
  5337. ->skip($this->pageOffset)
  5338. ->limit($this->pageCount)
  5339. ->sort(array("_id" => $params['sort']));
  5340.  
  5341. // parsing the result
  5342. $parsedDeals = array();
  5343.  
  5344. $settings = SiteSettings::getSettings();
  5345. if ($this->communityId) {
  5346. $id = $this->communityId;
  5347. $defaults = CommunityPreferences::model()->findByPk($id);
  5348. } else {
  5349. $id = $this->userId;
  5350. $defaults = UserPreferences::model()->findByPk($id);
  5351. }
  5352. $wallet_id = $defaults['pref_wallet_id'] > 0 ? $defaults['pref_wallet_id'] : 1;
  5353. $imageS3Path = 'uploads/tagverts';
  5354.  
  5355. if ($deals) {
  5356. $i = 0;
  5357. foreach ($deals as $deal) {
  5358. $dealId = $deal['_id']->__toString();
  5359. $parsedDeals[$i]['title'] = $deal['title'];
  5360. $parsedDeals[$i]['type'] = $deal['type'];
  5361. $parsedDeals[$i]['description'] = $deal['description'];
  5362. //$parsedDeals[$i]['url'] = $settings->site_url.'/d/'.$dealId.'?userId='.$id.'&wallet_id='.$wallet_id;
  5363. $parsedDeals[$i]['url'] = 'http://www.tagbond.com/d/' . $dealId . '?userId=' . $id . '&wallet_id=' . $wallet_id;
  5364.  
  5365. //get advert images
  5366. if ($filter['image_type'] == 'base64') {
  5367. $imageData = false;
  5368. $imageS3Name = 'd_' . $deal['_id']->__toString() . '.png';
  5369. $resultS3 = Yii::app()->tamazon->isObjectExist($imageS3Path, $imageS3Name);
  5370. if ($resultS3) {
  5371. $resultS3 = Yii::app()->tamazon->getObject($imageS3Path, $imageS3Name);
  5372. $imageData = base64_encode($resultS3['Body']);
  5373. }
  5374. $parsedDeals[$i]['image'] = $imageData;
  5375. } else {
  5376. $parsedDeals[$i]['image_url'] = $settings->site_url . '/image/tagvert/' . $dealId;
  5377. }
  5378.  
  5379. $i++;
  5380. }
  5381. }
  5382. return $parsedDeals;
  5383. }
  5384.  
  5385. public function avatarUpload($dealId, $imageData) {
  5386. $imageData = base64_decode($imageData);
  5387. if ($imageData) {
  5388. if (UserImages::checkAws() && UserImages::getImageType($imageData)) {
  5389.  
  5390. $collection_permission = Yii::app()->edmsMongoCollection('deals');
  5391. $permitted = $collection_permission->findOne(array("_id" => new MongoId($dealId), "owner.id" => intval($this->communityId)));
  5392. if (!$permitted)
  5393. throw new CHttpException(403, "permission_denied");
  5394.  
  5395. $imageData = UserImages::convertImage($imageData);
  5396. if ($imageData) {
  5397. //save original image to s3
  5398. $imageName = 'd_' . $dealId . ".jpg";
  5399. $imagePath = Yii::app()->params['uploadPath'] . '/avatars/';
  5400. $imageS3Name = 'd_' . $dealId . '.png';
  5401. $imageS3Path = 'uploads/tagverts';
  5402.  
  5403. //save image
  5404. $resultS3 = Yii::app()->tamazon->uploadObject($imageS3Path, $imageS3Name, $imageData);
  5405.  
  5406. if (!$resultS3) {
  5407. file_put_contents($imagePath . $imageName, $imageData);
  5408. } else {
  5409. //create thumb 1
  5410. $imageData_thumb_1 = UserImages::imagesSizes($imageData, 50, 50);
  5411. //save thumb 1
  5412. $thumbnail_1 = Yii::app()->tamazon->uploadObject('uploads/tagverts/thumbnail_1', $imageName, $imageData_thumb_1);
  5413.  
  5414. //create thumb 2
  5415. $imageData_thumb_2 = UserImages::imagesSizes($imageData, 75, 75);
  5416. //save thumb 2
  5417. $thumbnail_2 = Yii::app()->tamazon->uploadObject('uploads/tagverts/thumbnail_2', $imageName, $imageData_thumb_2);
  5418.  
  5419. //create thumb 3
  5420. $imageData_thumb_3 = UserImages::imagesSizes($imageData, 150, 150);
  5421. //save thumb 3
  5422. $thumbnail_3 = Yii::app()->tamazon->uploadObject('uploads/tagverts/thumbnail_3', $imageName, $imageData_thumb_3);
  5423. }
  5424. return true;
  5425. }
  5426. }
  5427. }
  5428. return false;
  5429. }
  5430.  
  5431. public function checkPPTValidity($deal_id) {
  5432.  
  5433. $dealCollection = Yii::app()->edmsMongoCollection('deals');
  5434. $dealData = $dealCollection->findOne(array("_id" => new MongoID($deal_id)));
  5435.  
  5436. $budget = $dealData['pay_per_take']['budget'];
  5437. $return_data['amount'] = $dealData['pay_per_take']['amount'];
  5438. $return_data['community_id'] = $dealData['owner']['id'];
  5439. $return_data['wallet_id'] = $dealData['pay_per_take']['wallet_id'];
  5440.  
  5441. if ($budget < $return_data['amount'])
  5442. throw new CHttpException(403, "ppt_budget_reached");
  5443.  
  5444. if ($dealData['pay_per_take']['type'] == 'reward') {
  5445. $community = Communities::model()->findByPk();
  5446. $community_balance = $community->community_credits;
  5447. } else if ($dealData['pay_per_take']['type'] == 'wallet') {
  5448. $wallet_balance = WalletBalances::getWalletBalance($dealData['owner']['id'], '2', $dealData['pay_per_take']['wallet_id']);
  5449. $community_balance = $wallet_balance['amount'];
  5450. }
  5451.  
  5452. if ($return_data['amount'] > $community_balance)
  5453. throw new CHttpException(403, "not_enough_community_balance_for_ppt");
  5454.  
  5455. return $return_data;
  5456. }
  5457.  
  5458. public function getEventDetails($filter, $params) {
  5459. $collection = Yii::app()->edmsMongoCollection('deals_live');
  5460.  
  5461. // pagination
  5462. if (isset($this->pageOffset) && (!is_numeric($this->pageOffset) || $this->pageOffset < 0)) {
  5463. $this->pageOffset = 0;
  5464. }
  5465.  
  5466. if (isset($this->pageCount) && (!is_numeric($this->pageCount) || $this->pageCount < 0)) {
  5467. $this->pageCount = 100;
  5468. }
  5469.  
  5470. //sorting
  5471. if ($params['sort']) {
  5472. $params['sort'] = intval($params['sort']);
  5473. } else {
  5474. $params['sort'] = -1;
  5475. }
  5476.  
  5477. $query = array();
  5478.  
  5479. if ($filter['user_id']) {
  5480. $query['user_id'] = intval($filter['user_id']);
  5481. }
  5482.  
  5483. if ($filter['deal_id']) {
  5484. $query['deal_id'] = new MongoID($filter['deal_id']);
  5485. }
  5486.  
  5487. //$query['owner.id'] = intval($this->communityId);
  5488.  
  5489. if ($filter['paid']) {
  5490. $query['paid'] = $filter['paid'];
  5491. }
  5492. // executing query
  5493. $deals = $collection->find($query)
  5494. ->skip($this->pageOffset)
  5495. ->limit($this->pageCount)
  5496. ->sort(array("_id" => $params['sort']));
  5497.  
  5498. // parsing the result
  5499. $parsedDeals = array();
  5500.  
  5501. if ($deals) {
  5502. $i = 0;
  5503. foreach ($deals as $deal) {
  5504. $parsedDeals['title'] = $deal['title'];
  5505. $parsedDeals['eventdetails'] = $deal['dealinfo'];
  5506. $parsedDeals['tickets'][$i] = $deal['price'];
  5507. $parsedDeals['userdetails'][$i][id] = $deal['userinfo']['id'];
  5508. $parsedDeals['userdetails'][$i][user_firstname] = $deal['userinfo']['user_firstname'];
  5509. $parsedDeals['userdetails'][$i][user_lastname] = $deal['userinfo']['user_lastname'];
  5510.  
  5511. $parsedDeals['userdetails'][$i]['date_taken'] = $deal['date_taken'];
  5512. $parsedDeals['userdetails'][$i]['tickets'] = $deal['purchasedTickets'];
  5513. if ($filter['transactions'])
  5514. $parsedDeals['userdetails'][$i]['transactionlist'] = $deal['purchasedTickets'];
  5515. $i++;
  5516. }
  5517. }
  5518. if (count($parsedDeals) == 0) {
  5519. throw new CHttpException(404, "no_event_found");
  5520. }
  5521. return $parsedDeals;
  5522. }
  5523.  
  5524. public function markTransactionPaid($filter) {
  5525. $collection = Yii::app()->edmsMongoCollection('deals_live');
  5526. if ($filter['user_id'] && $filter['deal_id'] && $filter['transaction_id']) {
  5527. $query['user_id'] = intval($filter['user_id']);
  5528. $query['deal_id'] = new MongoID($filter['deal_id']);
  5529. $query['owner.id'] = intval($this->communityId);
  5530. $query['purchasedTickets.history.transaction_code'] = $filter['transaction_id'];
  5531. }
  5532. $deals = $collection->find($query);
  5533. $payment_status = $filter['paid'] == 'yes' ? 'yes' : 'no';
  5534.  
  5535. if ($deals) {
  5536. foreach ($deals as $d) {
  5537. $owner_id = $d['owner']['id'];
  5538. $collection_id = $d['_id'];
  5539. $deal['transaction'] = $d['purchasedTickets'];
  5540. }
  5541. }
  5542.  
  5543. if (!count($deal)) {
  5544. throw new CHttpException(403, "not_a_valid_transaction");
  5545. }
  5546.  
  5547. $array = $deal['transaction']['history'];
  5548. $key = 'transaction_code';
  5549. $value = $filter['transaction_id'];
  5550.  
  5551. $count = count($array);
  5552. for ($i = 0; $i < $count; $i++) {
  5553. if (Deals::search_in_array($value, $array[$i])) {
  5554. $found = $i;
  5555. break;
  5556. }
  5557. }
  5558. $collection->update(
  5559. array("_id" => new MongoID($collection_id)), array('$set' => array("purchasedTickets.history.$found.paid" => $payment_status))
  5560. );
  5561. return $this->getTicketDetails($filter);
  5562. }
  5563.  
  5564. public function updateTicketsUsageStatus($filter) {
  5565. $collection = Yii::app()->edmsMongoCollection('deals_live');
  5566. if ($filter['ticket_id']) {
  5567. $query['deal_id'] = new MongoID($filter['deal_id']);
  5568. $query['user_id'] = intval($filter['user_id']);
  5569. $query['owner.id'] = intval($this->communityId);
  5570. $query['purchasedTickets.tickets.id'] = $filter['ticket_id'];
  5571. }
  5572. $deals = $collection->find($query);
  5573. if ($deals) {
  5574. foreach ($deals as $d) {
  5575. $owner_id = $d['owner']['id'];
  5576. $collection_id = $d['_id'];
  5577. $deal['history'] = $d['purchasedTickets'];
  5578. }
  5579. }
  5580.  
  5581. if (!count($deal)) {
  5582. throw new CHttpException(403, "not_a_valid_ticket");
  5583. }
  5584.  
  5585. $array = $deal['history']['tickets'];
  5586. $key = 'id';
  5587. $value = $filter['ticket_id'];
  5588.  
  5589. $count = count($array);
  5590. for ($i = 0; $i < $count; $i++) {
  5591. if (Deals::search_in_array($value, $array[$i])) {
  5592. $found = $i;
  5593. break;
  5594. }
  5595. }
  5596. $filter['transaction_id'] = $deal['history']['tickets'][$found]['transaction'];
  5597. $collection->update(
  5598. array("_id" => new MongoID($collection_id)), array('$set' => array("purchasedTickets.tickets.$found.used" => "yes"))
  5599. );
  5600. return $this->getTicketDetails($filter);
  5601. }
  5602.  
  5603. public function getTicketDetails($filter) {
  5604.  
  5605. $collection = Yii::app()->edmsMongoCollection('deals_live');
  5606.  
  5607. // pagination
  5608. if (isset($this->pageOffset) && (!is_numeric($this->pageOffset) || $this->pageOffset < 0)) {
  5609. $this->pageOffset = 0;
  5610. }
  5611.  
  5612. if (isset($this->pageCount) && (!is_numeric($this->pageCount) || $this->pageCount < 0)) {
  5613. $this->pageCount = 100;
  5614. }
  5615.  
  5616. //sorting
  5617. if ($params['sort']) {
  5618. $params['sort'] = intval($params['sort']);
  5619. } else {
  5620. $params['sort'] = -1;
  5621. }
  5622.  
  5623. $query = array();
  5624.  
  5625. //$query['owner.id'] = intval($this->communityId);
  5626. $query['deal_id'] = new MongoID($filter['deal_id']);
  5627. if ($filter['ticket_id'])
  5628. $query['purchasedTickets.tickets.id'] = $filter['ticket_id'];
  5629. $query['purchasedTickets.tickets.transaction'] = $filter['transaction_id'];
  5630. $ticket_id = $filter['ticket_id'];
  5631. // executing query
  5632. $deals = $collection->find($query)
  5633. ->skip($this->pageOffset)
  5634. ->limit($this->pageCount)
  5635. ->sort(array("_id" => $params['sort']));
  5636.  
  5637. // parsing the result
  5638. $parsedDeals = array();
  5639. if (!$deals) {
  5640. throw new CHttpException(403, "not_live_ticket");
  5641. }
  5642. if ($deals) {
  5643. foreach ($deals as $d) {
  5644. $deal['tickets'] = $d['price'];
  5645. $deal['history'] = $d['purchasedTickets'];
  5646. $parsedDeals['event_details'] = $d['dealinfo'];
  5647. $parsedDeals['user'] = $d['userinfo'];
  5648. $owner_id = $d['owner']['id'];
  5649. }
  5650. }
  5651. if (!count($parsedDeals)) {
  5652. throw new CHttpException(403, "not_a_live_ticket");
  5653. }
  5654.  
  5655. /* only community owner can view ticket details */
  5656.  
  5657. if ($owner_id != intval($this->communityId)) {
  5658. throw new CHttpException(403, "permission_denied");
  5659. }
  5660.  
  5661. $array = $deal['history']['tickets'];
  5662. $key = 'id';
  5663. $value = $ticket_id;
  5664.  
  5665. $count = count($array);
  5666. for ($i = 0; $i < $count; $i++) {
  5667. if (Deals::search_in_array($value, $array[$i])) {
  5668. $found = $i;
  5669. break;
  5670. }
  5671. }
  5672.  
  5673. $parsedDeals['ticket_details'] = $deal['history']['tickets'][$found];
  5674. if ($parsedDeals['ticket_details']['index'])
  5675. unset($parsedDeals['ticket_details']['index']);
  5676.  
  5677. $price_type = $deal['tickets']['type'];
  5678. if ($deal['tickets']['type'] == 'tPoints') {
  5679. $price_type = 'TAG Points';
  5680. } else {
  5681. $price_type = WalletTypes::getWalletName($deal['tickets']['wallet_id'], true);
  5682. }
  5683. $p_index = $deal['history']['tickets'][$found]['index'];
  5684. $parsedDeals['ticket_details']['price'] = $deal['tickets']['options'][$p_index]['price'] . " " . $price_type;
  5685.  
  5686. for ($u = 0; $u < count($deal['history']['history']); $u++) {
  5687. if ($deal['history']['history'][$u]['transaction_code'] == $filter['transaction_id']) {
  5688. $parsedDeals['ticket_details']['paid'] = $deal['history']['history'][$u]['paid'];
  5689. $parsedDeals['ticket_details']['paidUsing'] = $deal['history']['history'][$u]['paidUsing'];
  5690. }
  5691. }
  5692.  
  5693. return $parsedDeals;
  5694. }
  5695.  
  5696. public function getTicketCount($deal_id) {
  5697. $collection = Yii::app()->edmsMongoCollection('deals_live');
  5698.  
  5699. $query = array();
  5700.  
  5701. $query['deal_id'] = new MongoID($filter['deal_id']);
  5702.  
  5703. // executing query
  5704. $deals = $collection->find($query);
  5705.  
  5706. // parsing the result
  5707. $parsedDeals = array();
  5708. if (!$deals) {
  5709. throw new CHttpException(403, "not_live_ticket");
  5710. }
  5711. if ($deals) {
  5712. foreach ($deals as $d) {
  5713. $deal['tickets'] = $d['price'];
  5714. $deal['history'] = $d['purchasedTickets'];
  5715. $parsedDeals['event_details'] = $d['dealinfo'];
  5716. $parsedDeals['user'] = $d['userinfo'];
  5717. $owner_id = $d['owner']['id'];
  5718. }
  5719. }
  5720. if (!count($parsedDeals)) {
  5721. throw new CHttpException(403, "not_a_live_ticket");
  5722. }
  5723.  
  5724. /* only community owner can view ticket details */
  5725.  
  5726. if ($owner_id != intval($this->communityId)) {
  5727. throw new CHttpException(403, "permission_denied");
  5728. }
  5729.  
  5730. $array = $deal['history'];
  5731. $key = 'id';
  5732. $value = $ticket_id;
  5733.  
  5734. $count = count($array);
  5735. for ($i = 0; $i < $count; $i++) {
  5736. if (Deals::search_in_array($value, $array[$i])) {
  5737. $found = $i;
  5738. break;
  5739. }
  5740. }
  5741. $parsedDeals['ticket_details'] = $deal['history'][$found]['history'][0];
  5742. $parsedDeals['ticket_details']['category'] = $deal['tickets']['options'][$found]['category'];
  5743. $tickets = $deal['history'][$found]['tickets'][0];
  5744. if ($tickets) {
  5745. for ($t = 0; $t < count($tickets); $t++) {
  5746. if ($tickets[$t]['id'] == $ticket_id) {
  5747. $parsedDeals['ticket_details']['id'] = $ticket_id;
  5748. $parsedDeals['ticket_details']['used'] = $tickets[$t]['used'];
  5749. }
  5750. }
  5751. }
  5752.  
  5753. //return $parsedDeals;
  5754. }
  5755.  
  5756. //payreferral fee
  5757. public function payReferral($dealId, $tracker, $user) {
  5758. $collection = Yii::app()->edmsMongoCollection('deals');
  5759. $deal = $collection->findOne(array(
  5760. "_id" => new MongoID($dealId),
  5761. "tracker" => $tracker
  5762. ));
  5763. $affiliate_details = $deal['affiliate_fee'];
  5764. $from_id = $affiliate_details[''][0];
  5765. $transfer = new WalletTransfers();
  5766. $transfer->setIdentity($this->thisObj);
  5767. $transfer->reference_id = uniqid() . rand(10 * 45, 100 * 98);
  5768. $transfer->transfer_from_wallet_id = $transfer->transfer_to_wallet_id = $affiliate_details['wallet_id'][0];
  5769. $transfer->transfer_from_amount = $transfer->transfer_amount = $affiliate_details['amount'][0];
  5770. $transfer->transfer_to_id = $user;
  5771. $transfer->transfer_to_type = 1;
  5772. $transfer->transfer_from_id = $deal['owner']['id'];
  5773. $transfer->transfer_from_type = ($deal['owner']['type'] == 'user') ? '1' : '2';
  5774. $transfer->transfer_narration = 'Referral Commission #' . $dealId;
  5775.  
  5776. if (!$transfer->transfer()) {
  5777. $status_message['payment_failed'][] = $user;
  5778. return false;
  5779. }
  5780. //dbug::p($transfer->getErrors());
  5781. }
  5782.  
  5783. //generic call for ppt, ppc, and ppr -- incomplete
  5784. public function payCommission() {
  5785. switch ($this->type) {
  5786. case 'ppt':
  5787. $type = 10;
  5788. break;
  5789.  
  5790. case 'ppc':
  5791. $type = 14;
  5792. break;
  5793.  
  5794. case 'ppr':
  5795. $type = 15;
  5796. break;
  5797. }
  5798. $settings = SiteSettings::getSettings();
  5799. $walletBalance = WalletBalances::model()->findByAttributes(array(
  5800. 'balance_id' => $userId,
  5801. 'balance_type' => 1,
  5802. 'wallet_type_id' => $deal['price']['wallet_id'],
  5803. ));
  5804.  
  5805. /* if(!$walletBalance || !$walletBalance->checkWalletBalance($deal['price']['amount'])){
  5806. $status_message['insufficient_amount'][] = $assigneeUserId;
  5807. continue;
  5808. }* */
  5809.  
  5810. $transfers = new WalletTransfers();
  5811. //$transfers->transfer_from_wallet_id = $deal['price']['wallet_id'];
  5812. if ($type == 10) {//ppt
  5813. }
  5814. }
  5815.  
  5816. public function getPromoCodeDetails() {
  5817. $collection = Yii::app()->edmsMongoCollection('deals_live');
  5818.  
  5819. $query = array();
  5820.  
  5821. $query['type'] = "promo";
  5822. $query['owner.id'] = intval($this->communityId);
  5823. $query['dealinfo.promo_codes.code'] = $this->promoCodes;
  5824.  
  5825. // executing query
  5826. $deals = $collection->find($query);
  5827.  
  5828. // parsing the result
  5829. $parsedDeals = array();
  5830. if (!$deals) {
  5831. throw new CHttpException(403, "invalid_promocode");
  5832. }
  5833. if ($deals) {
  5834. foreach ($deals as $d) {
  5835. $parsedDeals['promo_type'] = $d['dealinfo']['promo_type'];
  5836. $parsedDeals['user'] = $d['userinfo'];
  5837. $parsedDeals['emailInfo'] = $d['dealinfo']['emailInfo'];
  5838. }
  5839. }
  5840. if (!count($parsedDeals)) {
  5841. throw new CHttpException(403, "invalid_promocode");
  5842. }
  5843.  
  5844. return $parsedDeals;
  5845. }
  5846.  
  5847. public static function payAffiliateReward($live = NULL, $deal, $method, $quantity, $affiliateInfo = NULL) {
  5848. $from = $deal->owner->id;
  5849. $fromType = 2;
  5850. $wallet = ($live != NULL) ? $live->affiliate_info->wallet_id : $affiliateInfo->wallet_id;
  5851.  
  5852. //for affiliate user
  5853. $totalForAffiliate = ($live != NULL) ? $live->affiliate_info->amount : $affiliateInfo->amount;
  5854. $to = ($live != NULL) ? $live->affiliate_info->id : $affiliateInfo->id;
  5855. $userGets = $totalForAffiliate * $quantity;
  5856. $narration = "Affiliate reward for sharing " . $deal->dealinfo['event_name'] . " advert (" . $totalForAffiliate . " x " . $quantity . ")";
  5857.  
  5858. self::transferPayment($userGets, $from, $fromType, $to, 1, $wallet, $narration);
  5859.  
  5860. //for system
  5861. $totalForSystem = ($live != NULL) ? $live->affiliate_info->systemAmount : $affiliateInfo->systemAmount;
  5862. $systemGets = $totalForSystem * $quantity;
  5863. $to = Yii::app()->params['tagcashID'];
  5864. $narration = "30% Affiliate reward for sharing " . $deal->dealinfo['event_name'] . " advert (" . $totalForSystem . " x " . $quantity . ")";
  5865.  
  5866. self::transferPayment($systemGets, $from, $fromType, $to, 2, $wallet, $narration);
  5867.  
  5868. return true;
  5869. }
  5870.  
  5871. public static function payPercentageAffiliateReward($live = NULL, $deal, $method, $quantity, $price, $percentage, $affiliateInfo = NULL) {
  5872. $set = $percentage * 100;
  5873. $totalSales = $quantity * $price;
  5874. $toBegiven = $totalSales * $percentage;
  5875. $from = $deal->owner->id;
  5876. $fromType = 2;
  5877. $wallet = ($live != NULL) ? $live->affiliate_info->wallet_id : $affiliateInfo->wallet_id;
  5878.  
  5879. //for affiliate user
  5880. $totalForAffiliate = $toBegiven * .7;
  5881. $to = ($live != NULL) ? $live->affiliate_info->id : $affiliateInfo->id;
  5882. $userGets = $totalForAffiliate;
  5883. $narration = "Affiliate reward for sharing " . $deal->dealinfo['event_name'] . " advert (" . $set . "% of total sales)";
  5884.  
  5885. self::transferPayment($userGets, $from, $fromType, $to, 1, $wallet, $narration);
  5886.  
  5887. //for system
  5888. $totalForSystem = $toBegiven * .3;
  5889. $systemGets = $totalForSystem;
  5890. $to = Yii::app()->params['tagcashID'];
  5891. $narration = "30% Affiliate reward for sharing " . $deal->dealinfo['event_name'] . " advert (" . $set . "% of total sales)";
  5892.  
  5893. self::transferPayment($systemGets, $from, $fromType, $to, 2, $wallet, $narration);
  5894.  
  5895. return true;
  5896. }
  5897.  
  5898. public function transferPayment($amount, $from, $fromType, $to, $toType, $wallet, $narration, $return_ref_id = false) {
  5899. $preTransaction = Yii::app()->db->getCurrentTransaction();
  5900. if (!$preTransaction) {
  5901. $transaction = Yii::app()->db->beginTransaction();
  5902. }
  5903.  
  5904. $code = uniqid() . rand(10 * 45, 100 * 98);
  5905. $modelWalletTransfers = new WalletTransfers();
  5906. $modelWalletTransfers->settings = SiteSettings::getSettings();
  5907. $modelWalletTransfers->user = Users::model()->findByPk($from);
  5908. $modelWalletTransfers->reference_id = $code;
  5909. $modelWalletTransfers->transfer_type = 1;
  5910. $modelWalletTransfers->transfer_amount = $amount;
  5911. $modelWalletTransfers->transfer_from_id = $from;
  5912. $modelWalletTransfers->transfer_from_type = $fromType; //1 - user , 2 - community
  5913. $modelWalletTransfers->transfer_from_wallet_id = $wallet;
  5914. $modelWalletTransfers->transfer_from_amount = $amount;
  5915. $modelWalletTransfers->transfer_to_id = $to;
  5916. $modelWalletTransfers->transfer_to_type = $toType; //1 - user , 2 - community
  5917. $modelWalletTransfers->transfer_to_wallet_id = $wallet;
  5918. $modelWalletTransfers->transfer_narration = $narration;
  5919. $modelWalletTransfers->userId = $from;
  5920. $stat = $modelWalletTransfers->transfer();
  5921. if ($stat) {
  5922. //end transaction - commiting
  5923. if (!$preTransaction) {
  5924. $transaction->commit();
  5925. }
  5926. if ($return_ref_id == true)
  5927. return $stat;
  5928. return true;
  5929. }
  5930. else {
  5931. if ($return_ref_id == true) {
  5932. return $modelWalletTransfers->getErrors();
  5933. }
  5934. return false;
  5935. }
  5936. }
  5937.  
  5938. public function itemPurchasePayment($merchant_pay, $from, $wallet, $order_id) {
  5939. $preTransaction = Yii::app()->db->getCurrentTransaction();
  5940. if (!$preTransaction) {
  5941. $transaction = Yii::app()->db->beginTransaction();
  5942. }
  5943. $transfer_type = 1; // wallet escrow transfer. see above commented code.
  5944. $narration = 'Purchase Catalog : #' . $order_id;
  5945. $escrow = new Escrow;
  5946. $escrow->setIdentity($this->thisObj);
  5947. $params = array(
  5948. 'from_wallet_id' => $wallet,
  5949. 'to_type' => 'community',
  5950. 'to_id' => 2,
  5951. 'to_wallet_id' => $wallet,
  5952. 'amount' => array_sum($merchant_pay),
  5953. 'narration' => $narration,
  5954. 'transfer_type' => $transfer_type
  5955. );
  5956. $stat = $escrow->initiate($params, true);
  5957. if ($stat) {
  5958. SELF::updateItemPurchaseMerchantPayments($merchant_pay, 1, $wallet, $stat, $order_id);
  5959. //end transaction - commiting
  5960. if (!$preTransaction) {
  5961. $transaction->commit();
  5962. }
  5963. return $stat;
  5964. } else {
  5965. return false;
  5966. }
  5967. }
  5968.  
  5969. public static function updateItemPurchaseMerchantPayments($merchant_pay, $payment_method = 1, $wallet, $stat, $order_id) {
  5970. foreach ($merchant_pay as $merchant_id => $amount) {
  5971. $purchseRecord = new ItemPurchaseMerchantPayments;
  5972. $purchseRecord->order_id = $order_id;
  5973. $purchseRecord->payment_id = $stat;
  5974. $purchseRecord->payment_method = $payment_method;
  5975. $purchseRecord->merchant_id = $merchant_id;
  5976. $purchseRecord->amount = $amount;
  5977. $purchseRecord->wallet_id = $wallet;
  5978. $purchseRecord->pay_date = gmdate("Y-m-d H:i:s");
  5979. $purchseRecord->status = 0;
  5980. $purchseRecord->save(true);
  5981. if ($purchseRecord->getErrors()) {
  5982. return false;
  5983. }
  5984. return true;
  5985. }
  5986. }
  5987.  
  5988. public function purchaseTicket() {
  5989. $object = new stdClass;
  5990. $object->errors = array();
  5991.  
  5992. $collection = Yii::app()->edmsMongoCollection('deals');
  5993. $deal = $collection->findOne(array(
  5994. "_id" => new MongoID($this->dealId),
  5995. ));
  5996. if ($deal) {
  5997. if ($this->payment_method) {
  5998. if (!in_array($this->payment_method, $deal['methodOfPayment']['method'])) {
  5999. throw new CHttpException(403, "payment_method_not_available");
  6000. }
  6001. } else {
  6002. if ($deal['methodOfPayment']['method']) {
  6003. throw new CHttpException(403, "payment_method_not_valid");
  6004. }
  6005. }
  6006.  
  6007. $checkMember = CommunityUsers::model()->findByAttributes(array("user_id" => $this->userId, "community_id" => $deal['owner']['id']));
  6008.  
  6009. //if not member : auto join
  6010. if (!$checkMember) {
  6011. $default_role = CommunityRoles::model()->findByAttributes(array('community_id' => $deal->owner->id, 'role_default' => '1'));
  6012. $roleId = $default_role->id;
  6013. $modelUsers = new CommunityUsers;
  6014. $modelUsers->user_id = $this->userId;
  6015. $modelUsers->community_id = $deal['owner']['id'];
  6016. $modelUsers->role_id = $roleId;
  6017. $modelUsers->communityuser_status = 1;
  6018. $modelUsers->communityuser_relation = 1;
  6019. $modelUsers->save();
  6020. }
  6021.  
  6022. //limits - Per User, Per Day and Global Limit
  6023. if ($deal['limits']['max_global_limit']) {
  6024.  
  6025. if (Deals::countTimesTaken($this->dealId, true) >= $deal['limits']['max_global_limit']) {
  6026. $object->errors[] = 'limit_exceeded';
  6027. }
  6028. } else {
  6029. if ($deal['limits']['max_limit_per_day']) {
  6030. if (Deals::countTimesTakenPerDay($this->dealId) >= $deal['limits']['max_limit_per_day']) {
  6031. $object->errors[] = 'limit_per_day_exceeded';
  6032. }
  6033. } else {
  6034. if ($deal['limits']['max_limit_per_user']) {
  6035. if (Deals::countTimesTaken($this->dealId, true, $this->userId) >= $deal['limits']['max_limit_per_user']) {
  6036. $object->errors[] = 'limit_per_user_exceeded';
  6037. }
  6038. }
  6039. }
  6040. }
  6041. if (!$object->errors) {
  6042.  
  6043. //check for payment method 0= tagpoints; 1 = tagcash payment; 2= cash on pickup/delivery
  6044. if ($this->payment_method) {
  6045.  
  6046. if ($this->payment_method == 1) { //pay using tagcash
  6047. if ($this->wallet_id <= 0)
  6048. throw new CHttpException(403, "invalid_wallet_id");
  6049. $response = $this->payTicketViaTagcash();
  6050. if ($response)
  6051. $object->result->transaction_id = $response;
  6052. else
  6053. $object->errors[] = 'payment_failed';
  6054. }
  6055. elseif ($this->payment_method == 2) { //pay on site
  6056. $response = $this->payTicketsOnSite();
  6057. if ($response)
  6058. $object->result->transaction_id = $response;
  6059. else
  6060. $object->errors[] = 'transaction_failed';
  6061. }
  6062. elseif ($this->payment_method == 3) { //paypal
  6063. if ($this->paypalInfo && $this->paypalInfo['txn_id'] && $this->paypalInfo['payment_date']) {
  6064.  
  6065. $response = $this->payTicketsViaPaypal();
  6066.  
  6067. if ($response)
  6068. $object->result->transaction_id = $response;
  6069. else
  6070. $object->errors[] = 'transaction_failed';
  6071. }
  6072. else {
  6073. throw new CHttpException(403, "incomplete_paypal_information");
  6074. }
  6075. } elseif ($this->payment_method == 4) { //dragonpay
  6076. $response = $this->payTicketsViaDragonpay();
  6077. if ($response)
  6078. $object->result->url = $response;
  6079. else
  6080. $object->errors[] = 'transaction_failed';
  6081. }
  6082. }else {
  6083. if ($deal['price']['type'] == 'tPoints') {
  6084. $this->wallet_id = 20;
  6085. $response = $this->payTicketViaTagcash();
  6086. if ($response)
  6087. $object->result->transaction_id = $response;
  6088. else
  6089. $object->errors[] = 'transaction_failed';
  6090. }else {
  6091. $response = $this->getFreeTickets();
  6092. if ($response)
  6093. $object->result->transaction_id = $response;
  6094. else
  6095. $object->errors[] = 'transaction_failed';
  6096. }
  6097. }
  6098. }
  6099. return $object;
  6100. }
  6101. }
  6102.  
  6103. public function getFreeTickets() {
  6104. $cart_tickets = $this->tickets;
  6105. $dealId = $this->dealId;
  6106. $userId = $this->userId;
  6107. $ticket_index = array_keys($cart_tickets);
  6108. $ticket_count = array_values($cart_tickets);
  6109. $quantity = array_sum($cart_tickets);
  6110.  
  6111. $collection = Yii::app()->edmsMongoCollection('deals');
  6112. $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
  6113. $livePurchasedTicket = self::liveDealInfo($dealId, $userId);
  6114. $deal = self::dealInfo($dealId);
  6115.  
  6116. //affiliate
  6117. if ($params['affiliateId'] && ($params['affiliateId'] != $this->userId)) {
  6118. $affiliateId = $params['affiliateId'];
  6119. $affiliateWalletId = $params['affiliateWalletId'];
  6120. } else {
  6121. $affiliateId = NULL;
  6122. }
  6123.  
  6124. if (!$livePurchasedTicket) {
  6125. //initialize bookmark of event
  6126. SELF::bookmarkDeal($dealId, $affiliateId, NULL, $affiliateWalletId);
  6127. $purchasedTickets = array('history' => array(), 'tickets' => array());
  6128. } else {
  6129. $purchasedTickets = $livePurchasedTicket->purchasedTickets;
  6130. }
  6131. $transaction_id = uniqid() . rand(10 * 45, 100 * 98);
  6132. $purchaseDetails = array(
  6133. 'transaction_code' => $transaction_id,
  6134. 'date_purchased' => date('Y-m-d H:i:s A'),
  6135. 'quantity' => $quantity,
  6136. 'paid' => 'yes',
  6137. 'paidUsing' => 'Free Ticket'
  6138. );
  6139. if ($params['participant']['additional']) {
  6140. $purchaseDetails['additional'] = $params['participant']['additional'];
  6141. }
  6142. $totalAmount = 0;
  6143.  
  6144. for ($i = 0; $i < sizeOf($ticket_index); $i++) {
  6145. if ($deal->price['options'][$ticket_index[$i]]['price'] && $deal->price['options'][$ticket_index[$i]]['price'] > 0)
  6146. return false;
  6147. if ($ticket_count[$i] > 0) {
  6148. for ($counter = 0; $counter < $ticket_count[$i]; $counter++) {
  6149. $ticket_id = uniqid() . rand(10 * 45, 100 * 98);
  6150. $ticket = array(
  6151. 'id' => $ticket_id,
  6152. 'index' => $ticket_index[$i],
  6153. 'used' => 'no',
  6154. 'category' => $deal->price['options'][$ticket_index[$i]]['category'],
  6155. 'transaction' => $transaction_id,
  6156. 'first_name' => $params['fname'],
  6157. 'middle_name' => $params['mname'],
  6158. 'last_name' => $params['lname'],
  6159. 'email' => $params['email'],
  6160. 'contact' => $params['number']
  6161. );
  6162. array_push($purchasedTickets['tickets'], $ticket);
  6163. }
  6164. if ($deal->price['options'][$ticket_index[$i]]['quantity'] != "") {
  6165. $deal->price['options'][$ticket_index[$i]]['quantity'] -= $ticket_count[$i];
  6166. }
  6167. }
  6168. }
  6169.  
  6170. array_push($purchasedTickets['history'], $purchaseDetails);
  6171. $collection->update(
  6172. array(
  6173. "_id" => new MongoID($dealId),
  6174. ), array('$set' => array("price" => $deal->price))
  6175. );
  6176. $liveCollection->update(
  6177. array(
  6178. "deal_id" => new MongoID($dealId),
  6179. "user_id" => intval($this->userId),
  6180. ), array('$set' => array("status" => intval(8), "price" => $deal->price, "purchasedTickets" => $purchasedTickets))
  6181. );
  6182. return $transaction_id;
  6183. }
  6184.  
  6185. public function payTicketViaTagcash() {
  6186. $cart_tickets = $this->tickets;
  6187. $dealId = $this->dealId;
  6188. $userId = $this->userId;
  6189. $ticket_index = array_keys($cart_tickets);
  6190. $ticket_count = array_values($cart_tickets);
  6191.  
  6192. $collection = Yii::app()->edmsMongoCollection('deals');
  6193. $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
  6194. $livePurchasedTicket = self::liveDealInfo($dealId, $userId);
  6195. $deal = self::dealInfo($dealId);
  6196.  
  6197. $quantity = array_sum($cart_tickets);
  6198. $fromId = $userId;
  6199. $fromType = 1;
  6200. $walletId = $this->wallet_id;
  6201. $toId = $deal->owner['id'];
  6202. $toType = 2;
  6203. $narration = "Payment for purchasing tickets for the upcoming " . $deal->dealinfo['event_name'];
  6204.  
  6205. //affiliate
  6206. if ($params['affiliateId'] && ($params['affiliateId'] != $this->userId)) {
  6207. $affiliateId = $params['affiliateId'];
  6208. $affiliateWalletId = $params['affiliateWalletId'];
  6209. } else {
  6210. $affiliateId = NULL;
  6211. }
  6212.  
  6213. if (!$livePurchasedTicket) {
  6214. //initialize bookmark of event
  6215. SELF::bookmarkDeal($dealId, $affiliateId, NULL, $affiliateWalletId);
  6216. $purchasedTickets = array('history' => array(), 'tickets' => array());
  6217. } else {
  6218. $purchasedTickets = $livePurchasedTicket->purchasedTickets;
  6219. }
  6220. $transaction_id = uniqid() . rand(10 * 45, 100 * 98);
  6221. $purchaseDetails = array(
  6222. 'transaction_code' => $transaction_id,
  6223. 'date_purchased' => date('Y-m-d H:i:s A'),
  6224. 'quantity' => $quantity,
  6225. 'paid' => 'yes',
  6226. 'paidUsing' => 'tagcash'
  6227. );
  6228. if ($params['participant']['additional']) {
  6229. $purchaseDetails['additional'] = $params['participant']['additional'];
  6230. }
  6231. $totalAmount = 0;
  6232.  
  6233. for ($i = 0; $i < sizeOf($ticket_index); $i++) {
  6234. $totalAmount += (($deal->price['options'][$ticket_index[$i]]['price']) * $ticket_count[$i]);
  6235. if ($ticket_count[$i] > 0) {
  6236. for ($counter = 0; $counter < $ticket_count[$i]; $counter++) {
  6237. $ticket_id = uniqid() . rand(10 * 45, 100 * 98);
  6238. $ticket = array(
  6239. 'id' => $ticket_id,
  6240. 'index' => $ticket_index[$i],
  6241. 'used' => 'no',
  6242. 'category' => $deal->price['options'][$ticket_index[$i]]['category'],
  6243. 'transaction' => $transaction_id,
  6244. 'first_name' => $params['fname'],
  6245. 'middle_name' => $params['mname'],
  6246. 'last_name' => $params['lname'],
  6247. 'email' => $params['email'],
  6248. 'contact' => $params['number']
  6249. );
  6250. array_push($purchasedTickets['tickets'], $ticket);
  6251. }
  6252. if ($deal->price['options'][$ticket_index[$i]]['quantity'] != "") {
  6253. $deal->price['options'][$ticket_index[$i]]['quantity'] -= $ticket_count[$i];
  6254. }
  6255. }
  6256. }
  6257.  
  6258. //check user wallet balance
  6259. $user_balance = WalletBalances::getWalletBalance($userId, 1, $walletId);
  6260. if ($totalAmount > $user_balance['amount'])
  6261. throw new CHttpException(403, "insufficient_amount");
  6262. array_push($purchasedTickets['history'], $purchaseDetails);
  6263.  
  6264. //start transaction - if sns error it wont update mongo, so roll back
  6265. $preTransaction = Yii::app()->db->getCurrentTransaction();
  6266. if (!$preTransaction) {
  6267. $transaction = Yii::app()->db->beginTransaction();
  6268. }
  6269.  
  6270. $stat = Deals::transferPayment($totalAmount, $fromId, $fromType, $toId, $toType, $walletId, $narration);
  6271. if ($stat) {
  6272. $collection->update(
  6273. array(
  6274. "_id" => new MongoID($dealId),
  6275. ), array('$set' => array("price" => $deal->price))
  6276. );
  6277. $liveCollection->update(
  6278. array(
  6279. "deal_id" => new MongoID($dealId),
  6280. "user_id" => intval($this->userId),
  6281. ), array('$set' => array("status" => intval(8), "price" => $deal->price, "purchasedTickets" => $purchasedTickets))
  6282. );
  6283. $transaction->commit();
  6284. return $transaction_id;
  6285. } else
  6286. return false;
  6287. }
  6288.  
  6289. public function payTicketsOnSite() {
  6290. $cart_tickets = $this->tickets;
  6291. $dealId = $this->dealId;
  6292. $userId = $this->userId;
  6293. $ticket_index = array_keys($cart_tickets);
  6294. $ticket_count = array_values($cart_tickets);
  6295. $quantity = array_sum($cart_tickets);
  6296.  
  6297. $collection = Yii::app()->edmsMongoCollection('deals');
  6298. $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
  6299. $livePurchasedTicket = self::liveDealInfo($dealId, $userId);
  6300. $deal = self::dealInfo($dealId);
  6301.  
  6302. //affiliate
  6303. if ($params['affiliateId'] && ($params['affiliateId'] != $this->userId)) {
  6304. $affiliateId = $params['affiliateId'];
  6305. $affiliateWalletId = $params['affiliateWalletId'];
  6306. } else {
  6307. $affiliateId = NULL;
  6308. }
  6309.  
  6310. if (!$livePurchasedTicket) {
  6311. //initialize bookmark of event
  6312. SELF::bookmarkDeal($dealId, $affiliateId, NULL, $affiliateWalletId);
  6313. $purchasedTickets = array('history' => array(), 'tickets' => array());
  6314. } else {
  6315. $purchasedTickets = $livePurchasedTicket->purchasedTickets;
  6316. }
  6317. $transaction_id = uniqid() . rand(10 * 45, 100 * 98);
  6318. $purchaseDetails = array(
  6319. 'transaction_code' => $transaction_id,
  6320. 'date_purchased' => date('Y-m-d H:i:s A'),
  6321. 'quantity' => $quantity,
  6322. 'paid' => 'no',
  6323. 'paidUsing' => 'pickup'
  6324. );
  6325. if ($params['participant']['additional']) {
  6326. $purchaseDetails['additional'] = $params['participant']['additional'];
  6327. }
  6328. $totalAmount = 0;
  6329.  
  6330. for ($i = 0; $i < sizeOf($ticket_index); $i++) {
  6331. $totalAmount += (($deal->price['options'][$ticket_index[$i]]['price']) * $ticket_count[$i]);
  6332. if ($ticket_count[$i] > 0) {
  6333. for ($counter = 0; $counter < $ticket_count[$i]; $counter++) {
  6334. $ticket_id = uniqid() . rand(10 * 45, 100 * 98);
  6335. $ticket = array(
  6336. 'id' => $ticket_id,
  6337. 'index' => $ticket_index[$i],
  6338. 'used' => 'no',
  6339. 'category' => $deal->price['options'][$ticket_index[$i]]['category'],
  6340. 'transaction' => $transaction_id,
  6341. 'first_name' => $params['fname'],
  6342. 'middle_name' => $params['mname'],
  6343. 'last_name' => $params['lname'],
  6344. 'email' => $params['email'],
  6345. 'contact' => $params['number']
  6346. );
  6347. array_push($purchasedTickets['tickets'], $ticket);
  6348. }
  6349. if ($deal->price['options'][$ticket_index[$i]]['quantity'] != "") {
  6350. $deal->price['options'][$ticket_index[$i]]['quantity'] -= $ticket_count[$i];
  6351. }
  6352. }
  6353. }
  6354.  
  6355. array_push($purchasedTickets['history'], $purchaseDetails);
  6356. $collection->update(
  6357. array(
  6358. "_id" => new MongoID($dealId),
  6359. ), array('$set' => array("price" => $deal->price))
  6360. );
  6361. $liveCollection->update(
  6362. array(
  6363. "deal_id" => new MongoID($dealId),
  6364. "user_id" => intval($this->userId),
  6365. ), array('$set' => array("status" => intval(8), "price" => $deal->price, "purchasedTickets" => $purchasedTickets))
  6366. );
  6367. return $transaction_id;
  6368. }
  6369.  
  6370. public static function payTicketsViaPaypal() {
  6371. $cart_tickets = $this->tickets;
  6372. $dealId = $this->dealId;
  6373. $userId = $this->userId;
  6374. $ticket_index = array_keys($cart_tickets);
  6375. $ticket_count = array_values($cart_tickets);
  6376. $quantity = array_sum($cart_tickets);
  6377.  
  6378. $collection = Yii::app()->edmsMongoCollection('deals');
  6379. $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
  6380. $livePurchasedTicket = self::liveDealInfo($dealId, $userId);
  6381. $deal = self::dealInfo($dealId);
  6382.  
  6383. //affiliate
  6384. if ($params['affiliateId'] && ($params['affiliateId'] != $this->userId)) {
  6385. $affiliateId = $params['affiliateId'];
  6386. $affiliateWalletId = $params['affiliateWalletId'];
  6387. } else {
  6388. $affiliateId = NULL;
  6389. }
  6390.  
  6391. if (!$livePurchasedTicket) {
  6392. //initialize bookmark of event
  6393. SELF::bookmarkDeal($dealId, $affiliateId, NULL, $affiliateWalletId);
  6394. $purchasedTickets = array('history' => array(), 'tickets' => array());
  6395. } else {
  6396. $purchasedTickets = $livePurchasedTicket->purchasedTickets;
  6397. }
  6398.  
  6399. $transaction_id = uniqid() . rand(10 * 45, 100 * 98);
  6400. $purchaseDetails = array(
  6401. 'transaction_code' => $transaction_id,
  6402. 'date_purchased' => date('Y-m-d H:i:s A'),
  6403. 'quantity' => $quantity,
  6404. 'paid' => 'yes',
  6405. 'paidUsing' => 'paypal',
  6406. 'paypalInfo' => $this->paypalInfo
  6407. );
  6408. if ($params['participant']['additional']) {
  6409. $purchaseDetails['additional'] = $params['participant']['additional'];
  6410. }
  6411.  
  6412. $totalAmount = 0;
  6413. for ($i = 0; $i < sizeOf($ticket_index); $i++) {
  6414. $totalAmount += (($deal->price['options'][$ticket_index[$i]]['price']) * $ticket_count[$i]);
  6415. if ($ticket_count[$i] > 0) {
  6416. for ($counter = 0; $counter < $ticket_count[$i]; $counter++) {
  6417. $ticket_id = uniqid() . rand(10 * 45, 100 * 98);
  6418. $ticket = array(
  6419. 'id' => $ticket_id,
  6420. 'index' => $ticket_index[$i],
  6421. 'used' => 'no',
  6422. 'category' => $deal->price['options'][$ticket_index[$i]]['category'],
  6423. 'transaction' => $transaction_id,
  6424. 'first_name' => $params['fname'],
  6425. 'middle_name' => $params['mname'],
  6426. 'last_name' => $params['lname'],
  6427. 'email' => $params['email'],
  6428. 'contact' => $params['number']
  6429. );
  6430. array_push($purchasedTickets['tickets'], $ticket);
  6431. }
  6432. if ($deal->price['options'][$ticket_index[$i]]['quantity'] != "") {
  6433. $deal->price['options'][$ticket_index[$i]]['quantity'] -= $ticket_count[$i];
  6434. }
  6435. }
  6436. }
  6437.  
  6438. array_push($purchasedTickets['history'], $purchaseDetails);
  6439. $collection->update(
  6440. array(
  6441. "_id" => new MongoID($dealId),
  6442. ), array('$set' => array("price" => $deal->price))
  6443. );
  6444. $liveCollection->update(
  6445. array(
  6446. "deal_id" => new MongoID($dealId),
  6447. "user_id" => intval($this->userId),
  6448. ), array('$set' => array("status" => intval(8), "price" => $deal->price, "purchasedTickets" => $purchasedTickets))
  6449. );
  6450. return $transaction_id;
  6451. }
  6452.  
  6453. public function payTicketsViaDragonpay() {
  6454. $cart_tickets = $this->tickets;
  6455. $dealId = $this->dealId;
  6456. $userId = $this->userId;
  6457. $ticket_index = array_keys($cart_tickets);
  6458. $ticket_count = array_values($cart_tickets);
  6459. $quantity = array_sum($cart_tickets);
  6460.  
  6461. $collection = Yii::app()->edmsMongoCollection('deals');
  6462. $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
  6463. $livePurchasedTicket = self::liveDealInfo($dealId, $userId);
  6464. $deal = self::dealInfo($dealId);
  6465.  
  6466. $fromId = $userId;
  6467. $fromType = 1;
  6468. $walletId = $this->wallet_id;
  6469. $toId = $deal->owner['id'];
  6470. $toType = 2;
  6471. $narration = "Payment for purchasing tickets for the upcoming " . $deal->dealinfo['event_name'];
  6472.  
  6473. //affiliate
  6474. if ($params['affiliateId'] && ($params['affiliateId'] != $this->userId)) {
  6475. $affiliateId = $params['affiliateId'];
  6476. $affiliateWalletId = $params['affiliateWalletId'];
  6477. } else {
  6478. $affiliateId = NULL;
  6479. }
  6480.  
  6481. if (!$livePurchasedTicket) {
  6482. //initialize bookmark of event
  6483. SELF::bookmarkDeal($dealId, $affiliateId, NULL, $affiliateWalletId);
  6484. $purchasedTickets = array('history' => array(), 'tickets' => array());
  6485. } else {
  6486. $purchasedTickets = $livePurchasedTicket->purchasedTickets;
  6487. }
  6488.  
  6489. $transaction_id = uniqid() . rand(10 * 45, 100 * 98);
  6490. $purchaseDetails = array(
  6491. 'transaction_code' => $transaction_id,
  6492. 'date_purchased' => date('Y-m-d H:i:s A'),
  6493. 'quantity' => $quantity,
  6494. 'paid' => 'no',
  6495. 'paidUsing' => 'dragonpay'
  6496. );
  6497. if ($params['participant']['additional']) {
  6498. $purchaseDetails['additional'] = $params['participant']['additional'];
  6499. }
  6500.  
  6501. $totalAmount = 0;
  6502. for ($i = 0; $i < sizeOf($ticket_index); $i++) {
  6503. $totalAmount += (($deal->price['options'][$ticket_index[$i]]['price']) * $ticket_count[$i]);
  6504. if ($ticket_count[$i] > 0) {
  6505. for ($counter = 0; $counter < $ticket_count[$i]; $counter++) {
  6506. $ticket_id = uniqid() . rand(10 * 45, 100 * 98);
  6507. $ticket = array(
  6508. 'id' => $ticket_id,
  6509. 'index' => $ticket_index[$i],
  6510. 'used' => 'no',
  6511. 'category' => $deal->price['options'][$ticket_index[$i]]['category'],
  6512. 'transaction' => $transaction_id,
  6513. 'first_name' => $params['fname'],
  6514. 'middle_name' => $params['mname'],
  6515. 'last_name' => $params['lname'],
  6516. 'email' => $params['email'],
  6517. 'contact' => $params['number']
  6518. );
  6519. array_push($purchasedTickets['tickets'], $ticket);
  6520. }
  6521. if ($deal->price['options'][$ticket_index[$i]]['quantity'] != "") {
  6522. $deal->price['options'][$ticket_index[$i]]['quantity'] -= $ticket_count[$i];
  6523. }
  6524. }
  6525. }
  6526.  
  6527. array_push($purchasedTickets['history'], $purchaseDetails);
  6528.  
  6529. //initiate dragon pay transaction
  6530. $dragonpayTransaction = new DragonpayTransaction;
  6531. $dragonpayTransaction->transfer_from_id = $fromId;
  6532. $dragonpayTransaction->transfer_from_type = $fromType;
  6533. $dragonpayTransaction->transfer_to_id = $toId;
  6534. $dragonpayTransaction->transfer_to_type = $toType;
  6535. $dragonpayTransaction->transfer_from_wallet_id = $walletId;
  6536. $dragonpayTransaction->transfer_to_wallet_id = $walletId;
  6537. $dragonpayTransaction->transfer_from_amount = $totalAmount;
  6538. $dragonpayTransaction->transfer_to_amount = $totalAmount;
  6539. $dragonpayTransaction->custom_field_1 = $dealId;
  6540. $dragonpayTransaction->custom_field_2 = $transaction_id;
  6541. $dragonpayTransaction->transfer_narration = $narration;
  6542. $dragonpayTransaction->method = "tag77";
  6543. $result = $dragonpayTransaction->postDragonpayTransaction();
  6544.  
  6545. if ($result->status == 'success') {
  6546. //update mongo
  6547. $collection->update(
  6548. array(
  6549. "_id" => new MongoID($dealId),
  6550. ), array('$set' => array("price" => $deal->price))
  6551. );
  6552. $liveCollection->update(
  6553. array(
  6554. "deal_id" => new MongoID($dealId),
  6555. "user_id" => intval($this->userId),
  6556. ), array('$set' => array("status" => intval(8), "price" => $deal->price, "purchasedTickets" => $purchasedTickets))
  6557. );
  6558.  
  6559. $redirectUrl = $result->url . '?' . $result->fields;
  6560.  
  6561. return $redirectUrl;
  6562. }
  6563. return false;
  6564. }
  6565.  
  6566. public function bookmarkDeal($dealId = NULL, $affiliate_id = NULL, $assigner_id = NULL, $affiliate_wallet_id = NULL, $tracker = NULL, $userId = NULL) {
  6567. if ($dealId)
  6568. $Deal = self::dealInfo($dealId);
  6569. else
  6570. $Deal = self::dealInfo($this->dealId);
  6571. if (!$userId)
  6572. $userId = $this->userId;
  6573.  
  6574. $checkMember = CommunityUsers::model()->findByAttributes(array("user_id" => $userId, "community_id" => $Deal->owner->id));
  6575.  
  6576. //if not member; automatically adds
  6577. if (!$checkMember) {
  6578. $role = CommunityRoles::model()->findByAttributes(array('community_id' => $Deal->owner->id, 'role_default' => '1'));
  6579. $roleId = $role->id;
  6580. $modelUsers = new CommunityUsers;
  6581. $modelUsers->user_id = $userId;
  6582. $modelUsers->community_id = $Deal->owner->id;
  6583. $modelUsers->role_id = $roleId;
  6584. $modelUsers->communityuser_status = 1;
  6585. $modelUsers->communityuser_relation = 1;
  6586. $modelUsers->save();
  6587. }
  6588.  
  6589. $user = Users::model()->findByPk($userId);
  6590. //copying to live deal
  6591. $liveDeal = new stdClass();
  6592. $liveDeal->deal_id = new MongoID($this->dealId);
  6593. $liveDeal->title = $Deal->title;
  6594. $liveDeal->type = $Deal->type;
  6595. $liveDeal->description = $Deal->description;
  6596. $liveDeal->hiddenDescription = $Deal->hiddenDescription;
  6597. $liveDeal->status = 7;
  6598. $liveDeal->module = $Deal->module;
  6599.  
  6600. $liveDeal->city = $Deal->city;
  6601. $liveDeal->town = $Deal->town;
  6602. $liveDeal->zipCode = $Deal->zipCode;
  6603. $liveDeal->country = $Deal->country;
  6604. $liveDeal->owner = $Deal->owner;
  6605. $liveDeal->start_date = $Deal->start_date;
  6606. $liveDeal->end_date = $Deal->end_date;
  6607. $liveDeal->date_taken = date('Y-m-d H:i:s');
  6608. $liveDeal->date_redeemed = "";
  6609. $liveDeal->auto = $Deal->auto;
  6610. $liveDeal->visibility = $Deal->visibility;
  6611. $liveDeal->dealinfo = $Deal->dealinfo;
  6612. $liveDeal->tags = $Deal->tags;
  6613. $liveDeal->limits = $Deal->limits;
  6614. $liveDeal->roles = $Deal->roles;
  6615. $liveDeal->total_value = $Deal->total_value;
  6616. $liveDeal->credit_type = $Deal->credit_type;
  6617. $liveDeal->assigner_id = $assigner_id;
  6618. $liveDeal->user_id = intval($userId);
  6619.  
  6620. //user details
  6621. $userInfo = new stdClass;
  6622. $userInfo->id = intval($userId);
  6623. $userInfo->user_firstname = $user->user_firstname;
  6624. $userInfo->user_lastname = $user->user_lastname;
  6625.  
  6626. $liveDeal->userinfo = $userInfo;
  6627.  
  6628. if ($liveDeal->scanCount) {
  6629. $liveDeal->scanCount = $Deal->scanCount;
  6630. }
  6631.  
  6632. if ($liveDeal->scanSchedule) {
  6633. $liveDeal->scanSchedule = $Deal->scanSchedule;
  6634. }
  6635.  
  6636. if ($Deal->methodOfPayment) {
  6637. $liveDeal->methodOfPayment = $Deal->methodOfPayment;
  6638. }
  6639.  
  6640. if ($Deal->digitalDelivery) {
  6641. $liveDeal->digitalDelivery = $Deal->digitalDelivery;
  6642. }
  6643.  
  6644. if ($Deal->pickUpAddress) {
  6645. $liveDeal->pickUpAddress = $Deal->pickUpAddress;
  6646. }
  6647.  
  6648. if ($Deal->price) {
  6649. $liveDeal->price = $Deal->price;
  6650. }
  6651.  
  6652. if ($Deal->multiDelivery) {
  6653. $liveDeal->multiDelivery = $Deal->multiDelivery;
  6654. }
  6655.  
  6656. if ($Deal->affiliate_fee) {
  6657. $liveDeal->affiliate_fee = $Deal->affiliate_fee;
  6658. }
  6659.  
  6660. if ($Deal->rewardinfo) {
  6661. $liveDeal->rewardinfo = $Deal->rewardinfo;
  6662. }
  6663.  
  6664. if ($Deal->paypertake) {
  6665. $liveDeal->paypertake = $Deal->paypertake;
  6666. }
  6667.  
  6668. if ($Deal->payperclick) {
  6669. $liveDeal->payperclick = $Deal->payperclick;
  6670. }
  6671.  
  6672. if ($Deal->bankDeposit) {
  6673. $liveDeal->bankDeposit = $Deal->bankDeposit;
  6674. }
  6675.  
  6676. if ($affiliate_id) {
  6677. //get affiliate info
  6678. $affiliate = Users::model()->findByPk($affiliate_id);
  6679.  
  6680. //set affiliate info
  6681. $affiliateInfo = new stdClass;
  6682. $affiliateInfo->user_id = intval($affiliate_id);
  6683. $affiliateInfo->user_firstname = $affiliate->user_firstname;
  6684. $affiliateInfo->user_lastname = $affiliate->user_lastname;
  6685. if ($Deal->affiliate_fee['wallet_id']) {
  6686. if (in_array($affiliate_wallet_id, $Deal->affiliate_fee['wallet_id'])) {
  6687. $key = array_search($affiliate_wallet_id, $Deal->affiliate_fee['wallet_id']);
  6688.  
  6689. if ($affiliate_wallet_id) {
  6690. $affiliateInfo->wallet_id = intval($affiliate_wallet_id);
  6691. }
  6692. if ($Deal->affiliate_fee['affiliate_price_type'][$key] == 0) {
  6693. $affiliateInfo->amount = ($Deal->affiliate_fee['amount'][$key] * .7);
  6694. $affiliateInfo->systemAmount = ($Deal->affiliate_fee['amount'][$key] * .3);
  6695. } else {
  6696. $affiliateInfo->amount = $Deal->affiliate_fee['amount'][$key] / 100;
  6697. }
  6698. $affiliateInfo->affiliate_price_type = $Deal->affiliate_fee['affiliate_price_type'][$key];
  6699. }
  6700. }
  6701. $liveDeal->affiliate_info = $affiliateInfo;
  6702. }
  6703.  
  6704. //Stamp Deal
  6705. if ($Deal->type == "stamp") {
  6706. $liveDeal->stamp_log = array();
  6707. $liveDeal->stamp_notes = array();
  6708. }
  6709.  
  6710. //Poll/Survey Deal
  6711. if ($Deal->type == "survey") {
  6712. $response = new stdClass;
  6713. $response->status = 0;
  6714. $response->answer = NULL;
  6715. $liveDeal->response = $response;
  6716. }
  6717.  
  6718. //ticket
  6719. if ($Deal->type == "ticket") {
  6720. $purchasedTickets = array('history' => array(), 'tickets' => array());
  6721. $liveDeal->purchasedTickets = $purchasedTickets;
  6722. }
  6723.  
  6724.  
  6725. if ($tracker) {
  6726. if ($Deal->tracker == $tracker) {
  6727. $liveDeal->tracker = $Deal->tracker;
  6728. self::countBookMark($this->dealId, $affiliate_id);
  6729. }
  6730. }
  6731.  
  6732. $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
  6733.  
  6734. if ($liveCollection->insert($liveDeal))
  6735. return true;
  6736. else
  6737. return false;
  6738. }
  6739.  
  6740. public static function checkIfDealIsBookmarkable($dealId, $user = NULL) {
  6741. $collection = Yii::app()->edmsMongoCollection('deals');
  6742.  
  6743. $deal = (object) $collection->findOne(array("_id" => new MongoID($dealId)));
  6744.  
  6745. if ($deal->status == 2 || strtotime(date('Y-m-d')) > strtotime($deal->end_date)) {
  6746. return "expired_deal";
  6747. }
  6748.  
  6749. if ($deal->status != 1) {
  6750. return "cannot_bookmark";
  6751. }
  6752.  
  6753. $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
  6754.  
  6755. if ($user) {
  6756.  
  6757. $deal_count = $liveCollection->find(array("deal_id" => new MongoID($dealId), "user_id" => intval($user), "status" => intval(7)))->count();
  6758. } else {
  6759. $deal_count = $liveCollection->find(array("deal_id" => new MongoID($dealId), "status" => intval(7)))->count();
  6760. }
  6761. if ($deal_count > 0) {
  6762. return "already_bookmarked";
  6763. } else {
  6764. return 0;
  6765. }
  6766. }
  6767.  
  6768. public static function countBookMark($dealId, $affiliate = NULL) {
  6769.  
  6770. $deal = self::dealInfo($dealId);
  6771. $collection = Yii::app()->edmsMongoCollection('deals');
  6772. if ($deal->sharedBookmarkCount) {
  6773. $count = $deal->sharedBookmarkCount + 1;
  6774. } else {
  6775. $count = 1;
  6776. }
  6777. $collection->update(
  6778. array(
  6779. "_id" => new MongoID($dealId),
  6780. ), array('$set' => array("sharedBookmarkCount" => intval($count)))
  6781. );
  6782. return true;
  6783. }
  6784.  
  6785. //get user bookmarked deals of $type
  6786. public function getBookmarkedDeals($type, $id) {
  6787.  
  6788. // pagination
  6789. if (isset($this->pageOffset) && (!is_numeric($this->pageOffset) || $this->pageOffset < 0)) {
  6790. $this->pageOffset = 0;
  6791. }
  6792.  
  6793. if (isset($this->pageCount) && (!is_numeric($this->pageCount) || $this->pageCount < 0)) {
  6794. $this->pageCount = 100;
  6795. }
  6796.  
  6797. $collection = Yii::app()->edmsMongoCollection('deals_live');
  6798. if ($type == 'community')
  6799. $query = array("owner.id" => intval($id), "owner.type" => "community");
  6800. else
  6801. $query = array("user_id" => intval($id));
  6802.  
  6803. //$query["dealinfo.end_event_date"] = array('$gt' => date('Y-m-d'));
  6804.  
  6805. $query['status'] = intval(7);
  6806.  
  6807. //sort by date
  6808. $result = $collection->find($query)->sort(array('start_date' => -1))->skip($this->pageOffset)->limit($this->pageCount);
  6809.  
  6810. $deals = array();
  6811. foreach ($result as $liveDeal) {
  6812.  
  6813. $object = new stdClass;
  6814. $object->deal_id = $liveDeal['deal_id']->__toString();
  6815. $object->title = $liveDeal['title'];
  6816. $object->description = $liveDeal['description'];
  6817. if (strtotime(date('Y-m-d')) > strtotime($liveDeal['end_date']))
  6818. $object->deal_status = self::formatStatus(2);
  6819. else
  6820. $object->deal_status = self::formatStatus($liveDeal['status']);
  6821.  
  6822. $object->userinfo = $liveDeal['userinfo'];
  6823. $object->dealinfo = $liveDeal['dealinfo'];
  6824. $object->roles = $liveDeal['roles'];
  6825. $object->userinfo['status'] = self::formatStatus($liveDeal['status']);
  6826. $object->userinfo['taken_date'] = date("Y-m-d H:i:s", $liveDeal['_id']->getTimestamp());
  6827. $object->owner = $liveDeal['owner'];
  6828.  
  6829. //can take action (add stamp)
  6830. if ($liveDeal['type'] == "stamp") {
  6831. if ($liveDeal['status'] == 1) {
  6832. if ($roleDetails->role_type == 1) {
  6833. //if owner
  6834. $object->can_take_action = true;
  6835. } else if ($roleDetails->role_type == 2) {
  6836. //If a staff member is trying to take action
  6837. if (in_array($roleDetails->role_id, $liveDeal['roles']['redeem'])) {
  6838. $object->can_take_action = true;
  6839. }
  6840. } else {
  6841. //if member
  6842. if ($liveDeal['dealinfo']['take_action']) {
  6843. $object->can_take_action = true;
  6844. }
  6845. }
  6846. }
  6847. }
  6848.  
  6849. //show ticket and transaction details
  6850. if ($liveDeal['type'] == "ticket") {
  6851. if ($liveDeal['price']) {
  6852. $object->price = $liveDeal['price'];
  6853. }
  6854. if ($liveDeal['purchasedTickets']) {
  6855. $object->purchasedTickets = $liveDeal['purchasedTickets'];
  6856. }
  6857. if ($liveDeal['scanCount']) {
  6858. $object->scanCount = $liveDeal['scanCount'];
  6859. }
  6860. if ($liveDeal['scanSchedule']) {
  6861. $object->scanSchedule = $liveDeal['scanSchedule'];
  6862. }
  6863. }
  6864.  
  6865. //can redeem
  6866. $object->can_redeem = false;
  6867. if ($liveDeal['status'] == 3) {
  6868. if ($roleDetails->role_type == 1) {
  6869. //if owner
  6870. $object->can_redeem = true;
  6871. } else if ($roleDetails->role_type == 2) {
  6872. //if staff
  6873. if (in_array($roleDetails->role_id, $liveDeal['roles']['redeem'])) {
  6874. $object->can_redeem = true;
  6875. }
  6876. } else {
  6877. //if member
  6878. if ($liveDeal['rewardinfo']['self_redeem']) {
  6879. $object->can_redeem = true;
  6880. }
  6881. }
  6882. }
  6883.  
  6884. $deals[] = $object;
  6885. }
  6886. return $deals;
  6887. }
  6888.  
  6889. public static function countActiveBookmarks($dealId) {
  6890. $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
  6891. $liveCount = $liveCollection->find(array("deal_id" => new MongoID($dealId), "status" => intval(7)))->count();
  6892.  
  6893. return $liveCount;
  6894. }
  6895.  
  6896. public static function getRemainingUserTicketLimit($dealId, $index, $userId) {
  6897. $deal = self::dealInfo($dealId);
  6898. $liveDeal = self::liveDealInfo($dealId, $userId);
  6899. $limit = $deal->price['options'][$index]['limit'];
  6900. if ($liveDeal) {
  6901. $tickets = $liveDeal->purchasedTickets['tickets'];
  6902. $counter = 0;
  6903. for ($i = 0; $i < sizeOf($tickets); $i++) {
  6904.  
  6905. if ($tickets[$i]['index'] == $index) {
  6906. $counter++;
  6907. }
  6908. }
  6909. $balance = $limit - $counter;
  6910. } else {
  6911. $balance = $limit;
  6912. }
  6913. return $balance;
  6914. }
  6915.  
  6916. public static function getRemainingTicketQuantity($dealId, $index) {
  6917. $deal = self::dealInfo($dealId);
  6918. return $deal ? $deal->price['options'][$index]['quantity'] : 0;
  6919. }
  6920.  
  6921. public static function getRemainingLimitForTicket($id, $optionLimit, $index) {
  6922. $liveDeal = self::liveDealInfo($dealId, $userId);
  6923. if ($live) {
  6924. $tickets = $liveDeal->purchasedTickets['tickets'];
  6925. $counter = 0;
  6926. for ($i = 0; $i < sizeOf($tickets); $i++) {
  6927.  
  6928. if ($tickets[$i]['index'] == $index) {
  6929. $counter++;
  6930. }
  6931. }
  6932. $limit = $optionLimit - $counter;
  6933. } else {
  6934. $limit = $optionLimit;
  6935. }
  6936.  
  6937. return $limit;
  6938. }
  6939.  
  6940. public static function getRemainingLimitForFree($id, $optionLimit) {
  6941. $liveDeal = self::liveDealInfo($dealId, $userId);
  6942. if ($live) {
  6943. $tickets = $liveDeal->purchasedTickets['tickets'];
  6944. $counter = 0;
  6945. for ($i = 0; $i < sizeOf($tickets); $i++) {
  6946. $counter++;
  6947. }
  6948. $limit = $optionLimit - $counter;
  6949. if ($limit <= 0) {
  6950. $limit = 0;
  6951. }
  6952. } else {
  6953. $limit = $optionLimit;
  6954. }
  6955.  
  6956. return $limit;
  6957. }
  6958.  
  6959. public function assignTicket($userId) {
  6960. $cart_tickets = $this->tickets;
  6961. $dealId = $this->dealId;
  6962. $ticket_index = array_keys($cart_tickets);
  6963. $ticket_count = array_values($cart_tickets);
  6964. $quantity = array_sum($cart_tickets);
  6965.  
  6966. $collection_permission = Yii::app()->edmsMongoCollection('deals');
  6967. $permitted = $collection_permission->findOne(array("_id" => new MongoId($dealId), "owner.id" => intval($this->communityId)));
  6968.  
  6969. if (!$permitted) {
  6970. throw new CHttpException(403, 'permission_denied');
  6971. }
  6972.  
  6973. $count = 0;
  6974. foreach ($ticket_index as $index) {
  6975. //check limit of user to buy
  6976. $balance = SELF::getRemainingUserTicketLimit($dealId, $index, $userId);
  6977. if ($balance < $ticket_count[$count]) {
  6978. throw new CHttpException(403, 'user_limit_reached_for_ticket(s)');
  6979. }
  6980. //check enough quantity to buy
  6981. $balance_qty = SELF::getRemainingTicketQuantity($dealId, $index);
  6982. if ($balance_qty < $ticket_count[$count])
  6983. throw new CHttpException(403, 'not_enough_tickets_to_buy)');
  6984.  
  6985. $count++;
  6986. }
  6987. $deal_status = 8;
  6988. if ($this->paid == 'no') {
  6989. $payment_status = 'no';
  6990. $paid_using = 'pickup';
  6991. } else {
  6992. $payment_status = 'yes';
  6993. $paid_using = 'assign';
  6994. }
  6995.  
  6996. $collection = Yii::app()->edmsMongoCollection('deals');
  6997. $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
  6998. $livePurchasedTicket = self::liveDealInfo($dealId, $userId);
  6999. $deal = self::dealInfo($dealId);
  7000.  
  7001. //affiliate
  7002. $affiliateId = NULL;
  7003. $affiliateWalletId = NULL;
  7004.  
  7005. if (!$livePurchasedTicket) {
  7006. //initialize bookmark of event
  7007. SELF::bookmarkDeal($dealId, $affiliateId, NULL, $affiliateWalletId, NULL, $userId);
  7008. $purchasedTickets = array('history' => array(), 'tickets' => array());
  7009. } else {
  7010. $purchasedTickets = $livePurchasedTicket->purchasedTickets;
  7011. }
  7012. if (!$this->visitor_details) {
  7013. //get user info
  7014. $user_details = Users::model()->findByPk($userId);
  7015. $user['fname'] = $user_details['user_firstname'];
  7016. $user['lname'] = $user_details['user_lastname'];
  7017. $user['mname'] = '';
  7018. $user['email'] = $user_details['user_email'];
  7019. $user['number'] = $user_details['user_mobile'];
  7020. } else
  7021. $user = $this->visitor_details;
  7022.  
  7023. $transaction_id = uniqid() . rand(10 * 45, 100 * 98);
  7024. $purchaseDetails = array(
  7025. 'transaction_code' => $transaction_id,
  7026. 'date_purchased' => date('Y-m-d H:i:s A'),
  7027. 'quantity' => $quantity,
  7028. 'paid' => $payment_status,
  7029. 'paidUsing' => $paid_using
  7030. );
  7031. $totalAmount = 0;
  7032.  
  7033. for ($i = 0; $i < sizeOf($ticket_index); $i++) {
  7034. if ($ticket_count[$i] > 0) {
  7035. for ($counter = 0; $counter < $ticket_count[$i]; $counter++) {
  7036. $ticket_id = uniqid() . rand(10 * 45, 100 * 98);
  7037. $ticket = array(
  7038. 'id' => $ticket_id,
  7039. 'index' => $ticket_index[$i],
  7040. 'used' => 'no',
  7041. 'category' => $deal->price['options'][$ticket_index[$i]]['category'],
  7042. 'transaction' => $transaction_id,
  7043. 'first_name' => $user['fname'],
  7044. 'middle_name' => $user['mname'],
  7045. 'last_name' => $user['lname'],
  7046. 'email' => $user['email'],
  7047. 'contact' => $user['number']
  7048. );
  7049. array_push($purchasedTickets['tickets'], $ticket);
  7050. }
  7051. if ($deal->price['options'][$ticket_index[$i]]['quantity'] != "") {
  7052. $deal->price['options'][$ticket_index[$i]]['quantity'] -= $ticket_count[$i];
  7053. }
  7054. }
  7055. }
  7056. array_push($purchasedTickets['history'], $purchaseDetails);
  7057. $collection->update(
  7058. array(
  7059. "_id" => new MongoID($dealId),
  7060. ), array('$set' => array("price" => $deal->price))
  7061. );
  7062. $liveCollection->update(
  7063. array(
  7064. "deal_id" => new MongoID($dealId),
  7065. "user_id" => intval($userId),
  7066. ), array('$set' => array("status" => intval($deal_status), "price" => $deal->price, "purchasedTickets" => $purchasedTickets))
  7067. );
  7068. return $result['transaction_id'] = $transaction_id;
  7069. }
  7070.  
  7071. public static function getPaymentMethods($dealId) {
  7072. $deal = Yii::app()->edmsMongoCollection('deals');
  7073. $details = (array) $deal->findOne(array("_id" => new MongoID($dealId)));
  7074. if ($details['price']['type'] == 'wallet') {
  7075. if ($details && sizeOf($details['methodOfPayment']['method']) > 0)
  7076. return $result = SELF::formatPaymentMethod($details['methodOfPayment']['method']);
  7077. else
  7078. return false;
  7079. }
  7080. else if ($details['price']['type'] == 'rewards') {
  7081. return 'community_points';
  7082. } else if ($details['price']['type'] == 'others') {
  7083. return $details['price']['otherPayment'];
  7084. } else
  7085. return false;
  7086. }
  7087.  
  7088. /* public function getUnpaidTickets(){
  7089. $collectionLive = Yii::app()->edmsMongoCollection('deals_live');
  7090. $tickets = $collectionLive->find(array("deal_id" => new MongoID($this->dealId),"owner.id" => intval($this->communityId), "purchasedTickets.history.paid" => "no"));
  7091. $parsedDeals = array();
  7092. $i = 0;
  7093. foreach($tickets as $ticket){
  7094. $parsedDeals[$i]['deal_id'] = $ticket['deal_id'];
  7095. $parsedDeals[$i]['userinfo'] = $ticket['userinfo'];
  7096. $parsedDeals[$i]['price'] = $ticket['price'];
  7097. $j = 0;
  7098. foreach($ticket['purchasedTickets']['history'] as $history){
  7099. if($history['paid'] == 'no'){
  7100. $transaction_id = $history['transaction_code'];
  7101. $parsedDeals[$i]['purchasedTickets']['history'][$j] = $history;
  7102. $k = 0;
  7103. foreach($ticket['purchasedTickets']['tickets'] as $tickets){
  7104. if($tickets['transaction'] == $transaction_id){
  7105. $parsedDeals[$i]['purchasedTickets']['tickets'][] = $tickets;
  7106. }
  7107. $k++;
  7108. }
  7109.  
  7110. }
  7111. $j++;
  7112. }
  7113. //$parsedDeals[$i]['purchasedTickets']= $ticket['purchasedTickets'];
  7114. $i++;
  7115. }
  7116. } */
  7117.  
  7118. //for all e-commerce deals exluding tickets.
  7119. public function dealTransaction($params) {
  7120. $collection = Yii::app()->edmsMongoCollection('deals_live');
  7121.  
  7122. $query = array();
  7123. $query["paid"] = array('$exists' => false);
  7124. $query["deal_id"] = new MongoID($params['deal_id']);
  7125. $query['module'] = 'ecommerce';
  7126. $query["userinfo.id"] = intval($this->userId);
  7127.  
  7128. $deal = $collection->findOne($query);
  7129. $paid = 'no';
  7130. if ($deal) {
  7131. if (!(in_array($params['payment_method'], $deal['methodOfPayment']['method']))) {
  7132. $result['error'] = "payment_method_not_available";
  7133. return $result;
  7134. }
  7135.  
  7136. //tagcash payment
  7137. if (intval($params['payment_method']) == 1) {
  7138. $wallet_id = $deal['price']['wallet_id'];
  7139. $amount = $deal['price']['amount'];
  7140. $narration = "Payment for taking Tagvert ID: <a href='http://tagbond.local/tagvert/details/" . $filter['deal_id'] . "'>" . $filter['deal_id'] . "</a>";
  7141.  
  7142. $stat = Deals::transferPayment($amount, $this->userId, 1, $deal['owner']['id'], 2, $wallet_id, $narration);
  7143. if ($stat) {
  7144. $paid_using = "wallet";
  7145. $paid = 'yes';
  7146. } else {
  7147. $result['error'] = "error_occured_or_insufficient_balance";
  7148. return $result;
  7149. }
  7150. }
  7151.  
  7152. //Cash on Pickup
  7153. else if (intval($params['payment_method']) == 2) {
  7154. $paid_using = "COD";
  7155. }
  7156.  
  7157. //paypal
  7158. else if (intval($params['payment_method']) == 3) {
  7159. $paid_using = "Paypal";
  7160. }
  7161.  
  7162. //creditCard : DragonPay
  7163. else if (intval($params['payment_method']) == 4) {
  7164. $paid_using = "Dragonpay";
  7165. } else {
  7166. $paid_using = "Others";
  7167. }
  7168.  
  7169. $collection->update(
  7170. array(
  7171. "_id" => new MongoID($deal['_id']),
  7172. ), array('$set' => array("orderedDate" => date("Y-m-d H:i:s"), "paid" => $paid, "paidUsing" => $paid_using, "orderItemCount" => intval(1)))
  7173. );
  7174. return "transaction_successfull";
  7175. } else {
  7176. $result['error'] = "invalid_live_deal";
  7177. return $result;
  7178. }
  7179. }
  7180.  
  7181. public static function changeQRCode($id) {
  7182. $collection = Yii::app()->edmsMongoCollection('deals');
  7183. $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
  7184. $newCode = rand();
  7185. $collection->update(
  7186. array("_id" => new MongoID($id)), array('$set' => array("dealinfo.code" => $newCode))
  7187. );
  7188.  
  7189. $liveCollection->update(
  7190. array("deal_id" => new MongoID($id)), array('$set' => array("dealinfo.code" => $newCode))
  7191. );
  7192.  
  7193. return true;
  7194. }
  7195.  
  7196. public static function changeLiveDealPriority($status, $dealId, $communityId) {
  7197. //0 - urgent 1 - non urgent
  7198. if ($status == 1 || $status == 0) {
  7199. $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
  7200. $stat = $liveCollection->update(
  7201. array("deal_id" => new MongoID($dealId),
  7202. "owner.id" => intval($communityId),
  7203. "owner.type" => "community"), array('$set' => array("priority" => $status))
  7204. );
  7205. if ($stat) {
  7206. if ($status == 1) {
  7207. //if catalog, relase payment if any
  7208. $result = $liveCollection->findOne(
  7209. array("deal_id" => new MongoID($dealId),
  7210. "owner.id" => intval($communityId),
  7211. "owner.type" => "community"));
  7212. if ($stat['type'] == 'catalog') {
  7213. //relaease payment
  7214. }
  7215. }
  7216. return true;
  7217. } else
  7218. return false;
  7219. }
  7220. return false;
  7221. }
  7222.  
  7223. public function getCatalogItems($params, $itemsonly = false, $search = false) {
  7224. $collection = Yii::app()->edmsMongoCollection('deals');
  7225. $deal = $collection->findOne(array("_id" => new MongoID($params['deal_id'])));
  7226. $items = array();
  7227. if ($deal && $deal['items']) {
  7228. $catalogImages = new CatalogImages;
  7229. foreach ($deal['items'] as $item) {
  7230. if ($search) {
  7231. if ($params['catalog_name'] && $item['catalog_name']) {
  7232. $pos = strpos(strtolower($item['catalog_name']), strtolower($params['catalog_name']));
  7233. if ($pos === false)
  7234. continue;
  7235. }
  7236.  
  7237. if ($params['category_id'] > 0) {
  7238. if ($item['category']['id'] != $params['category_id'])
  7239. continue;
  7240. }
  7241. }
  7242. if ($itemsonly)
  7243. $items[] = $item['id'];
  7244. else {
  7245. $item_details = SELF::formatItemDetails($item['id']);
  7246. if (empty($item['category'])) {
  7247. $item_details['category']['id'] = 0;
  7248. $item_details['category']['name'] = '';
  7249. }
  7250. $item['price']['wallet'] = $item['price']['wallet_name'];
  7251. unset($item['price']['wallet_name']);
  7252. $image = $catalogImages->getCatalogImages($item['id']);
  7253. $item_details['image'] = $image ? $image : array();
  7254. if (!$this->communityId)
  7255. $item_details['favorite'] = FavoriteCatalogs::checkFavourite($this->userId, $params['deal_id'], $item['id']);
  7256. $items[] = $item_details;
  7257. }
  7258. }
  7259. }
  7260. return $items;
  7261. }
  7262.  
  7263. public function getSlotDeals($params, $imageOnly = false) {
  7264. //offset wont work isnce image checking is enabled
  7265. if (!$params['count'] || $params['count'] < 0)
  7266. $count = 0;
  7267. else
  7268. $count = $params['count'];
  7269.  
  7270. if (!$params['offset'] || $params['offset'] < 0)
  7271. $offset = 100;
  7272. else
  7273. $offset = $params['offset'];
  7274.  
  7275. $result = array();
  7276. $query = array();
  7277. $query['status'] = intval(1);
  7278. $query['country.id'] = intval($params['country_id']);
  7279. $query['end_date'] = array('$gte' => date('Y-m-d'));
  7280.  
  7281. //only coupon tagverts now
  7282. $query['type'] = 'coupon';
  7283.  
  7284. //disbale for testing. need to uncomment below two lines when goes live
  7285. $query["game_slots.status"] = intval(1);
  7286. $query["game_slots.limit"] = array('$gt' => intval(0));
  7287. $collection = Yii::app()->edmsMongoCollection('deals');
  7288.  
  7289. //random result
  7290. $array_key = array('_id', 'title', 'description', 'start_date', 'end_date', 'country.id', 'type');
  7291. $array_sort = array(1, -1);
  7292. $rand_sort = $array_sort[array_rand($array_sort)];
  7293. $rand_sort1 = $array_sort[array_rand($array_sort)];
  7294. $rand1 = $array_key[array_rand($array_key)];
  7295. $rand = $array_key[array_rand($array_key)];
  7296. if ($rand)
  7297. $sort[$rand] = $rand_sort;
  7298. if ($rand1)
  7299. $sort[$rand1] = $rand_sort1;
  7300.  
  7301. $deals = $collection->find($query)
  7302. ->sort($sort);
  7303. /* ->skip($offset)
  7304.  
  7305. ->limit($count); */
  7306. if ($deals) {
  7307.  
  7308. $details = array();
  7309. foreach ($deals as $deal) {
  7310. if (!$imageOnly) {
  7311. $detail['id'] = $deal['_id']->__toString();
  7312. $detail['title'] = $deal['title'];
  7313. $detail['link'] = Yii::app()->params['site_url'] . "/d/" . $detail['id'];
  7314. }
  7315. $tFilePath = 'uploads/tagverts/thumbnail_1';
  7316. $tFileName = 'd_' . $detail['id'] . '.png';
  7317. $tresultS3 = Yii::app()->tamazon->isObjectExist($tFilePath, $tFileName);
  7318. if (!$tresultS3) {
  7319. $tFileName = 'd_' . $detail['id'] . '.jpg';
  7320. $tresultS3 = Yii::app()->tamazon->isObjectExist($tFilePath, $tFileName);
  7321. }
  7322. $detail['image_url'] = "";
  7323. if (!$tresultS3) {
  7324. //hinding temporarly
  7325. /* $filePath = 'uploads/tagverts';
  7326. $fileName = 'd_'.$detail['id'].'.png';
  7327. $resultS3 = Yii::app()->tamazon->isObjectExist($filePath, $fileName);
  7328. if(!$resultS3){
  7329. $fileName = 'd_'.$detail['id'].'.jpg';
  7330. $resultS3 = Yii::app()->tamazon->isObjectExist($filePath, $fileName);
  7331. if(!$resultS3) */
  7332. continue;
  7333. /* }
  7334. $imageDataS3 = Yii::app()->tamazon->getObject($filePath, $fileName);
  7335. $imageData = UserImages::createThumb($imageDataS3['Body'], 40, 40);
  7336. $uResultS3 = Yii::app()->tamazon->uploadObject($tFilePath, $tFileName, $imageData); */
  7337. }
  7338. $detail['image_url'] = sprintf('http://%s.s3.amazonaws.com/uploads/tagverts/thumbnail_1/%s', Yii::app()->tamazon->bucketRoot, $tFileName);
  7339. $result[] = $detail;
  7340. if (sizeof($result) == $count)
  7341. break;
  7342. }
  7343. return $result;
  7344. }
  7345. }
  7346.  
  7347. public function paymentCheckout($data) {
  7348. $criteria = new CDbCriteria;
  7349. $criteria->select = 'community_id, stock, price, price_wallet, email, catalog_name';
  7350. $transaction = Yii::app()->db->beginTransaction();
  7351. $cart = json_decode($data['item']);
  7352. $purchased_item_ids = array();
  7353. $global_items_ids = array();
  7354. $total_delivery = 0;
  7355. $collection = Yii::app()->edmsMongoCollection('deals');
  7356. $order_id = $this->userId . time();
  7357. foreach ($cart as $catalog_id => $catalog) {
  7358. $catalog_wise_purchased_item_ids = array();
  7359. $deal = $collection->findOne(array("_id" => new MongoID($catalog_id)));
  7360. if (!$deal)
  7361. throw new CHttpException(403, "invalid_deal");
  7362. $items = $deal['items'];
  7363. $delivery_charge = $deal['delivery_options']['amount'];
  7364. $items_ids = array();
  7365. foreach ($items as $item) {
  7366. $items_ids[] = $item['id'];
  7367. $catalog_details = Catalog::model()->findByPk($item['id'], $criteria);
  7368. $item_details[$item['id']]['stock'] = intval($catalog_details['stock']);
  7369. $item_details[$item['id']]['price'] = $catalog_details['price'];
  7370. $item_details[$item['id']]['wallet_id'] = $catalog_details['price_wallet'];
  7371. $item_details[$item['id']]['delivery_amount'] = $deal['delivery_options']['amount'];
  7372. $item_details[$item['id']]['delivery_wallet_id'] = $deal['delivery_options']['wallet_id'];
  7373. $item_details[$item['id']]['email'] = $catalog_details['email'];
  7374. $item_details[$item['id']]['name'] = $catalog_details['catalog_name'];
  7375. $item_details[$item['id']]['community_id'] = $catalog_details['community_id'];
  7376. }
  7377.  
  7378. foreach ($catalog as $cart_details) {
  7379. $cart_item_id = $cart_details->item;
  7380. $global_items_ids[$cart_item_id] += $cart_details->count;
  7381.  
  7382. $emaildata['item_id'] = $cart_item_id;
  7383. $emaildata['item_name'] = $item_details[$cart_item_id]['name'];
  7384. $emaildata['email'] = $item_details[$cart_item_id]['email'];
  7385. $emaildata['quantity'] = $global_items_ids[$cart_item_id];
  7386. $emaildata['price'] = $item_details[$cart_item_id]['price'];
  7387. $emaildata['community_id'] = $item_details[$cart_item_id]['community_id'];
  7388. $emailinfo[] = $emaildata;
  7389. //this is for checking item exists as well as stock. if no item, 'if' succeed
  7390. if ($cart_details->count > $item_details[$cart_item_id]['stock']) {
  7391. $response['result']['error'] = 'insufficient_stock';
  7392. $response['result']['values'] = array('item_id' => $cart_item_id, 'stock' => $item_details[$cart_item_id]['stock']);
  7393. $response['status'] = 'failed';
  7394. Rest::sendResponse(403, json_encode($response, JSON_NUMERIC_CHECK));
  7395. } else {
  7396. $merchant_pay[$deal['owner']['id']] += ($item_details[$cart_item_id]['price'] * $cart_details->count);
  7397. $total_amount += ($item_details[$cart_item_id]['price'] * $cart_details->count);
  7398. $item_wallets[$item_details[$cart_item_id]['wallet_id']] = $item_details[$cart_item_id]['wallet_id'];
  7399. }
  7400. }
  7401. $items_missing = array_diff($catalog_wise_purchased_item_ids, $items_ids);
  7402. if (sizeof($items_missing) > 0) {
  7403. $miss_details[$catalog_id] = $items_missing;
  7404. $response['result']['error'] = 'items_does_not_exists';
  7405. $response['result']['values'] = $miss_details;
  7406. $response['status'] = 'failed';
  7407. Rest::sendResponse(403, json_encode($response, JSON_NUMERIC_CHECK));
  7408. }
  7409. $merchant_pay[$deal['owner']['id']] += $delivery_charge;
  7410. $total_amount += $delivery_charge;
  7411. $total_delivery += $delivery_charge;
  7412. }
  7413. $item_wallets = array_values($item_wallets);
  7414. if (sizeof($item_wallets) > 1)
  7415. throw new CHttpException(403, "clubbing_multiple_currencies_not_available");
  7416.  
  7417. foreach ($global_items_ids as $item => $count) {
  7418. if ($count > $item_details[$item]['stock']) {
  7419. $response['result']['error'] = 'insufficient_stock';
  7420. $response['result']['values'] = array('item_id' => $item, 'stock' => $item_details[$item]['stock']);
  7421. $response['status'] = 'failed';
  7422. Rest::sendResponse(403, json_encode($response, JSON_NUMERIC_CHECK));
  7423. }
  7424. if ($item_details[$item]['delivery_amount'] > 0) {
  7425. if ($item_wallets[0] != $item_details[$item]['delivery_wallet_id']) {
  7426. $response['result']['error'] = 'delivery_not_available';
  7427. $response['result']['values'] = array('item_id' => $item, 'delivery_wallet_id' => $item_details[$item]['delivery_wallet_id']);
  7428. $response['status'] = 'failed';
  7429. Rest::sendResponse(403, json_encode($response, JSON_NUMERIC_CHECK));
  7430. }
  7431. }
  7432. }
  7433. //amount sent is differnt from actual amount
  7434. if ($total_amount != $data['amount'])
  7435. throw new CHttpException(403, "item_or_delivery_amount_changed");
  7436.  
  7437. $response = array();
  7438. //validations OK. process payment
  7439. if ($data['payment_method'] == 'tagcash') {
  7440. $stat = 0;
  7441. $data['ref_id'] = 1;
  7442. if ($data['amount'] > 0) {
  7443. $result = $this->itemPurchasePayment($merchant_pay, $this->userId, $item_wallets[0], $order_id);
  7444. if ($result) {
  7445. $data['ref_id'] = $response['reference_id'] = $result;
  7446. $stat = 1;
  7447. } else
  7448. return false;
  7449. }
  7450. }
  7451.  
  7452. if ($data['payment_method'] == 'bank') {
  7453. $data['payment_details'] = json_decode($data['payment_details'], true);
  7454. $stat = 0;
  7455. if ($data['payment_details']['bank_code'] && $data['payment_details']['banking_method'] && $data['payment_details']['date'] && $data['payment_details']['time']) {
  7456. if (Banks::isExisting($data['payment_details']['bank_code'])) {
  7457. $response['status'] = "success";
  7458. $txn = new PayTransactions('initial');
  7459. $txn->refno = uniqid(rand(10 * 45, true));
  7460. $txn->txnid = (isset($data['payment_details']['transaction_id'])) ? $data['payment_details']['transaction_id'] : rand() . time();
  7461. $txn->depositor_id = 2;
  7462. $txn->depositor_type = 2;
  7463. $txn->email = $this->user->user_email;
  7464. $txn->amount = array_sum($merchant_pay);
  7465. $txn->currency = "PHP";
  7466. $txn->status = "P";
  7467. $txn->digest = sha1($txn->depositor_id . ':' . $txn->depositor_type . ':' . $txn->txnid . ':' . $txn->email . ':' . $txn->currency);
  7468. $txn->proc_id = ($data['payment_details']['banking_method'] == "otc") ? $data['payment_details']['bank_code'] . "X" : $data['payment_details']['bank_code'] . "C";
  7469. $txn->agree_to_terms = 1;
  7470. if ($txn->validate() && $txn->save()) {
  7471. $deposit = DepositConfirmations::model()->findByAttributes(array('refno' => $txn->txnid));
  7472. $txnDate = explode(' ', $data['payment_details']['date']);
  7473. $model = new DepositConfirmations;
  7474. $model->refno = $txn->refno;
  7475. $model->amount = $txn->amount;
  7476. $model->txnid = $txn->txnid;
  7477. $model->date = date('Y-m-d', strtotime($data['payment_details']['date']));
  7478. $model->time = $data['payment_details']['time'];
  7479. if ($model->validate() && $model->save()) {
  7480. /* notify admin */
  7481. $txnDetails = PayTransactions::getData($txn->refno);
  7482. $settings = array(
  7483. 'view' => 'notify',
  7484. 'subject' => "TAGPay Request",
  7485. );
  7486. $emaildata = array(
  7487. 'email' => "accounts@tagcash.com",
  7488. 'data' => $txnDetails,
  7489. );
  7490.  
  7491. $mail = new TagbondMail;
  7492. $mail->sendTagbondMail($settings, $emaildata);
  7493. }
  7494. $data['ref_id'] = $response['reference_id'] = $txn->refno;
  7495. if (SELF::updateItemPurchaseMerchantPayments($merchant_pay, 3, $item_wallets[0], $data['ref_id'], $order_id))
  7496. $stat = 1;
  7497. else
  7498. return false;
  7499. }
  7500. }else {
  7501. throw new CHttpException(403, "bank_not_found");
  7502. }
  7503. } else {
  7504. throw new CHttpException(403, "missing_payment_details");
  7505. }
  7506. }
  7507.  
  7508. if ($data['payment_method'] == '7connect') {
  7509. $stat = 0;
  7510. $modelCliqq = new CliqqLog;
  7511. $settings = SiteSettings::getSettings();
  7512. $transactURL = $this->thisObj->_SETTINGS->{'7Connect_turl'};
  7513. $transactionKey = $this->thisObj->_SETTINGS->{'7Connect_transactionkey'};
  7514. $merchantId = $this->thisObj->_SETTINGS->{'7Connect_merchantId'};
  7515. $merchantRef = rand() . time();
  7516. $successURL = Yii::app()->createAbsoluteUrl('credit/saveCliqqStatus', array('access_token' => $_POST['access_token']));
  7517. $failURL = Yii::app()->createAbsoluteUrl('credit/saveCliqqStatus', array('access_token' => $_POST['access_token']));
  7518. $token = sha1($merchantId . $merchantRef . '{' . $transactionKey . '}');
  7519.  
  7520. $modelCliqq->user_id = 2;
  7521. $modelCliqq->user_type = 2;
  7522. $modelCliqq->website = 2;
  7523. $modelCliqq->wallet_id = 1;
  7524. $modelCliqq->amount = array_sum($merchant_pay);
  7525. $modelCliqq->reference_id = $merchantRef;
  7526.  
  7527. if ($modelCliqq->save()) {
  7528. $fields = array(
  7529. 'merchantID' => $merchantId,
  7530. 'merchantRef' => $merchantRef,
  7531. 'amount' => array_sum($merchant_pay),
  7532. 'successURL' => $successURL,
  7533. 'failURL' => $failURL,
  7534. 'token' => $token,
  7535. 'transactionDescription' => 'Tagcash Deposit via 7connect - ' . array_sum($merchant_pay),
  7536. 'returnPaymentDetails' => 'Y'
  7537. );
  7538.  
  7539. $params = http_build_query($fields);
  7540. $response['link'] = $transactURL . '?' . $params;
  7541. $response['reference_id'] = $merchantRef;
  7542. $data['ref_id'] = $merchantRef;
  7543. if (SELF::updateItemPurchaseMerchantPayments($merchant_pay, 2, $item_wallets[0], $merchantRef, $order_id))
  7544. $stat = 1;
  7545. else
  7546. return false;
  7547. }
  7548. else {
  7549. return false;
  7550. }
  7551. }
  7552.  
  7553. if ($data['payment_method'] == 'agent') {
  7554. $stat = 0;
  7555. $agentObj = new PaybyagentLog();
  7556. $agentObj->setIdentity($this->thisObj);
  7557. foreach ($merchant_pay as $merchant_id => $amount) {
  7558. $log['beneficiary_id'] = $merchant_id;
  7559. $log['beneficiary_type'] = 2;
  7560. $log['wallet_id'] = $item_wallets[0];
  7561. $log['amount'] = $amount;
  7562. $log['custom'] = 'catalog purchase';
  7563. $logs[] = $log;
  7564. }
  7565. $agent_ref = $agentObj->logTransaction($logs, true);
  7566. if ($agent_ref) {
  7567. if (SELF::updateItemPurchaseMerchantPayments($merchant_pay, 4, $item_wallets[0], $agent_ref, $order_id)) {
  7568. $stat = 1;
  7569. $data['ref_id'] = $response['reference_id'] = $agent_ref;
  7570. } else
  7571. return false;
  7572. } else
  7573. return false;
  7574. }
  7575. if ($stat === 1) {
  7576. foreach ($cart as $catalog_id => $catalog) {
  7577. $deal_data = array();
  7578. $deal_data['purchased_items'] = $catalog;
  7579. $deal_data['delivery_address'] = $data['delivery_address'];
  7580. $deal_data['amount'] = $data['amount'] ? $data['amount'] : 0;
  7581. if ($deal_data['delivery_method']) {
  7582. $deal_data['delivery_method']['method'] = $data['delivery_method'];
  7583. }
  7584. $deal_data['payment_method'] = $data['payment_method'];
  7585. $deal_data['transaction_id'] = $data['ref_id'];
  7586. $deal_data['wallet_id'] = $item_wallets[0];
  7587. $deal_data['order_id'] = $order_id;
  7588. $deal_stat = Deals::takeDeal($catalog_id, NULL, NULL, $deal_data);
  7589. }
  7590. foreach ($global_items_ids as $item => $count) {
  7591. SELF::updateStock($item, $count);
  7592. }
  7593. if ($transaction) {
  7594. $transaction->commit();
  7595. }
  7596. $response['order_id'] = $order_id;
  7597. //send GCM notification
  7598. //send notifiction to user who placed the order
  7599. $message = array(
  7600. 'message' => 'Your catalog purchase order on Miskio is confirmed #' . $order_id,
  7601. 'user_id' => $this->user->id,
  7602. 'user_type' => 1,
  7603. 'notification_type' => 17,
  7604. 'count' => 1
  7605. //'vibrate' => 1,
  7606. //'sound' => 1
  7607. );
  7608. //sendMessage
  7609. Gcm::sendMessage($message);
  7610.  
  7611. //send order details - email
  7612. //email to user and item owner
  7613. $user_email = $this->user->user_email;
  7614. $user_settings = array(
  7615. 'view' => 'common',
  7616. 'subject' => 'Your order is confirmed #' . $order_id
  7617. );
  7618. $user_body = '
  7619. Thank you for placing an order with ' . $this->thisObj->_CLIENTDETAILS['name'] . '!<br/><br/>Order Id : #' . $order_id . '<br/><br/>
  7620. <table width="100%" cellpadding="5">
  7621. <tr bgcolor="#eb3f3c">
  7622. <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>
  7623. </tr>
  7624. ';
  7625. $settings = array(
  7626. 'view' => 'common',
  7627. 'subject' => 'New purchase order #' . $order_id
  7628. );
  7629. $gross = 0;
  7630. $wallet = WalletTypes::getWalletName($item_wallets[0], true);
  7631. foreach ($emailinfo as $iteminfo) {
  7632. if ($iteminfo['email']) {
  7633. $body = 'One of the user has placed an order!<br/><br/>
  7634. <table width="100%"><tr><td width="25%">
  7635. Order Id </td><td>' . $order_id . '</td></tr>';
  7636. $body .= '<tr><td>Item </td><td> ' . $iteminfo['item_name'] . '(#' . $iteminfo['item_id'] . ')</td></tr>
  7637. <tr><td>Quantity </td><td> ' . $iteminfo['quantity'] . '</td></tr>
  7638. <tr><td>User </td><td> ' . $this->user->user_firstname . ' ' . $this->user->user_lastname . '</td></tr>
  7639. <tr><td>Delivery Address </td><td> ' . $data['delivery_address'] . '</td></tr>
  7640. <tr><td><b>Payment details</b></td></tr>
  7641. <tr><td>Payment method</td><td> ' . $data['payment_method'] . '</td></tr>
  7642. <tr><td>Transaction Id</td><td>' . $data['ref_id'] . '</td></tr>';
  7643. if ($data['payment_method'] == 'bank')
  7644. $body .= '<tr><td></td><td>' . $data['payment_details'] . '</td></tr><tr><td></td></tr>';
  7645.  
  7646. $body .='</table>';
  7647. $data_arr = array(
  7648. 'email' => $iteminfo['email'],
  7649. 'head' => $this->thisObj->_CLIENTDETAILS['name'],
  7650. 'message' => $body
  7651. );
  7652. $mail = new TagbondMail();
  7653. $mail->sendTagbondMail($settings, $data_arr, '');
  7654. }
  7655. //send notifiction to merchant : product owner
  7656. $message = array(
  7657. 'message' => 'Received a Miskio purchase order #' . $order_id,
  7658. 'user_id' => $iteminfo['community_id'],
  7659. 'user_type' => 2,
  7660. 'notification_type' => 18,
  7661. 'count' => 1
  7662. //'vibrate' => 1,
  7663. //'sound' => 1
  7664. );
  7665. //sendMessage
  7666. Gcm::sendMessage($message);
  7667.  
  7668. $total_price = intval($iteminfo['quantity']) * floatval($iteminfo['price']);
  7669. $gross += $total_price;
  7670. $user_body .= '
  7671. <tr>
  7672. <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>
  7673. </tr>';
  7674. }
  7675. $user_body .= '</table><table width = "100%"><tr><td></td></tr>
  7676. <tr>
  7677. <td width="25%"><b>Delivery charges</b></td><td colspan="3">: ' . $total_delivery . ' ' . $wallet . '</td>
  7678. </tr>
  7679. <tr>
  7680. <td><b>Gross Total</b></td><td colspan="3">: ' . ($gross + $total_delivery) . ' ' . $wallet . '</td>
  7681. </tr>
  7682. <tr>
  7683. <td>Delivery Address</td><td colspan="3">: ' . $data['delivery_address'] . '</td>
  7684. </tr></table>';
  7685. $user_body .= '<table><tr><th>
  7686. Payment Details </th></tr>
  7687. <tr><td>Payment method </td><td>: ' . $data['payment_method'] . '</td></tr>
  7688. <tr><td>Transaction Id </td><td>: ' . $data['ref_id'] . '</td></tr></table>';
  7689. if ($data['payment_method'] == '7connect') {
  7690. $user_body .= 'Please make payment<br/>
  7691. Payment Url : ' . $response['link'] . '<br/>';
  7692. }
  7693. $data_arr = array(
  7694. 'email' => $user_email,
  7695. 'head' => $this->thisObj->_CLIENTDETAILS['name'],
  7696. 'toName' => ucfirst($this->user->user_firstname . ' ' . $this->user->user_lastname),
  7697. 'message' => $user_body
  7698. );
  7699. $mail_u = new TagbondMail();
  7700. $mail_u->sendTagbondMail($user_settings, $data_arr, '');
  7701.  
  7702. return $response;
  7703. } else {
  7704. return false;
  7705. }
  7706. }
  7707.  
  7708. public static function updateStock($item_id, $count) {
  7709. try {
  7710. $result = Catalog::model()->findByPk($item_id);
  7711. $result->stock -= $count;
  7712. $result->save();
  7713. $collection = Yii::app()->edmsMongoCollection('deals');
  7714. $deals = $collection->find(array('items.id' => $item_id));
  7715. if ($deals) {
  7716. foreach ($deals as $deal) {
  7717. $item_list = array();
  7718. $items = $deal['items'];
  7719. foreach ($items as $item) {
  7720. $update_item = $item;
  7721. if ($item['id'] == $item_id) {
  7722. if ($item['stock'] > 0) {
  7723. $update_item['stock'] = $item['stock'] - $count;
  7724. }
  7725. }
  7726. //$update_item['stock'] = $update_item['stock']>=0?intval($update_item['stock']):0;
  7727. $item_list[] = $update_item;
  7728. }
  7729. $collection->update(
  7730. array(
  7731. "_id" => new MongoID($deal['_id']->__toString()),
  7732. ), array('$set' => array("items" => $item_list))
  7733. );
  7734. }
  7735. }
  7736. } catch (Exception $e) {
  7737.  
  7738. }
  7739. }
  7740.  
  7741. /* public function payForItems($params){
  7742. $collection = Yii::app()->edmsMongoCollection('deals');
  7743. $deal = $collection->findOne(array("_id" => new MongoID($params['deal_id'])));
  7744.  
  7745. //validations
  7746. if(!$deal)
  7747. throw new CHttpException(403, "invalid_deal");
  7748.  
  7749. $items = $deal['items'];
  7750. $purchased_items = $params['catalog_item'];
  7751.  
  7752. $pitems = array_keys($purchased_items);
  7753.  
  7754. $total_weight = 0;
  7755.  
  7756. //get Item ids, weight for delivery charges
  7757. foreach($items as $item){
  7758. $item_id[] = $item['id'];
  7759. if(in_array($item['id'], $pitems)){
  7760. $item_price+= ($item['price']['amount'])*$purchased_items[$item['id']];
  7761. $item_wallet[$item['price']['wallet_id']]++;
  7762. $total_weight += $item['weight'];
  7763. }
  7764. }
  7765. //calculate delivery cost
  7766. $delivery_cost = 0;
  7767. if(isset($params['delivery_method'])){
  7768. if($params['delivery_method']['method'] == 'xend'){
  7769. $xendObj = new Xend(SiteSettings::getSettings());
  7770. $delivery_cost = $xendObj->calculate($params['province'], $params['pouch'], $total_weight);
  7771. }
  7772. else{
  7773. if($deal['delivery_options']['amount'] > 0 && $deal['delivery_options']['wallet_id'] > 0) {
  7774. $delivery_cost = $deal['delivery_options']['amount'];
  7775. }
  7776. }
  7777. }
  7778.  
  7779. $total_amount = $item_price+$delivery_cost;
  7780.  
  7781. //amount sent is differnt from actual amount
  7782. if($total_amount != $params['amount'])
  7783. throw new CHttpException(403, "item_or_delivery_amount_changed");
  7784.  
  7785. //multiple wallet types
  7786. if(sizeof($item_wallet)!=1){
  7787. throw new CHttpException(403, "clubbing_multiple_wallet_types");
  7788. }
  7789. else{
  7790. reset($item_wallet);
  7791. $wallet = key($item_wallet);
  7792. if($wallet != $params['wallet_id']){
  7793. throw new CHttpException(403, "wallet_missmatch");
  7794. }
  7795. }
  7796.  
  7797. //check all passed items are active in deal
  7798.  
  7799. $result = array_intersect($pitems, $item_id);
  7800. if(sizeof($result) != sizeof($purchased_items)){
  7801. throw new CHttpException(403, "all_items_not_available");
  7802. }
  7803. //validation ends
  7804.  
  7805. //reset($item_wallet);
  7806. //$wallet = key($item_wallet);
  7807. //$converted_amount = Currency::convertCurrency($params['amount'], $wallet, WalletTypes::getWalletName($params['wallet_id'],true));
  7808.  
  7809. $data = array();
  7810. $data['purchased_items'] = $purchased_items;
  7811. $data['delivery_address'] = $params['delivery_address'];
  7812. $data['amount'] = $params['amount']?$params['amount']:0;
  7813. $data['item_details'] = $params['item_details'];
  7814. if($params['delivery_method']){
  7815. $data['delivery_method']['method'] = $params['delivery_method'];
  7816. $data['delivery_method']['amount'] = $delivery_cost;
  7817. }
  7818. if($params['payment_method'] == 'tagcash'){
  7819. $stat = 1;
  7820. if($params['amount'] > 0){
  7821. $transaction = Yii::app()->db->beginTransaction();
  7822. $stat = Deals::transferPayment($params['amount'],$this->userId,1,$deal['owner']['id'],2,$params['wallet_id'],'catalog_purchase',true);
  7823. }
  7824. if(is_numeric($stat)){
  7825. $data['payment_method'] = $params['payment_method'];
  7826. $data['transaction_id'] = $stat;
  7827. $deal_stat = SELF::takeDeal($params['deal_id'], NULL, NULL, $data);
  7828. if($deal_stat){
  7829. if($transaction)
  7830. $transaction->commit();
  7831. return $stat;
  7832. }
  7833. }
  7834. else{
  7835. if($stat['transfer_amount'][0])
  7836. throw new CHttpException(403, $stat['transfer_amount'][0]);
  7837. }
  7838. }
  7839.  
  7840. if($params['payment_method'] == 'bank'){
  7841. $stat = 1;
  7842. if(isset($params['ref_id'])){
  7843. //verify ref id exists in table
  7844. }
  7845. else{
  7846. return false;
  7847. }
  7848. $data['payment_method'] = $params['payment_method'];
  7849. $data['transaction_id'] = $params['ref_id'];
  7850. $deal_stat = SELF::takeDeal($params['deal_id'], NULL, NULL, $data);
  7851. if($deal_stat){
  7852. if($transaction)
  7853. $transaction->commit();
  7854. return $stat;
  7855. }
  7856. }
  7857. if($params['payment_method'] == '7connect'){
  7858. $stat = 1;
  7859. if(isset($params['ref_id'])){
  7860. //verify ref id exists in table
  7861. }
  7862. else{
  7863. return false;
  7864. }
  7865. $data['payment_method'] = $params['payment_method'];
  7866. $data['transaction_id'] = $params['ref_id'];
  7867. $deal_stat = SELF::takeDeal($params['deal_id'], NULL, NULL, $data);
  7868. if($deal_stat){
  7869. if($transaction)
  7870. $transaction->commit();
  7871. return $stat;
  7872. }
  7873. }
  7874. return false;
  7875. } */
  7876.  
  7877. public function updateDeliveryOptions($params) {
  7878. $collection = Yii::app()->edmsMongoCollection('deals');
  7879. $deal = $collection->findOne(array("_id" => new MongoID($params['deal_id'])));
  7880. ///need to check permission for updating
  7881.  
  7882. if ($deal) {
  7883. $collection->update(
  7884. array(
  7885. "_id" => new MongoID($params['deal_id']),
  7886. ), array('$set' => array("delivery_options" => $params['delivery_options']))
  7887. );
  7888. return true;
  7889. } else {
  7890. return false;
  7891. }
  7892. }
  7893.  
  7894. public function getDeliveryOptions($deal_id) {
  7895. $collection = Yii::app()->edmsMongoCollection('deals');
  7896. $deal = $collection->findOne(array("_id" => new MongoID($deal_id), "delivery_options" => array('$exists' => true)));
  7897. if (isset($deal['delivery_options']))
  7898. return $deal['delivery_options'];
  7899. else
  7900. return '';
  7901. }
  7902.  
  7903. public function markFavorite($deal_id) {
  7904. $collection = Yii::app()->edmsMongoCollection('deals');
  7905. $deal = $collection->findOne(array("_id" => new MongoID($deal_id)));
  7906. if ($deal) {
  7907. $favorites = array();
  7908. if (isset($deal['users_favorite']))
  7909. $favorites = $deal['users_favorite'];
  7910. if (in_array($this->userId, $favorites)) {
  7911. if (($key = array_search($this->userId, $favorites)) !== false)
  7912. unset($favorites[$key]);
  7913. $favorites = array_values($favorites);
  7914. $result = 'removed_from_favorites';
  7915. }
  7916. else {
  7917. $favorites[] = $this->userId;
  7918. $result = 'added_to_favorites';
  7919. }
  7920. $collection->update(
  7921. array(
  7922. "_id" => new MongoID($deal_id),
  7923. ), array('$set' => array("users_favorite" => $favorites))
  7924. );
  7925. return $result;
  7926. } else {
  7927. return false;
  7928. }
  7929. }
  7930.  
  7931. public static function getFavoriteDeals($userId, $pageOffset, $pageCount) {
  7932. $collection = Yii::app()->edmsMongoCollection('deals');
  7933. $query['users_favorite'] = array('$in' => array($userId));
  7934. $result = $collection->find($query)
  7935. ->skip($pageOffset)
  7936. ->limit($pageCount);
  7937. $response = array();
  7938. if ($result) {
  7939. $data = array();
  7940. foreach ($result as $deal) {
  7941. $details = SELF::formatDeal($deal, false, null, $userId);
  7942. $response[] = $details;
  7943. }
  7944. }
  7945. return $response;
  7946. }
  7947.  
  7948. public function gameSlotAward($details) {
  7949. $dealId = $details['deal_id'];
  7950. $assigneeId = $details['user_id'];
  7951. if (!TagMongo::isValidId($dealId)) {
  7952. throw new CHttpException(404, "invalid_deal_id");
  7953. }
  7954.  
  7955. $userId = $this->userId;
  7956.  
  7957. $collection = Yii::app()->edmsMongoCollection('deals');
  7958. $deal = (object) $collection->findOne(array("_id" => new MongoID($dealId)));
  7959.  
  7960. //check deal validity
  7961. if (!$deal) {
  7962. throw new CHttpException(404, "invalid_deal");
  7963. } else if ($deal->status != 1) {
  7964. throw new CHttpException(403, "deal_unavailable");
  7965. }
  7966.  
  7967. $checkMember = CommunityUsers::model()->findByAttributes(array("user_id" => $assigneeId, "community_id" => $deal->owner['id']));
  7968. //if not member; automatically adds
  7969. if (!$checkMember) {
  7970. $role = CommunityRoles::model()->findByAttributes(array('community_id' => $deal->owner['id'], 'role_default' => '1'));
  7971. $roleId = $role->id;
  7972. $modelUsers = new CommunityUsers;
  7973. $modelUsers->user_id = $assigneeId;
  7974. $modelUsers->community_id = $deal->owner['id'];
  7975. $modelUsers->role_id = $roleId;
  7976. $modelUsers->communityuser_status = 1;
  7977. $modelUsers->communityuser_relation = 1;
  7978. $modelUsers->save();
  7979. }
  7980.  
  7981. $liveDeal = new stdClass();
  7982. $liveDeal->deal_id = new MongoID($dealId);
  7983. $liveDeal->type = $deal->type;
  7984. $liveDeal->owner = $deal->owner;
  7985. $liveDeal->title = $deal->title;
  7986. $liveDeal->description = $deal->description;
  7987. $liveDeal->hiddenDescription = $deal->hiddenDescription;
  7988. $liveDeal->start_date = $deal->start_date;
  7989. $liveDeal->end_date = $deal->end_date;
  7990. $liveDeal->city = $deal->city;
  7991. $liveDeal->town = $deal->town;
  7992. $liveDeal->zipCode = $deal->zipCode;
  7993. $liveDeal->date_taken = date('Y-m-d');
  7994. $liveDeal->date_redeemed = "";
  7995. $liveDeal->auto = $deal->auto;
  7996. $liveDeal->country = $deal->country;
  7997. $liveDeal->visibility = $deal->visibility;
  7998. $liveDeal->tags = $deal->tags;
  7999. $liveDeal->dealinfo = $deal->dealinfo;
  8000. $liveDeal->roles = $deal->roles;
  8001. $liveDeal->limits = $deal->limits;
  8002. $liveDeal->total_value = $deal->total_value;
  8003. $liveDeal->credit_type = $deal->credit_type;
  8004. if ($deal->methodOfPayment) {
  8005. $liveDeal->methodOfPayment = $deal->methodOfPayment;
  8006. }
  8007. if ($deal->digitalDelivery) {
  8008. $liveDeal->digitalDelivery = $deal->digitalDelivery;
  8009. }
  8010. if ($deal->pickUpAddress) {
  8011. $liveDeal->pickUpAddress = $deal->pickUpAddress;
  8012. }
  8013. if ($deal->price) {
  8014. $liveDeal->price = $deal->price;
  8015. }
  8016. if ($deal->affiliate_fee) {
  8017. $liveDeal->affiliate_fee = $deal->affiliate_fee;
  8018. }
  8019. if ($deal->rewardinfo) {
  8020. $liveDeal->rewardinfo = $deal->rewardinfo;
  8021. }
  8022.  
  8023. if ($deal->pay_per_take)
  8024. $liveDeal->pay_per_take = $deal->pay_per_take;
  8025. if ($deal->pay_per_click)
  8026. $liveDeal->pay_per_click = $deal->pay_per_click;
  8027.  
  8028. $liveDeal->module = $deal->module;
  8029.  
  8030. if ($deal->module == "ecommerce") {
  8031. $liveDeal->status = 9;
  8032. } else {
  8033. $liveDeal->status = 8;
  8034. }
  8035.  
  8036. $liveDeal->user_id = intval($assigneeId);
  8037. $liveDeal->assigner_id = intval($userId);
  8038.  
  8039. $user = Users::model()->findByPk($assigneeId);
  8040.  
  8041. if (!$user) {
  8042. throw new CHttpException(403, "user_doesnt_exist");
  8043. }
  8044.  
  8045. if ($deal->type == "stamp") {
  8046. $userinfo = new stdClass;
  8047. $userinfo->id = intval($user->id);
  8048. $userinfo->user_firstname = $user->user_firstname;
  8049. $userinfo->user_lastname = $user->user_lastname;
  8050. $liveDeal->stamp_log = array();
  8051. $liveDeal->stamp_notes = array();
  8052. } else {
  8053. $userinfo = new stdClass;
  8054. $userinfo->id = intval($user->id);
  8055. $userinfo->user_firstname = $user->user_firstname;
  8056. $userinfo->user_lastname = $user->user_lastname;
  8057. }
  8058.  
  8059. //ticket
  8060. if ($deal->type == "ticket" && $deal->module == "ecommerce") {
  8061. $purchasedTickets = array('history' => array(), 'tickets' => array());
  8062. $liveDeal->purchasedTickets = $purchasedTickets;
  8063. }
  8064.  
  8065. if ($deal->type == "catalog") {
  8066. if (!isset($details['item_id']) || $details['item_id'] < 1)
  8067. throw new CHttpException(403, "invalid_item");
  8068.  
  8069. $items = $deal->items;
  8070. foreach ($items as $item) {
  8071. if ($details['item_id'] == $item['id']) {
  8072. $item_details = $item;
  8073. $item_details['count'] = 1;
  8074. break;
  8075. }
  8076. }
  8077. if (!item_details) {
  8078. throw new CHttpException(403, "item_doesnot_exists");
  8079. } else {
  8080.  
  8081. $liveDeal->purchase_details['items'] = $item_details;
  8082. $liveDeal->purchase_details['delivery_address'] = $details['delivery_address'];
  8083. $liveDeal->purchase_details['delivery_method'] = array();
  8084. $liveDeal->purchase_details['payment_details']['total_amount'] = 0;
  8085. $liveDeal->purchase_details['payment_details']['paid_using'] = 'gameslotaward';
  8086. $liveDeal->purchase_details['payment_details']['transaction_id'] = '';
  8087. }
  8088. } else {
  8089. $liveDeal->paid = 'yes';
  8090. $liveDeal->paidUsing = 'gameslotaward';
  8091. }
  8092. $liveDeal->userinfo = $userinfo;
  8093. $liveDeal->orderedDate = date("Y-m-d H:i:s");
  8094. $liveDeal->orderItemCount = 1;
  8095. $liveCollection = Yii::app()->edmsMongoCollection('deals_live');
  8096. $liveCollection->insert($liveDeal);
  8097. return true;
  8098. }
  8099.  
  8100. public static function bookABus($id, $passengers, $obj) {
  8101. $originalTagvert = Yii::app()->edmsMongoCollection('deals');
  8102. $deal = $originalTagvert->findOne(array("_id" => new MongoID($id)));
  8103. $deal['dealinfo']['passengers'] = json_decode($passengers, true);
  8104.  
  8105. //check if available seats
  8106. if ($deal['dealinfo']['bus_info']['available'] < count($deal['dealinfo']['passengers'])) {
  8107. throw new CHttpException(403, "insufficient_seats");
  8108. }
  8109.  
  8110. //check if seats are available
  8111. $occupiedSeats = Deals::getOccupiedSeats($id);
  8112. foreach ($deal['dealinfo']['passengers'] as $v) {
  8113. if (in_array($v['seat_no'], $occupiedSeats)) {
  8114. throw new CHttpException(403, "seat_not_available");
  8115. }
  8116. }
  8117.  
  8118. $total = 0;
  8119. $totalSeatPrice = ($deal['dealinfo']['price'] * count($deal['dealinfo']['passengers']));
  8120.  
  8121. $total += $totalSeatPrice;
  8122.  
  8123. //add reservation fee
  8124. if ($deal['price']) {
  8125. $total += $deal['price']['amount'];
  8126. }
  8127.  
  8128. $mealArr = array();
  8129. $totalMealPrice = 0;
  8130. if ($deal['dealinfo']['passengers']) {
  8131. foreach ($deal['dealinfo']['passengers'] as $v) {
  8132. if ($v['meals']) {
  8133. foreach ($v['meals'] as $m) {
  8134. if (array_key_exists($m['meal'], $mealArr)) {
  8135. $mealArr[$m['meal']] += 1;
  8136. } else {
  8137. $mealArr[$m['meal']] = 1;
  8138. }
  8139. $totalSeatPrice += $m['price'];
  8140. $totalMealPrice += $m['price'];
  8141. }
  8142. }
  8143. }
  8144. }
  8145. $additional = '';
  8146. if ($mealArr) {
  8147. $mealsStr = '';
  8148. foreach ($mealArr as $k => $m) {
  8149. $mealsStr .= $k . " x" . $m . ",";
  8150. }
  8151. $additional = 'Meals (' . trim($mealsStr, ",") . ' = total of ' . $totalMealPrice . ')';
  8152. }
  8153. if (!WalletBalances::checkIfCanPay($obj->_USERID, 1, 1, $total)) {
  8154. throw new CHttpException(403, "insufficient_funds");
  8155. }
  8156.  
  8157. $d = new Deals;
  8158. $d->setIdentity($obj);
  8159.  
  8160. //take tagvert
  8161. if ($d->takeDeal($id, null, null, $deal['dealinfo']['passengers'])) {
  8162.  
  8163. $transfer = new WalletTransfers();
  8164. $transfer->setIdentity($obj);
  8165. $transfer->reference_id = uniqid() . rand(10 * 45, 100 * 98);
  8166. $transfer->transfer_from_amount = $totalSeatPrice;
  8167. $transfer->transfer_amount = NULL;
  8168. $transfer->transfer_from_id = $obj->_USERID;
  8169. $transfer->transfer_from_type = 1;
  8170. $transfer->walletFrom = $deal['price']['wallet_id'];
  8171. $transfer->transfer_to_amount = $total;
  8172. $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;
  8173. $transfer->setTo(2, $deal['owner']['id']);
  8174. $transfer->setType(1);
  8175. $transfer->setWallets($transfer->walletFrom, $transfer->walletFrom);
  8176. $transfer->transfer();
  8177.  
  8178. //update bus tagvert's available seats
  8179. $originalTagvert->update(array(
  8180. "_id" => new MongoID($id),
  8181. ), array(
  8182. '$set' => array(
  8183. 'dealinfo.bus_info.available' => $deal['dealinfo']['bus_info']['available'] - count($deal['dealinfo']['passengers'])
  8184. )
  8185. )
  8186. );
  8187. return true;
  8188. }
  8189. return false;
  8190. }
  8191.  
  8192. public static function getOccupiedSeats($dealId) {
  8193. if (!TagMongo::isValidId($dealId)) {
  8194. throw new CHttpException(404, invalid_deal_id);
  8195. }
  8196.  
  8197. $collection = Yii::app()->edmsMongoCollection('deals_live');
  8198. $live = $collection->find(array('deal_id' => new MongoId($dealId)));
  8199.  
  8200. $seats = array();
  8201. if ($live->count()) {
  8202.  
  8203. foreach ($live as $v) {
  8204. $passengers = $v['dealinfo']['passengers'];
  8205. foreach ($passengers as $p) {
  8206. $seats[] = $p['seat_no'];
  8207. }
  8208. }
  8209. }
  8210.  
  8211. return $seats;
  8212. }
  8213.  
  8214. public function getBusTicket($dealId, $id) {
  8215. if (!TagMongo::isValidId($dealId)) {
  8216. throw new CHttpException(404, invalid_deal_id);
  8217. }
  8218.  
  8219. $details = $this->getLiveDealDetails($dealId, $id);
  8220. $ticket = array();
  8221. if ($details) {
  8222. $ticket['booked_by'] = $details->userinfo;
  8223. $ticket['date_reserved'] = $details->userinfo['taken_date'];
  8224. $ticket['route_from'] = BusReservationRoutes::getRouteName($details->dealinfo['route_from']);
  8225. $ticket['route_to'] = BusReservationRoutes::getRouteName($details->dealinfo['route_to']);
  8226. $ticket['date_time'] = date('D d M', strtotime($details->dealinfo['date'])) . ' ' . $details->dealinfo['departure_time'] . ' - ' . $details->dealinfo['arrive_time'];
  8227. $ticket['issued'] = "Tagcash";
  8228. $ticket['passengers_count'] = sizeOf($details->dealinfo['passengers']);
  8229. $ticket['passengers'] = $details->dealinfo['passengers'];
  8230. if ($details->price) {
  8231. $ticket['price'] = $details->price;
  8232. }
  8233. }
  8234.  
  8235. return $ticket;
  8236. }
  8237.  
  8238. public static function createResume($data) {
  8239. $collection = Yii::app()->edmsMongoCollection('user_resumes');
  8240.  
  8241. return $collection->insert((object) $data);
  8242. }
  8243.  
  8244. public static function updateResume($id, $data) {
  8245. $collection = Yii::app()->edmsMongoCollection('user_resumes');
  8246.  
  8247. $update = $collection->update(array(
  8248. '_id' => new MongoId($id)
  8249. ), array('$set' => array('resume_info' => $data)
  8250. )
  8251. );
  8252. return $update;
  8253. }
  8254.  
  8255. public static function getResumes($id, $offset = 0, $limit = 20) {
  8256. $collection = Yii::app()->edmsMongoCollection('user_resumes');
  8257. if ($id) {
  8258. $query = $collection->findOne(array('_id' => new MongoId($id)));
  8259. } else {
  8260. $query = $collection->find()->sort(array('created_date' => -1))->skip($offset)->limit($limit);
  8261. if ($query) {
  8262. $resumes = array();
  8263. foreach ($query as $v) {
  8264. $resumes[] = $v;
  8265. }
  8266. $query = $resumes;
  8267. }
  8268. }
  8269.  
  8270. return $query;
  8271. }
  8272.  
  8273. public static function deleteResume($id) {
  8274. $collection = Yii::app()->edmsMongoCollection('user_resumes');
  8275.  
  8276. $query = $collection->remove(array('_id' => new MongoId($id)));
  8277.  
  8278.  
  8279. return $query;
  8280. }
  8281.  
  8282. public function getItems($filter) {
  8283. $parsedDeals = array();
  8284. $query = array();
  8285. $deal_type_master_list = array();
  8286. //sorting ( by cost_per_view) descending order
  8287. $sort = array("cost_per_view.amount" => -1, "status" => 1, "end_date" => 1);
  8288. if ($filter['loc']) {
  8289. $location['long'] = $filter['loc']['long'];
  8290. $location['lat'] = $filter['loc']['lat'];
  8291. }
  8292. $collection = Yii::app()->edmsMongoCollection('deals');
  8293. $query['type'] = 'catalog';
  8294. $query['items'] = array('$exists' => true, '$ne' => null, '$not' => array('$size' => 0));
  8295. $query['status'] = 1;
  8296. $query["end_date"] = array('$gte' => date('Y-m-d'));
  8297. if ($filter['country_id']) {
  8298. //$query['country.id'] = intval($filter['country_id']);
  8299. }
  8300. if ($filter['deal_id'])
  8301. $query['_id'] = new MongoID($filter['deal_id']);
  8302.  
  8303. if (is_array($filter['tags'])) {
  8304. $query['tags'] = array('$all' => $filter['tags']);
  8305. }
  8306.  
  8307. //filter by owner
  8308. if ($filter['community_id']) {
  8309. $query['owner.id'] = intval($filter['community_id']);
  8310. $query['owner.type'] = 'community';
  8311. }
  8312. //$query['visibility'] = 'public';
  8313. $query['switch'] = array('$ne' => intval(0));
  8314. if ($location['long'] && $location['lat']) {
  8315. $long = $location['long'];
  8316. $lat = $location['lat'];
  8317. if ($filter['distance'])
  8318. $distance = $filter['distance'];
  8319. else
  8320. $distance = 2; // default 2km
  8321.  
  8322. $query["location"] = array('$near' => array(floatval($long), floatval($lat)), '$maxDistance' => floatval($distance / 111.12));
  8323.  
  8324. unset($query['$or']); // or wont work with $near geospacial
  8325. $sort = array(); //no need of sort- automatically sorting via distance
  8326. }
  8327.  
  8328. //filter by category
  8329. if ($filter['category_id']) {
  8330. $query['category.id'] = $filter['category_id'];
  8331. }
  8332.  
  8333. //filter by catalog_id / item_id
  8334. if ($filter['item_id']) {
  8335. $query['items.id'] = intval($filter['item_id']);
  8336. }
  8337.  
  8338. //filter by hashtags
  8339. if (is_array($filter['hashtags'])) {
  8340. $query['$and'] = array();
  8341. $orQ['$or'][] = array("title" => array('$in' => $filter['hashtags']));
  8342. $orQ['$or'][] = array("items.hashtags" => array('$in' => $filter['hashtags']));
  8343. $orQ['$or'][] = array("items.catalog_name" => array('$in' => $filter['hashtags']));
  8344. $query['$and'] = array($orQ);
  8345.  
  8346. //$query['items.hashtags'] = array('$all' => $filter['hashtags']);
  8347. }
  8348.  
  8349. // executing query
  8350. //print_r(json_encode($query)); exit;
  8351. $deals = $collection->find($query)
  8352. ->sort($sort);
  8353.  
  8354. // parsing the result
  8355. if ($deals) {
  8356. $items = array();
  8357. $i = 0;
  8358. foreach ($deals as $deal) {
  8359. $image = array();
  8360. $catalogImages = new CatalogImages;
  8361. $items_count = sizeOf($deal['items']);
  8362. foreach ($deal['items'] as $item) {
  8363. if ($i < $this->pageOffset) {
  8364. $i++;
  8365. continue;
  8366. }
  8367. //filter by item id
  8368. if ($filter['item_id'] && $item['id'] != $filter['item_id'])
  8369. continue;
  8370.  
  8371. if ($item['category'])
  8372. unset($item['category']);
  8373. if ($filter['hashtags'] && !empty($filter['hashtags'])) {
  8374. if (!is_array($item['hashtags'])) {
  8375. $item['hashtags'] = array();
  8376. }
  8377. if (empty(array_intersect($item['hashtags'], $filter['hashtags'])) && !in_array($deal['title'], $filter['hashtags']) && !in_array($item['catalog_name'], $filter['hashtags'])) {
  8378. continue;
  8379. }
  8380. }
  8381. $itm = SELF::formatItemDetails($item['id']);
  8382. $itm['image'] = $catalogImages->getCatalogImages($item['id']) ? $catalogImages->getCatalogImages($item['id']) : $image;
  8383. $itm['deal_id'] = $deal['_id']->__toString();
  8384. $itm['title'] = $deal['title'];
  8385. $itm['items_count'] = $items_count;
  8386. $itm['item_rating'] = Ratings::getItemRate($item['id']);
  8387. $itm['favorite_item'] = FavoriteCatalogs::checkFavourite($this->userId, $item['deal_id'], $item['id']);
  8388. $itm['owner'] = self::formatOwner($deal['owner']);
  8389. $itm['city'] = is_array($deal['city']) ? $deal['city']['name'] : $deal['city'];
  8390. $itm['delivery_options'] = empty($deal['delivery_options']) ? (object) $deal['delivery_options'] : $deal['delivery_options'];
  8391. $items[] = $itm;
  8392. $i++;
  8393. if ($i == $this->pageOffset + $this->pageCount)
  8394. break;
  8395. }
  8396. if ($i == $this->pageOffset + $this->pageCount)
  8397. break;
  8398. }
  8399. return $items;
  8400. }
  8401. return array();
  8402. }
  8403.  
  8404. public static function formatItemDetails($item_id) {
  8405. $query = Yii::app()->db->createCommand()
  8406. ->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')
  8407. ->from('catalog c')
  8408. //select = cc.category_name + ->leftJoin("catalog_category cc", "cc.id = c.category_id")
  8409. ->leftJoin("wallet_types wt", "wt.id = c.price_wallet")
  8410. ->where('c.id = ' . $item_id);
  8411. $item_details = $query->queryAll();
  8412. $item_details = $item_details[0];
  8413. $item['id'] = $item_id;
  8414. $item['catalog_name'] = $item_details['catalog_name'];
  8415. $item['description'] = $item_details['description'];
  8416. $item['price']['amount'] = $item_details['price'];
  8417. $item['price']['wallet_id'] = $item_details['price_wallet'];
  8418. $item['price']['wallet_name'] = $item_details['currency_code'];
  8419. $item['stock'] = $item_details['stock'];
  8420. $item['category_id'] = $item_details['category_id'];
  8421. $item['weight'] = $item_details['weight'];
  8422. $item['email'] = $item_details['email'];
  8423. $item['sizes'] = $item_details['sizes'] ? explode(',', $item_details['sizes']) : array();
  8424. $item['colors'] = $item_details['colors'] ? explode(',', $item_details['colors']) : array();
  8425. $item['other'] = $item_details['other'] ? explode(',', $item_details['other']) : array();
  8426. $item['hashtags'] = $item_details['hashtags'] ? explode(',', $item_details['hashtags']) : array();
  8427. $item['time_to_ship'] = $item_details['time_to_ship'];
  8428. return $item;
  8429. }
  8430.  
  8431. public function listDealTypes($status = null) {
  8432. $collection = Yii::app()->edmsMongoCollection('deals');
  8433. $query['owner.id'] = intval($this->communityId);
  8434. if ($status == 'active') {
  8435. $query['status'] = 1;
  8436. $query["end_date"] = array('$gte' => date('Y-m-d'));
  8437. }
  8438. $dealTypes = $collection->distinct("type", $query);
  8439. return $dealTypes;
  8440. }
  8441.  
  8442. public function getOrderDetails($transaction_id) {
  8443. $collection = Yii::app()->edmsMongoCollection('deals_live');
  8444. $query['purchase_details.payment_details.transaction_id'] = $transaction_id;
  8445.  
  8446. if (!$this->communityId) {
  8447. $query['userinfo.id'] = intval($this->userId);
  8448. } else if ($this->community['community_resellerid'] == NULL) {
  8449. $query['owner.id'] = intval($this->communityId);
  8450. $query['owner.type'] = 'community';
  8451. }
  8452. $orders = $collection->find($query, array('owner', 'purchase_details', 'userinfo'));
  8453.  
  8454. if ($orders) {
  8455. foreach ($orders as $order) {
  8456. $order['purchase_details']['payment_details']['wallet_name'] = WalletTypes::getWalletName($order['purchase_details']['payment_details']['wallet_id'], true);
  8457. if ($this->community['community_resellerid'] == NULL) {
  8458. $return[] = array('owner' => $order['owner'], 'purchase_details' => $order['purchase_details'], 'userinfo' => $order['userinfo']);
  8459. } else {
  8460. $return[] = array('owner' => $order['owner'], 'payment_details' => $order['purchase_details']['payment_details'], 'userinfo' => $order['userinfo']);
  8461. }
  8462. }
  8463. return $return;
  8464. }
  8465. throw new CHttpException(403, 'invalid_transaction_id');
  8466. }
  8467.  
  8468. }
  8469.  
  8470. ?>
Add Comment
Please, Sign In to add comment