示例#1
0
 /**
  * Finds the Product model based on its primary key value.
  * If the model is not found, a 404 HTTP exception will be thrown.
  * @param integer $id
  * @return Product the loaded model
  * @throws NotFoundHttpException if the model cannot be found
  */
 protected function findModel($id)
 {
     if (($model = Product::findOne($id)) !== null) {
         return $model;
     } else {
         throw new NotFoundHttpException('The requested page does not exist.');
     }
 }
示例#2
0
 /**
  * The default implementation returns the names of the columns whose values have been populated into productCategory.
  */
 public function fields()
 {
     return array_merge(parent::fields(), ['name', 'properties', 'isDeleteCategory' => function () {
         $condition = ['category.id' => $this->_id];
         $info = Product::findOne($condition);
         if (!empty($info) || self::RESERVATION_CATEGORY_NAME == $this->name) {
             return false;
         } else {
             return true;
         }
     }]);
 }
 public function actionDelete($id)
 {
     $idstrList = explode(',', $id);
     $ids = [];
     foreach ($idstrList as $perId) {
         $ids[] = new MongoId($perId);
     }
     $where = ['_id' => ['$in' => $ids]];
     $goodsWhere = ['productId' => ['$in' => $ids]];
     $result = Product::findOne(array_merge($where, ['isBindCode' => true]));
     if (!empty($result)) {
         throw new BadRequestHttpException(Yii::t('product', 'can_not_delete_before_promocode'));
     }
     if (!empty(Campaign::getByProductIds($ids)) || !empty(Goods::findOne($goodsWhere))) {
         throw new BadRequestHttpException(Yii::t('product', 'can_not_delete'));
     }
     if (Product::deleteAll($where) == false) {
         throw new ServerErrorHttpException('Failed to delete the object for unknown reason.');
     }
     //delete the product intro
     ProductInfo::deleteAll($where);
     //delete goods and storeGoods
     $this->attachBehavior('ProductBehavior', new ProductBehavior());
     $this->delete($ids);
     Yii::$app->getResponse()->setStatusCode(204);
 }
 /**
  * update the property
  * @param $id,int,proprty id
  * @param $params,array
  * @param $accountId,MongoId
  */
 public static function updateProperty($id, $params, $accountId)
 {
     //update category property
     $where = ['accountId' => $accountId, '_id' => new \MongoId($id), 'properties.id' => $params['propertyId']];
     $categoryPropertyInfo = ProductCategory::findOne($where);
     if ($categoryPropertyInfo) {
         //only update the name and isrequired
         $addproperties = [];
         if (!empty($categoryPropertyInfo->properties)) {
             $where = ['properties.id' => $params['propertyId']];
             ProductCategory::updateAll(['$set' => ['properties.$.name' => $params['name'], 'properties.$.isRequired' => $params['isRequired']]], $where);
         }
         //check whether have properties
         $productInfo = Product::findOne(['category.id' => new \MongoId($id)]);
         if ($productInfo) {
             $where = ['category.properties.id' => $params['propertyId']];
             $updateData = ['category.properties.$.name' => $params['name'], 'category.properties.$.value' => $params['defaultValue']];
             Product::updateAll(['$set' => $updateData], $where);
             unset($productInfo);
         }
         unset($where);
         return $categoryPropertyInfo;
     } else {
         throw new BadRequestHttpException("categoryId or propertyId invalid");
     }
 }
 /**
  * check the code in the excel
  */
 public function actionCheckCode()
 {
     $params = Yii::$app->request->post();
     $productId = $params['productId'];
     //$productId = '1429862376675049';
     if (empty($productId)) {
         throw new BadRequestHttpException('missing param productId');
     }
     $fileKey = 'file';
     if (empty($_FILES[$fileKey])) {
         throw new BadRequestHttpException('missing param ' . $fileKey);
     }
     $accountId = $this->getAccountId();
     $where = ['accountId' => $accountId, 'sku' => $productId];
     $result = Product::findOne($where);
     LogUtil::info(['file' => $_FILES, 'where' => $where], 'promotimeCode');
     if (empty($result)) {
         throw new BadRequestHttpException(Yii::t("product", "product_deleted"));
     }
     unset($where);
     //upload config
     $config = ['maxSize' => self::MAXSIZE, 'allowFiles' => self::$ALLOWFILES, 'pathFormat' => self::PATHFORMAT, 'privateBucket' => true];
     //upload to qiniu
     $upload = new Uploader($fileKey, $config, 'upload', 1);
     $fileInfo = $upload->getFileInfo();
     $rootPath = Yii::$app->getRuntimePath() . '/code/';
     if (!is_dir($rootPath)) {
         FileHelper::createDirectory($rootPath, 0777, true);
     }
     $fileName = $fileInfo['title'];
     $locationPath = $rootPath . $fileName . $fileInfo['type'];
     if (empty($fileName)) {
         throw new InvalidParameterException($fileInfo['state']);
     }
     $checkArgs = ['qiniuBucket' => QINIU_DOMAIN_PRIVATE, 'productId' => $productId, 'filePath' => Yii::$app->qiniu->getPrivateUrl($fileName), 'locationPath' => $locationPath, 'fileName' => $fileName, 'accountId' => (string) $accountId, 'description' => 'Direct: Check if promotion codes to be imported is unique'];
     $jobId = Yii::$app->job->create('backend\\modules\\product\\job\\PromotionCheckCode', $checkArgs);
     return ['message' => 'OK', 'data' => ['token' => $jobId, 'filename' => $fileName]];
 }
