public static function createSmsJob($condition, $operator, $smsName) { $totalCount = 0; $accountId = Token::getAccountId(); if (!array_key_exists('accountId', $condition)) { $condition = array_merge($condition, ['accountId' => $accountId]); } switch ($smsName) { case 'cny_winners': $smsTemplate = self::CNY_WINNERS_SMS_TEMPLATE; $totalCount = LuckyDrawWinner::find()->where($condition)->count(); break; default: break; } $recordId = BulkSmsRecord::createSmsRecord($operator, $smsName, $smsTemplate, $totalCount); if (is_bool($recordId) && !$recordId) { throw new ServerErrorHttpException("發送失敗,請刷新頁面重試!"); } $args = ['condition' => serialize($condition), 'smsName' => $smsName, 'smsRecord' => (string) $recordId]; $jobId = Yii::$app->job->create('backend\\modules\\uhkklp\\job\\BulkSms', $args); if (!empty($jobId)) { return ['smsRecordId' => (string) $recordId, 'count' => $totalCount]; } else { throw new ServerErrorHttpException("發送失敗,請刷新頁面重試!"); } }
/** * The first step of creating page * Use the createBasic scenario **/ public function actionCreate() { $params = $this->getParams(); $accesstoken = $this->getAccessToken(); $token = Token::getToken($accesstoken); $page = new Page(['scenario' => 'createBasic']); $page->attributes = $params; $page->_id = new \MongoId(); $page->accountId = $token->accountId; $userId = $token->userId; $user = User::findByPk($userId); $page->creator = ['id' => $userId, 'name' => $user->name]; $page->url = Yii::$app->request->hostinfo . '/msite/page/' . $page->_id; $shortUrl = Yii::$app->urlService->shortenUrl($page->url); $page->shortUrl = $shortUrl['Short']; if ($page->validate()) { // all inputs are valid if ($page->save()) { return $page; } else { throw new ServerErrorHttpException(Yii::t('common', 'save_fail')); } } else { // valid fail, return errors $errors = array_keys($page->errors); throw new InvalidParameterException([$errors[0] => Yii::t("microSite", $errors[0] . '_field_not_empty')]); } }
/** * This method is used to valide the user's authority with token in help desk chat system. * This method is invoked right before an action is executed. * * The method will trigger the [[EVENT_BEFORE_ACTION]] event. The return value of the method * will determine whether the action should continue to run. * * If you override this method, your code should look like the following: * * ```php * public function beforeAction($action) * { * if (parent::beforeAction($action)) { * // your custom code here * return true; // or false if needed * } else { * return false; * } * } * ``` * @param Action $action the action to be executed. * @return boolean whether the action should continue to run. * @author Harry Sun */ public function beforeAction($action) { $route = $this->id . '/' . $action->id; //init i18n configuration from user agent Yii::$app->language = LanguageUtil::getBrowserLanguage(); // the action ids without auth $noAuth = ['site/login', 'site/logout', 'conversation/state', 'conversation/message', 'setting/index', 'setting/self-helpdesk', 'site/send-reset-password-email', 'site/reset-password', 'help-desk/check-auth', 'conversation/user-state', 'issue/create-from-js-sdk', 'issue/remove-attachment']; if (in_array($route, $noAuth)) { return true; } else { $accessToken = $this->getQuery('accesstoken'); $info = Token::getToken($accessToken); if (!empty($info) && isset($info->expireTime) && !MongodbUtil::isExpired($info->expireTime)) { Yii::$app->language = empty($info->language) ? LanguageUtil::DEFAULT_LANGUAGE : $info->language; $expireTime = new \MongoDate(time() + Token::EXPIRE_TIME); if ($info->expireTime < $expireTime) { $info->expireTime = $expireTime; } $updateResult = $info->update(); return true; } LogUtil::error(['accessToken' => $accessToken, 'message' => 'You have not logined']); throw new \yii\web\UnauthorizedHttpException('You have not logined'); } }
public function actionSave() { $this->_setJSONFormat(Yii::$app); $request = Yii::$app->request; $data = $request->post(); $code = '1'; if (!empty($data['_id'])) { $product = Product::findOne($data['_id']['$id']); $data['updatedAt'] = new \MongoDate(); $code = '2'; } if (empty($product)) { $product = new Product(); $accessToken = Token::getToken(); $user = User::findOne(['_id' => $accessToken->userId]); $data['accountId'] = $this->getAccountId(); $data['creator'] = $user->name; $data['createdAt'] = new \MongoDate(); $data['isDeleted'] = false; } if (!empty($product->accountId)) { unset($data['accountId']); } $product->attributes = $data; $product->save(); return ['code' => $code]; }
public static function createPrize($params, $activityId) { $accountId = Token::getAccountId(); if (empty($accountId)) { throw new ServerErrorHttpException("Fail to get account's id"); } for ($i = 0; $i < count($params); $i++) { unset($params[$i]['_id']); //remove default _id, create MongoId $params[$i]['activityId'] = $activityId; $params[$i]['accountId'] = $accountId; $params[$i]['points'] = (int) $params[$i]['points']; $params[$i]['quantity'] = (int) $params[$i]['quantity']; $prize = new ActivityPrize(); if (!empty($params[$i]['startDate'])) { $params[$i]['startDate'] = MongodbUtil::msTimetamp2MongoDate($params[$i]['startDate']); $params[$i]['endDate'] = MongodbUtil::msTimetamp2MongoDate($params[$i]['endDate']); } $prize->attributes = $params[$i]; if (!$prize->save()) { LogUtil::error(['message' => 'save activity-prize failed', 'error' => $prize->errors], 'activityPrize'); // throw new ServerErrorHttpException('save activityPrize failed'); return false; } unset($prize); } return true; }
public static function getCountBySmsRecordId($smsRecordId) { $accountId = Token::getAccountId(); $successful = BulkSmsLog::find()->where(['smsRecordId' => $smsRecordId, 'status' => true, 'accountId' => $accountId])->count(); $failed = BulkSmsLog::find()->where(['smsRecordId' => $smsRecordId, 'status' => false, 'accountId' => $accountId])->count(); unset($accountId); return ['successful' => $successful, 'failed' => $failed]; }
public static function createSmsRecord($operator, $smsName, $smsTemplate, $total = 0, $process = 0) { $properties = ['smsName' => $smsName, 'total' => $total, 'successful' => 0, 'failed' => 0, 'process' => $process, 'smsTemplate' => $smsTemplate, 'accountId' => Token::getAccountId(), 'operator' => $operator]; $smsRecord = new BulkSmsRecord(); $smsRecord->attributes = $properties; if (!$smsRecord->save()) { return false; } return $smsRecord->_id; }
public static function saveImportedCookbooks($datas, $accountId) { $results = []; $accessToken = Token::getToken(); $userId = $accessToken->userId; $user = User::findOne(['_id' => $userId]); for ($i = 0; $i < sizeof($datas); $i++) { $results[] = self::_saveSingleCookbook($datas[$i], $user, $accountId); } return $results; }
public static function createWinner($params) { $winner = new LuckyDrawWinner(); if (!array_key_exists('accountId', $params)) { $winner->accountId = Token::getAccountId(); } $winner->attributes = $params; $winner->createdAt = new \MongoDate(); $winner->save(); unset($winner); }
public static function getLastSmsRecord() { $accountId = Token::getAccountId(); $query = new Query(); $query = $query->from('uhkklpEarlyBirdSmsRecord')->select(['_id', 'total', 'successful', 'failed', 'process']); $recordOne = $query->where(['smsName' => 'sms_one', 'accountId' => $accountId])->orderBy(['createdAt' => SORT_DESC])->one(); $recordTwo = $query->where(['smsName' => 'sms_two', 'accountId' => $accountId])->orderBy(['createdAt' => SORT_DESC])->one(); $recordThree = $query->where(['smsName' => 'sms_three', 'accountId' => $accountId])->orderBy(['createdAt' => SORT_DESC])->one(); $recordFour = $query->where(['smsName' => 'sms_four', 'accountId' => $accountId])->orderBy(['createdAt' => SORT_DESC])->one(); unset($accountId, $query); return ['sms_one' => $recordOne, 'sms_two' => $recordTwo, 'sms_three' => $recordThree, 'sms_four' => $recordFour]; }
/** * Activate a module * * <b>Request Type </b>:PUT * <b>Request Endpoints </b>: http://{server-domain}/api/management/module/activate-module * <b>Content-type</b>: application/json<br/><br/> * <b>Summary</b>: This api is used for the user to activate a extension module. * * <b>Request Example </b>: * <pre> * http://{server-domain}/api/management/module/activate-module * </pre> * <pre> * { * "name" : "customer", * } * </pre> * **/ public function actionActivateModule() { $moduleName = $this->getParams('name'); $accountId = $this->getAccountId(); $moduleNames = Yii::$app->extModule->getDependencyModules($moduleName); $account = Account::findByPk($accountId); if (in_array($moduleName, $account->enabledMods)) { throw new BadRequestHttpException(\Yii::t('common', 'function_has_been_activated')); } $updateAccountResult = Account::updateAll(['$addToSet' => ['enabledMods' => ['$each' => $moduleNames]]], ['_id' => $accountId]); if ($updateAccountResult) { $updateTokenResult = Token::updateAll(['$addToSet' => ['enabledMods' => ['$each' => $moduleNames]]], ['accountId' => $accountId]); if ($updateTokenResult) { $installFilePath = Yii::getAlias('@backend') . DIRECTORY_SEPARATOR . 'modules' . DIRECTORY_SEPARATOR . $moduleName . DIRECTORY_SEPARATOR . 'Install.php'; if (file_exists($installFilePath)) { require_once $installFilePath; $className = 'backend\\modules\\' . $moduleName . '\\Install'; if (class_exists($className)) { $installObj = Yii::createObject($className); $installObj->run($accountId); } } list($menus, $mods) = Yii::$app->extModule->getMenuAndExt($moduleName); $dbMenus = $account->menus; $dbMods = $account->mods; foreach ($menus as $moduleName => $menu) { if (!isset($dbMenus[$moduleName])) { $dbMenus[$moduleName] = []; } $dbMenus[$moduleName] = ArrayHelper::merge($dbMenus[$moduleName], $menu); } $account->menus = $dbMenus; foreach ($mods as $mod) { $isInDB = false; foreach ($dbMods as $dbMod) { if (!empty($dbMod['name']) && !empty($mod['name']) && $dbMod['name'] == $mod['name']) { $isInDB = true; break; } } if (!$isInDB) { $dbMods[] = $mod; } } $account->mods = $dbMods; $account->save(true, ['menus', 'mods']); } else { throw new ServerErrorHttpException('Activate fail'); } } else { throw new ServerErrorHttpException('Activate fail'); } }
/** * Get the account id according to the accessToken * @return MongoId | boolean, the PK for the account or false for no such account found */ public function getAccountId() { $accountId = $this->getAccountIdFromCookies(); if (!empty($accountId)) { return new MongoId($accountId); } $token = $this->getAccessToken(); $tokenInfo = Token::getToken($token); if (empty($tokenInfo)) { return false; } return $tokenInfo->accountId; }
public static function creatWinner($winnerArr, $recordId, $prizeName) { $winner = new EarlyBirdWinner(); $winner->memberId = new \MongoId($winnerArr['id']); $winner->prizeLevel = $winnerArr['prizeLevel']; $winner->mobile = $winnerArr['mobile']; $winner->name = $winnerArr['name']; $winner->exchangeGoodsScore = $winnerArr['exchangeGoodsScore']; $winner->accountId = Token::getAccountId(); $winner->createdAt = new \MongoDate(); $winner->drawRecordId = $recordId; $winner->prizeName = $prizeName; $winner->save(); unset($winner); }
/** * exchange the promotioncode */ public function actionExchange() { $params = $this->getParams(); if (empty($params['code']) || empty($params['memberId'])) { throw new BadRequestHttpException(Yii::t('common', 'parameters_missing')); } //get email for user $accesstoken = $this->getAccessToken(); $tokenInfo = Token::findOne(['accessToken' => $accesstoken]); $userInfo = User::findByPk($tokenInfo['userId']); $params['operaterEmail'] = empty($userInfo['email']) ? '' : $userInfo['email']; $params['userInfo'] = empty($userInfo) ? null : ['id' => $userInfo->_id, 'name' => $userInfo->name]; $memberId = $params['memberId']; $params['memberId'] = new MongoId($memberId); if (!empty($params['exchangeTime'])) { $params['exchangeTime'] = TimeUtil::ms2sTime($params['exchangeTime']); } //exchange the promotion code $accountId = $this->getAccountId(); if (is_array($params['code'])) { //exchaneg code offline $codes = $params['code']; $successCode = []; foreach ($codes as $code) { $params['code'] = strtoupper($code); $result = PromotionCode::exchangeCampaignCode($params, $accountId, self::EXCHANEG_TYPE_OFFLINE); if ('success' == $result['result']) { $successCode[] = $code; } } list($codeNumber, $score) = CampaignLog::getCodeRecord($successCode); if (!empty($params['useWebhook'])) { $eventData = ['type' => Webhook::EVENT_PROMOTION_CODE_REDEEMED, 'member_id' => $memberId, 'codes' => $params['code'], 'redeemed_codes' => $successCode, 'score' => $score, 'origin' => Member::PORTAL, 'account_id' => (string) $accountId, 'created_at' => TimeUtil::msTime2String($params['exchangeTime'], \DateTime::ATOM)]; Yii::$app->webhook->triggerEvent($eventData); } //fix data $this->fixData($accountId, $params['memberId'], $successCode); return ['result' => 'success', 'codeNumber' => $codeNumber, 'totalScore' => $score, 'codes' => $successCode]; } else { $params['code'] = strtoupper($params['code']); $result = PromotionCode::exchangeCampaignCode($params, $accountId, self::EXCHANEG_TYPE_MOBILE); if ('error' == $result['result']) { throw new InvalidParameterException($result['message']); } else { return $result; } } }
public static function createBar($params) { $params['accountId'] = Token::getAccountId(); if (empty($params['accountId'])) { throw new ServerErrorHttpException("Fail to get account's id"); } unset($params['_id']); $bar = new ActivityBar(); $params['startDate'] = MongodbUtil::msTimetamp2MongoDate($params['startDate']); $params['endDate'] = MongodbUtil::msTimetamp2MongoDate($params['endDate']); $params['probability'] = (int) $params['probability']; $bar->attributes = $params; if (!$bar->save()) { LogUtil::error(['message' => 'save activity-bar failed', 'error' => $bar->errors], 'activityBar'); throw new ServerErrorHttpException('save activityBar failed'); } return $bar['_id']; }
public static function getList($currentPage = 1, $pageSize = 10, $sort = [], $condition = []) { if (empty($sort)) { $sort = ['_id' => SORT_DESC]; } else { foreach ($sort as $key => $value) { if ($value) { $sort = [$key => SORT_DESC]; } else { $sort = [$key => SORT_ASC]; } } } $offset = ($currentPage - 1) * $pageSize; $query = new Query(); $datas = $query->from(self::collectionName())->select(self::attributes())->where(['accountId' => Token::getAccountId()])->andWhere($condition)->orderBy($sort)->offset($offset)->limit($pageSize)->all(); return $datas; }
public static function createUser($params) { try { $result = true; $accountId = Token::getAccountId(); if (empty($accountId)) { throw new ServerErrorHttpException("Fail to get account's id"); } $params['accountId'] = $accountId; $user = new ActivityUser(); $user->attributes = $params; if (!$user->save()) { LogUtil::error(['message' => 'save activity-user failed', 'error' => $user->errors], 'activityUser'); $result = false; } return $result; } catch (\Exception $ex) { LogUtil::error(['message' => 'save activity-user failed', 'error' => $ex->getMessage()], 'activityUser'); return false; } }
public function actionUpdate($id) { $id = new \MongoId($id); $user = User::findOne(['_id' => $id]); $user->load($this->getParams(), ''); if ($user->save() === false && !$user->hasErrors()) { throw new ServerErrorHttpException('Failed to update the object for unknown reason.'); } //update the language information in token Token::updateAll(['language' => $user->language]); return $user; }
public function actionToCookbook() { sleep(2); Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; $request = Yii::$app->request; $fileB64 = $request->post('fileB64'); $file = base64_decode(substr($fileB64, strpos($fileB64, ";base64,") + 8)); $filePath = Yii::getAlias('@runtime') . '/cookbook' . date('his'); file_put_contents($filePath, $file); $phpReader = new \PHPExcel_Reader_Excel2007(); if (!$phpReader->canRead($filePath)) { $phpReader = new \PHPExcel_Reader_Excel5(); if (!$phpReader->canRead($filePath)) { $phpReader = new \PHPExcel_Reader_CSV(); if (!$phpReader->canRead($filePath)) { unlink($filePath); return ['fileError' => true]; } } } $phpExcel = $phpReader->load($filePath); $sheets = $phpExcel->getAllSheets(); $cookbookTitles = []; for ($si = 0; $si < sizeof($sheets); $si++) { $sheet = $sheets[$si]; $rowTemp = []; $cowTemp = []; $ingredientFinished = false; $rowCount = $sheet->getHighestRow(); $highestCol = $sheet->getHighestColumn(); $colCount = ord($highestCol) - 65; $cookbook = []; //There has a bug //When the 'cuisineType' row does not exist, the $rowCount will be infinity //The code blow can avoid this bug $rowCount = $rowCount > 100 ? 100 : $rowCount; for ($row = 1; $row <= $rowCount; $row++) { for ($col = 0; $col <= $colCount; $col++) { $val = $sheet->getCellByColumnAndRow($col, $row)->getValue(); $val = trim((string) $val); if ($val === '') { continue; } // Fill title and image if (!isset($cookbook['title'])) { $arr = explode('-', $val, 2); if (empty($arr) || sizeof($arr) < 2) { unlink($filePath); LogUtil::error(date('Y-m-d h:i:s') . ' ukkklp parse excel to cookbook error: title is required'); return ['contentError' => true]; } if (mb_strlen(trim(trim($arr[1])), 'utf-8') > 30) { unlink($filePath); LogUtil::error(date('Y-m-d h:i:s') . ' ukkklp parse excel to cookbook error: title should less than 30 words'); return ['titleLengthError' => true]; } $cookbook['image'] = Yii::$app->qiniu->domain . '/' . trim($arr[0]) . '.jpg'; $cookbook['title'] = trim(trim($arr[1])); unset($arr); continue; } // Find category row if (!isset($rowTemp['category'])) { if (!preg_match('/^category$/i', $val)) { unlink($filePath); LogUtil::error(date('Y-m-d h:i:s') . ' ukkklp parse excel to cookbook error: category is required'); return ['contentError' => true]; } $rowTemp['category'] = $row; continue; } // Fill category if ($rowTemp['category'] === $row) { //The first sheet's category row will leads to a bug if ($si == 0) { $firstCate = $val; } $arr = $this->_spiltByComma($val); // $arr = preg_split('/[,,]/', $val); $cookbook['category'] = []; foreach ($arr as $v) { $v = trim($v); if ($v != '') { $cookbook['category'][] = trim($v); } } $row++; $col = -1; unset($arr); continue; } // Find subCategory row if (!isset($rowTemp['subCategory'])) { if (!preg_match('/^sub[\\s\\n]*category$/i', $val)) { unlink($filePath); LogUtil::error(date('Y-m-d h:i:s') . ' ukkklp parse excel to cookbook error: subCategory is required'); return ['contentError' => true]; } $rowTemp['subCategory'] = $row; continue; } // Fill subCategory if ($rowTemp['subCategory'] === $row) { // $arr = preg_split('/[,,]/', $val); $arr = $this->_spiltByComma($val); $cookbook['subCategory'] = []; foreach ($arr as $v) { $v = trim($v); if ($v != '') { $cookbook['subCategory'][] = trim($v); } } $row++; $col = -1; unset($arr); continue; } // Find cuisineType row if (!isset($rowTemp['cuisineType'])) { if (preg_match('/^cuisine[\\s\\n]*type$/i', $val)) { $rowTemp['cuisineType'] = $row; continue; } else { $rowTemp['cuisineType'] = ''; } } // Fill cuisineType if ($rowTemp['cuisineType'] === $row) { // $arr = preg_split('/[,,]/', $val); $arr = $this->_spiltByComma($val); $cookbook['cuisineType'] = []; foreach ($arr as $v) { $v = trim($v); if ($v != '') { $cookbook['cuisineType'][] = trim($v); } } $row++; $col = -1; unset($arr); continue; } // Find yield row if (!isset($rowTemp['yield'])) { if (!preg_match('/^yield$/i', $val)) { unlink($filePath); LogUtil::error(date('Y-m-d h:i:s') . ' ukkklp parse excel to cookbook error: yield is required'); return ['contentError' => true]; } $rowTemp['yield'] = $row; continue; } // Fill yield if ($rowTemp['yield'] === $row) { if (!isset($cookbook['yield'])) { $cookbook['yield'] = []; $cookbook['yield']['Quantity'] = $val; } else { $cookbook['yield']['unit'] = $val; } continue; } // Find portionSize row if (!isset($rowTemp['portionSize'])) { if (!preg_match('/^portion[\\s\\n]*size$/i', $val)) { unlink($filePath); LogUtil::error(date('Y-m-d h:i:s') . ' ukkklp parse excel to cookbook error: portionSize is required'); return ['contentError' => true]; } $rowTemp['portionSize'] = $row; continue; } // Fill portionSize if ($rowTemp['portionSize'] === $row) { $cookbook['portionSize'] = $val; $row++; $col = -1; continue; } //Find ingredient quantity colume if (!isset($colTemp['idtQuantity'])) { if (!preg_match('/^quantity$/i', $val)) { unlink($filePath); LogUtil::error(date('Y-m-d h:i:s') . ' ukkklp parse excel to cookbook error: ingredient quantity is required'); return ['contentError' => true]; } $colTemp['idtQuantity'] = $col; continue; } //Find ingredient unit colume if (!isset($colTemp['idtUnit'])) { if (!preg_match('/^unit$/i', $val)) { unlink($filePath); LogUtil::error(date('Y-m-d h:i:s') . ' ukkklp parse excel to cookbook error: ingredient unit is required'); return ['contentError' => true]; } $colTemp['idtUnit'] = $col; continue; } //Find ingredient name colume if (!isset($colTemp['idtName'])) { if (!preg_match('/^ingredient[\\s\\n]*name$/i', $val)) { unlink($filePath); LogUtil::error(date('Y-m-d h:i:s') . ' ukkklp parse excel to cookbook error: ingredient name is required'); return ['contentError' => true]; } $colTemp['idtName'] = $col; continue; } //Fill ingredient if (!isset($cookbook['ingredient'])) { $cookbook['ingredient'] = []; } if (!$ingredientFinished) { // Fill ingredient quantity if ($col === $colTemp['idtQuantity']) { $cookbook['ingredient'][$row]['quantity'] = $val; } // Fill ingredient unit if ($col === $colTemp['idtUnit']) { $cookbook['ingredient'][$row]['unit'] = $val; } // Fill ingredient name if ($col === $colTemp['idtName']) { $cookbook['ingredient'][$row]['name'] = $val; } $ingredientFinished = preg_match('/^preparation[\\s\\n]*method$/i', $val); if ($ingredientFinished) { array_pop($cookbook['ingredient']); } continue; } // Find preparation method description colume if (!isset($colTemp['ptnDescription'])) { if (preg_match('/^description$/i', $val)) { $colTemp['ptnDescription'] = $col; } continue; } //Fill preparation method if (!isset($cookbook['preparationMethod'])) { $cookbook['preparationMethod'] = []; } // Fill preparation method description if ($col === $colTemp['ptnDescription']) { $cookbook['preparationMethod'][$row]['description'] = []; $arr = preg_split('/靈感來源\\s*or\\s*貼心小提示/i', $val); if (empty($arr) || sizeof($arr) !== 2) { $cookbook['preparationMethod'][$row]['description']['step'] = $val; $cookbook['preparationMethod'][$row]['description']['creativeExperience'] = ''; } else { $cookbook['preparationMethod'][$row]['description']['step'] = trim($arr[0]); $cookbook['preparationMethod'][$row]['description']['creativeExperience'] = trim($arr[1]); } unset($arr); } } } if (!isset($cookbook['ingredient']) || !isset($cookbook['preparationMethod'])) { unlink($filePath); return ['contentError' => true]; } $cookbook['ingredient'] = array_values($cookbook['ingredient']); $tmpInfo = $this->_findProductUrlAndSave($cookbook['ingredient']); $cookbook['ingredient'] = $tmpInfo['ingredients']; unset($tmpInfo); $cookbook['preparationMethod'] = array_values($cookbook['preparationMethod']); for ($i = 0; $i < sizeof($cookbook['ingredient']); $i++) { $cookbook['ingredient'][$i]['id'] = $this->_getRandomId(); } $cookbook['content'] = $cookbook['preparationMethod'][0]['description']['step']; $cookbook['creativeExperience'] = $cookbook['preparationMethod'][0]['description']['creativeExperience']; $cookbooks[] = $cookbook; unset($rowTemp); unset($colTemp); unset($cookbook); } unlink($filePath); if (empty($cookbooks)) { return []; } $results = Cookbook::saveImportedCookbooks($cookbooks, $this->getAccountId()); $cookbookBatch = new CookbookBatch(); $accessToken = Token::getToken(); $user = User::findOne(['_id' => $accessToken->userId]); $cookbookBatch->operator = $user->name; $cookbookBatch->cookbooks = $results; $cookbookBatch->hasImages = false; $cookbookBatch->accountId = $this->getAccountId(); $cookbookBatch->createdTime = new \MongoDate(); $cookbookBatch->insert(); return sizeof($results); }
/** * Mark all messages as read or delete all read messages * * <b>Request Type</b>: PUT<br/><br/> * <b>Request Endpoint</b>:http://{server-domain}/api/common/message/update<br/><br/> * <b>Content-type</b>: application/json<br/><br/> * <b>Summary</b>: This api is used for mark all messages as read or delete all read messages * <br/><br/> * * <b>Request Params</b>:<br/> * isRead: integer, the message read status * <br/><br/> * * <b>Response Params:</b><br/> * status: string, update result * <br/><br/> * * <b>Request Example:</b><br/> * <pre> * { * "isRead": 1 * } * </pre> * <br/><br/> * * <b>Response Example</b>:<br/> * <pre> * { * 'status': 'ok' * } * </pre> */ public function actionUpdate() { $token = $this->getAccessToken(); $isRead = (bool) $this->getParams('isRead', false); $tokenInfo = Token::getToken($token); $accountId = $tokenInfo->accountId; $userId = $tokenInfo->userId; $condition = ['accountId' => $accountId, '$or' => [['to.target' => Message::TO_TARGET_ACCOUNT], ['to.target' => Message::TO_TARGET_USER, 'to.id' => $userId]], 'isRead' => $isRead]; if ($isRead) { Message::deleteAll($condition); } else { Message::updateAll(['isRead' => true, 'readAt' => new \MongoDate()], $condition); } return ['status' => 'ok']; }
/** * Sync the stores data to wechat */ public function actionPush() { $channelIds = $this->getParams('channelIds'); $storeIds = $this->getParams('storeIds'); $isAllStores = $this->getParams('isAllStores', false); if (empty($channelIds) || empty($storeIds) && !$isAllStores) { throw new BadRequestHttpException(Yii::t('common', 'parameters_missing')); } $result = ['finished' => true]; $token = Token::getToken(); $accountId = $token->accountId; if ($isAllStores) { $stores = Store::find()->select(['_id'])->where(['accountId' => $accountId, 'isDeleted' => Store::NOT_DELETED])->all(); if (!empty($stores)) { $storeIds = []; foreach ($stores as $store) { $storeIds[] = (string) $store->_id; } } } $args = ['accountId' => (string) $accountId, 'channels' => $channelIds, 'storeIds' => $storeIds, 'userId' => (string) $token->userId, 'description' => 'Direct: Sync the stores data to wechat']; $token = Yii::$app->job->create('backend\\modules\\channel\\job\\StoreSync', $args); $result = ['finished' => false, 'token' => $token]; return $result; }
public function actionUpdate($id) { $params = $this->getParams(); $user = User::findByPk($id); $token = $this->getAccessToken(); $name = $this->getParams('name'); if (empty($name)) { throw new InvalidParameterException(['name' => Yii::t('common', 'required_filed')]); } $user->load($params, ''); $lauguage = $user->language; if ($user->save() && Token::channgeLanguage($token, $lauguage)) { $user->_id .= ''; return $user; } else { throw new ServerErrorHttpException('Fail to update user'); } }
/** * Add a channel into help desk setting * * <b>Request Type: </b>PUT<br/> * <b>Request Endpoint: </b>http://{server-domain}/api/helpdesk/setting/add-channel<br/> * <b>Content-type: </b>Application/json<br/> * <b>Summary: </b>This api is for adding a channel into help desk setting.<br/> * * <b>Request Example: </b> * <pre> * { * "settingId": '52d791327ae252f9149547cb', * "channelId": '52d791307ae252f9149547c9' * } * </pre> */ public function actionAddChannel() { $settingId = $this->getParams('settingId'); $channelIdStr = $this->getParams('channelId'); $accountId = $this->getAccountId(); if (!empty($channelIdStr) && !empty($settingId)) { $channelIds = explode(',', $channelIdStr); $helpDeskSetting = HelpDeskSetting::getInstance($accountId); $customerServicesSessionExpire = intval($helpDeskSetting->maxWaitTime) * 60 * 1000; $channels = []; foreach ($channelIds as $channelId) { array_push($channels, ['id' => $channelId, 'isSet' => false]); $accessToken = Token::createForWechat($accountId); Yii::$app->weConnect->updateCustomerServiceSetting($channelId, $customerServicesSessionExpire, $accessToken->accessToken); } $settingId = new \MongoId($settingId); // Add a channel into help desk setting $result = HelpDeskSetting::updateAll(['$addToSet' => ['channels' => ['$each' => $channels]]], ['_id' => $settingId]); if ($result) { return $channels; } throw new ServerErrorHttpException('add channel fail'); } throw new BadRequestHttpException('parameters missing'); }
/** * validateUnique validates that the attribute value is unique with isDeleted in the specified database table. * * The following is an example of validation rules using this validator: * * ```php * // a1 needs to be unique * ['a1', 'validateUnique'] * ``` * @author Harry Sun */ public function validateUnique($attribute) { $token = Token::getToken(); $condition = [$attribute => $this->{$attribute}]; if (!empty($token->accountId)) { $condition['accountId'] = $token->accountId; } else { if (!empty($this->accountId)) { $condition['accountId'] = $this->accountId; } } $model = self::findOne($condition); if (!empty($model) && $model->_id . '' !== $this->_id . '') { $this->addError($attribute, $this->{$attribute} . " has been used."); } }
/** * Logout * * <b>Request Type </b>:GET * <b>Request Endpoints </b>: http://{server-domain}/api/chat/site/logout * <b>Content-type</b>: application/json<br/><br/> * <b>Summary</b>: This api is used for the user to logout. * * <b>Request Example </b>: * <pre> * http://{server-domain}/api/chat/site/logout?accesstoken=7f2d1e92-9629-8429-00be-2d9c6d64acdb * </pre> * **/ public function actionLogout() { $accessToken = $this->getQuery('accesstoken'); if (empty($accessToken)) { return ['token' => $accessToken]; } Token::deleteAll(['accessToken' => $accessToken]); return ['token' => $accessToken]; }
/** * Query all menu actions * * <b>Request Type</b>: GET<br/><br/> * <b>Request Endpoint</b>:http://{server-domain}/api/common/channel/menu-action<br/><br/> * <b>Content-type</b>: application/json<br/><br/> * <b>Summary</b>: This api is used for querying all menu actions. * <br/><br/> * * <b>Request Params</b>:<br/> * <br/><br/> * * <b>Request Example:</b><br/> * <br/><br/> * * <b>Response Example</b>:<br/> * <pre> * { * "member": { * "title": "channel_menu_member", * "keycode": "USER_CENTER", * "actionKey": "channel_menu_member_title", * "msgType": "URL", * "content": "http://wm.com/api/mobile/member?appId=wx2df5d7e4ce8a04ca&channelId=54d9c155e4b0abe717853ee1" * }, * "helpdesk": { * "title": "helpdesk", * "keycode": "CUSTOMER_SERVICE", * "actionKey": "channel_menu_helpdesk_title", * "msgType": "", * "content": false * } * } * </pre> */ public function actionMenuAction() { $channelId = $this->getQuery('channelId'); $accountId = Token::getAccountId(); return Yii::$app->channelMenu->getMenuActions($channelId, $accountId); }
public static function getByAccesstoken($accesstoken) { return Token::findOne(['accessToken' => $accesstoken]); }
public static function getDrawCount() { return self::find(['accountId' => Token::getAccountId()])->count(); }
/** * Follower bind to be a member. * * <b>Request Type</b>: POST<br/><br/> * <b>Request Endpoint</b>:http://{server-domain}/api/mobile/bind<br/><br/> * <b>Response Content-type</b>: application/json<br/><br/> * <b>Summary</b>: This api is used for follower bind. * <br/><br/> * * <b>Request Params</b>:<br/> * mobile: string<br/> * openId: string<br/> * unionId: string<br/> * channelId: string<br/> * captcha: string<br/> * <br/><br/> * * <b>Response Params:</b><br/> * <br/><br/> * * <br/><br/> * * <b>Response Example</b>:<br/> * <pre> * { * "message": "OK", * "data": "http://wm.com?memberId=55d29e86d6f97f72618b4569" * </pre> */ public function actionBind() { //set language zh_cn when bind Yii::$app->language = LanguageUtil::LANGUAGE_ZH; $params = $this->getParams(); if (empty($params['mobile']) || empty($params['openId']) || empty($params['channelId']) || empty($params['captcha'])) { throw new BadRequestHttpException('missing param'); } $isTest = false; if ($params['mobile'] == self::TEST_PHONE && $params['captcha'] == self::TEST_CODE) { $isTest = true; } else { $this->attachBehavior('CaptchaBehavior', new CaptchaBehavior()); $this->checkCaptcha($params['mobile'], $params['captcha']); } //get accountId $openId = $params['openId']; $channel = Channel::getEnableByChannelId($params['channelId']); $origin = $channel->origin; $accountId = $channel->accountId; //create accessToken $token = Token::createForMobile($accountId); if (empty($token['accessToken'])) { throw new ServerErrorHttpException('Failed to create token for unknown reason.'); } $accessToken = $token['accessToken']; $this->setAccessToken($accessToken); //if member has bind if (empty($params['unionId'])) { $member = Member::getByOpenId($openId); } else { $unionId = $params['unionId']; $member = Member::getByUnionid($unionId); } if (!empty($member)) { $memberId = (string) $member->_id; $url = $this->buildBindRedirect($memberId, $params); return ['message' => 'OK', 'data' => $url]; } //check mobile has been bind $member = Member::getByMobile($params['mobile'], new \MongoId($accountId)); if (!empty($member)) { throw new InvalidParameterException(['phone' => Yii::t('common', 'phone_has_been_bound')]); } $follower = Yii::$app->weConnect->getFollowerByOriginId($openId, $params['channelId']); $originScene = empty($follower['firstSubscribeSource']) ? '' : $follower['firstSubscribeSource']; //init avatar and location $avatar = !empty($follower['headerImgUrl']) ? $follower['headerImgUrl'] : Yii::$app->params['defaultAvatar']; $location = []; !empty($follower['city']) ? $location['city'] = $follower['city'] : null; !empty($follower['province']) ? $location['province'] = $follower['province'] : null; !empty($follower['country']) ? $location['country'] = $follower['country'] : null; LogUtil::info(['message' => 'get follower info', 'follower' => $follower], 'channel'); //init member properties $memberProperties = MemberProperty::getByAccount($accountId); $propertyMobile = []; $propertyGender = []; $propertyName = []; $properties = []; foreach ($memberProperties as $memberProperty) { if ($memberProperty['name'] == Member::DEFAULT_PROPERTIES_MOBILE) { $propertyMobile['id'] = $memberProperty['_id']; $propertyMobile['name'] = $memberProperty['name']; $propertyMobile['value'] = $params['mobile']; $properties[] = $propertyMobile; } if ($memberProperty['name'] == Member::DEFAULT_PROPERTIES_GENDER) { $propertyGender['id'] = $memberProperty['_id']; $propertyGender['name'] = $memberProperty['name']; $propertyGender['value'] = !empty($follower['gender']) ? strtolower($follower['gender']) : 'male'; $properties[] = $propertyGender; } if ($memberProperty['name'] == Member::DEFAULT_PROPERTIES_NAME) { $propertyName['id'] = $memberProperty['_id']; $propertyName['name'] = $memberProperty['name']; $propertyName['value'] = $follower['nickname']; $properties[] = $propertyName; } } //get default card $card = MemberShipCard::getDefault($accountId); $memberId = new \MongoId(); $memberAttribute = ['$set' => ['_id' => $memberId, 'avatar' => $avatar, 'cardId' => $card['_id'], 'location' => $location, 'score' => 0, 'socialAccountId' => $params['channelId'], 'properties' => $properties, 'openId' => $openId, 'origin' => $origin, 'originScene' => $originScene, 'unionId' => empty($unionId) ? '' : $unionId, 'accountId' => $accountId, 'cardNumber' => Member::generateCardNumber($card['_id']), 'cardProvideTime' => new \MongoDate(), 'createdAt' => new \MongoDate(), 'socials' => [], 'isDeleted' => false]]; if (!$isTest) { $result = Member::updateAll($memberAttribute, ['openId' => $openId], ['upsert' => true]); } else { $result = true; } if ($result) { // reword score first bind card $this->attachBehavior('MemberBehavior', new MemberBehavior()); $this->updateItemByScoreRule(Member::findByPk($memberId)); Yii::$app->qrcode->create(Yii::$app->request->hostInfo, Qrcode::TYPE_MEMBER, $memberId, $accountId); $memberId = (string) $memberId; $url = $this->buildBindRedirect($memberId, $params); return ['message' => 'OK', 'data' => $url]; } else { LogUtil::error(['error' => 'member save error', 'params' => Json::encode($member)], 'member'); throw new ServerErrorHttpException("bind fail"); } }
/** * Get accountId and company when exchange * @param array $params * @return array */ public function exchange($params) { $token = Token::getToken(); \Yii::$app->language = empty($token->language) ? LanguageUtil::DEFAULT_LANGUAGE : $token->language; $this->checkCode($params); $accountId = $params['accountId']; $account = Account::findByPk($accountId); return ['accountId' => $accountId, 'company' => empty($account->company) ? null : $account->company]; }