示例#6
0
 public function getById($id)
 {
     return ModelProduct::findOne(['_id' => $id]);
 }
示例#7
0
 public function perform()
 {
     # Run task
     $args = $this->args;
     //job update productId
     switch ($args['type']) {
         case self::JOB_UPDATE:
             if (!empty($args['oldProductId']) && !empty($args['newProductId'])) {
                 ModelPromotionCode::updateAll(['$set' => ['productId' => new \MongoId($args['newProductId'])]], ['productId' => new \MongoId($args['oldProductId']), 'isUsed' => false]);
                 return true;
             }
             break;
         case self::JOB_GENERATE:
             //job generateCodes
             if (empty($accountId = $args['accountId']) || empty($productId = $args['productId']) || !array_key_exists('count', $args)) {
                 ResqueUtil::log(['error' => 'generate codes params error', 'param' => $args]);
                 return false;
             }
             $createdAt = new \MongoDate(time(), 0);
             $count = $args['count'];
             $successCount = 0;
             $batchCount = $count / self::PER_BATCH;
             for ($i = 0; $i < $batchCount; $i++) {
                 $restCount = $count - self::PER_BATCH * $i;
                 $rowsCount = $restCount >= self::PER_BATCH ? self::PER_BATCH : $restCount;
                 $codes = ModelPromotionCode::generateCodes($rowsCount, new \MongoId($productId));
                 ResqueUtil::log(['info' => 'generate code ok', 'param' => $args]);
                 $promotionCodes = [];
                 foreach ($codes as $code) {
                     $promotionCode = ['productId' => new \MongoId($productId), 'code' => $code, 'isUsed' => false, 'accountId' => new \MongoId($accountId), 'createdAt' => $createdAt, 'random' => rand()];
                     $promotionCodes[] = $promotionCode;
                 }
                 ResqueUtil::log(['info' => 'generate codes', 'param' => $args]);
                 $result = ModelPromotionCode::batchInsert($promotionCodes);
                 if (!$result) {
                     ResqueUtil::log(['error' => 'save codes failed', 'param' => $args, 'success count' => $successCount]);
                 } else {
                     $successCount += $rowsCount;
                 }
             }
             //change the isBindCode
             $this->changeProductStatus(new \MongoId($productId));
             return true;
         case self::JOB_DELETE:
             if (!empty($args['productId'])) {
                 $productId = new \MongoId($args['productId']);
                 $condition = ['productId' => $productId];
             } else {
                 ResqueUtil::log(['error' => 'delete codes params error', 'param' => $args]);
                 return false;
             }
             if (!empty($args['createdAt'])) {
                 $createdAt = new \MongoDate($args['createdAt']);
                 $condition = array_merge($condition, ['createdAt' => $createdAt]);
             }
             //if delete all code successfully,judge to change isBindCode
             if (ModelPromotionCode::deleteAll($condition)) {
                 $count = ModelPromotionCode::count(["productId" => $productId]);
                 if ($count <= 0) {
                     Product::updateAll(['isBindCode' => false], ['_id' => $productId]);
                 }
             }
             return true;
         case self::JOB_INSERT:
             if (!isset($args['accountId']) || !isset($args['productId']) || !isset($args['filename'])) {
                 ResqueUtil::log(['error' => 'missing param accountId or productId or filename', 'param' => $args]);
                 return false;
             }
             if (!isset($args['import'])) {
                 $args['import'] = false;
             }
             $redis = \Yii::$app->cache->redis;
             $createdAt = new \MongoDate(time());
             $product = Product::findOne($args['productId']);
             if (empty($product)) {
                 ResqueUtil::log(['error' => 'product has been deleted', 'param' => $args]);
                 return false;
             }
             $productId = $product['sku'];
             $cacheKey = $args['accountId'] . "_" . $productId . "_" . $args['filename'];
             $cacheSet = PromotionCheckCode::SET_HEAD . md5($cacheKey);
             $total = $redis->scard($cacheSet);
             //redis hash key name
             $cacheHash = md5($cacheKey);
             $k = 0;
             $promotionCodes = [];
             for ($i = 1; $i <= $total; ++$i) {
                 // insert the code
                 if ($args['import']) {
                     $key = $redis->spop($cacheSet);
                     if (!empty($key)) {
                         $promotionCode = ['productId' => new \MongoId($args['productId']), 'code' => $key, 'isUsed' => false, 'accountId' => new \MongoId($args['accountId']), 'createdAt' => $createdAt];
                         $promotionCodes[$k++] = $promotionCode;
                     }
                     //set default value in redis to avoid to insert data in mongo failly
                     $redis->HSET($cacheHash, 'right', 0);
                     $redis->HSET($cacheHash, 'wrong', self::PROMO_CODE_REPEATED);
                     //have data to store
                     if (count($promotionCodes) > 0) {
                         if ($k % self::PER_BATCH == 0 || $i == $total) {
                             try {
                                 $result = ModelPromotionCode::batchInsert($promotionCodes);
                             } catch (MongoDuplicateKeyException $e) {
                                 return false;
                             }
                             $promotionCodes = [];
                             if (!$result) {
                                 ResqueUtil::log(['error' => 'save codes failed', 'param' => $args, 'success count' => $i - count($promotionCodes)]);
                             }
                         }
                     }
                 }
             }
             $redis->del($cacheSet);
             //change the isBindCode
             $this->changeProductStatus($product['_id']);
             //update duplicate key error
             $redis->HSET($cacheHash, 'wrong', 0);
             return true;
             break;
         case self::JOB_DELETE_REDIS_CODE:
             if (!isset($args['filename']) || !isset($args['productId']) || !isset($args['accountId'])) {
                 ResqueUtil::log(['error' => 'missing param', 'param' => $args]);
                 return false;
             }
             $redis = \Yii::$app->cache->redis;
             $cacheSet = PromotionCheckCode::SET_HEAD . md5($args['accountId'] . '_' . $args['productId'] . '_' . $args['filename']);
             $redis->del($cacheSet);
             unset($commonKey, $cacheTotalKey, $count);
             return true;
             break;
         default:
             break;
     }
 }
示例#8
0
 /**
  * check the sku
  * @param $code string
  * @return product info
  */
 public static function getSku($code)
 {
     return Product::findOne(['sku' => $code]);
 }