/** * 只通过 treeKey 和 name 来加载一个 节点 * * 注意: treeKey , name 组合未必是唯一的,只能你自己保证唯一性了 * * @param string $treeKey * @param string $name * @param int $ttl * * @return DataMapper * @throws \InvalidArgumentException */ public function loadTreeNodeWithTreeKeyAndName($treeKey, $name, $ttl = 0) { if (empty($treeKey) || empty($name)) { throw new \InvalidArgumentException('treeKey, name can not be empty'); } $dataMapper = new DataMapper('meta'); $dataMapper->loadOne(array('meta_type = ? and meta_key = ? and meta_name = ?', Tree::META_TYPE, $treeKey, $name), null, $ttl); return $dataMapper; }
/** * 根据用户 id 取得用户的第一个地址 * * @return object 用户信息记录 * @param int $userId 用户数字 ID * @param int $ttl 缓存时间 * * */ public function loadUserFirstAddress($userId, $ttl = 0) { // 参数验证 $validator = new Validator(array('userId' => $userId, 'ttl' => $ttl)); $userId = $validator->required()->digits()->min(1)->validate('userId'); $ttl = $validator->digits()->min(0)->validate('ttl'); $this->validate($validator); $user = new DataMapper('user_address'); $user->loadOne(array('user_id=?', $userId), array('order' => 'address_id asc', 'offset' => 0, 'limit' => 1), $ttl); return $user; }
/** * 给出一组商品 ID,取得所有商品的图片, * 这是一个大查询,可能会很多数据,之所以加这个大查询的目的是, * 我们宁可要一个几百条记录的大查询,也不要几百个一条记录的小查询 * * @return array 图像集合 array(array(图片1), array(图片2)) * * @param array $goodsIdArray 商品的 ID 数组 * @param int $ttl 缓存时间 */ public function fetchGoodsGalleryArrayByGoodsIdArray(array $goodsIdArray, $ttl = 0) { if (!is_array($goodsIdArray) || empty($goodsIdArray)) { throw new \InvalidArgumentException('goodsIdArray must be an array not empty'); } // 参数验证 $validator = new Validator(array('ttl' => $ttl)); $ttl = $validator->digits()->min(0)->validate('ttl'); $this->validate($validator); $dataMapper = new DataMapper('goods_gallery'); $sqlInClause = QueryBuilder::buildInCondition('goods_id', $goodsIdArray, \PDO::PARAM_INT); return $dataMapper->find(array($sqlInClause), array('order' => 'goods_id asc , img_sort_order desc, img_id asc'), $ttl); }
/** * 检查 order_goods 对应的评论记录是否已经存在 * * @param int $rec_id * * @return bool */ public function isOrderGoodsCommentExist($rec_id) { if (!$rec_id) { return false; } // 参数验证 $validator = new Validator(array('rec_id' => $rec_id)); $rec_id = $validator->required()->digits()->min(1)->validate('rec_id'); $this->validate($validator); $dataMapper = new DataMapper('goods_comment'); $dataMapper->loadOne(array('rec_id = ?', $rec_id), null, 0); return !$dataMapper->isEmpty(); }
/** * 记录管理员的操作日志 * * @param string $operate 操作 * @param string $operate_desc 操作描述 * @param string $operate_data 操作数据,用于记录一些重要数据 */ public static function logAdminOperate($operate, $operate_desc, $operate_data) { $dataMapper = new DataMapper('admin_log'); $authAdminUser = AuthHelper::getAuthUser(); $dataMapper->user_id = $authAdminUser['user_id']; $dataMapper->user_name = $authAdminUser['user_name']; $dataMapper->operate = $operate; $dataMapper->operate_desc = $operate_desc; $dataMapper->operate_time = Time::gmTime(); $dataMapper->operate_data = $operate_data; $dataMapper->save(); unset($dataMapper); }
public function run(array $params) { global $f3; // 1. reset 整个数据库 printLog('Begin Reset Database', 'ResetData'); $dbEngine = DataMapper::getDbEngine(); // 解析 sql 文件,导入数据 $sqlFileContent = file_get_contents(CONSOLE_PATH . '/../install/Asset/data/bzfshop.sql'); $sqlFileContent = SqlHelper::removeComment($sqlFileContent); $sqlArray = SqlHelper::splitToSqlArray($sqlFileContent, ';'); unset($sqlFileContent); foreach ($sqlArray as $sqlQuery) { $queryObject = $dbEngine->prepare($sqlQuery); $queryObject->execute(); unset($sqlQuery); unset($queryObject); } unset($sqlArray); printLog('End Reset Database', 'ResetData'); // 2. 删除 /data 目录下的所有目录 printLog('remove everything under /data', 'ResetData'); $this->removeAllDirInsideDir($f3->get('sysConfig[data_path_root]')); // 3. 删除 RunTime 目录下所有目录 printLog('remove everything in Runtime', 'ResetData'); $this->removeAllDirInsideDir($f3->get('sysConfig[runtime_path]') . DIRECTORY_SEPARATOR . 'Log/'); $this->removeAllDirInsideDir($f3->get('sysConfig[runtime_path]') . DIRECTORY_SEPARATOR . 'Smarty/'); $this->removeAllDirInsideDir($f3->get('sysConfig[runtime_path]') . DIRECTORY_SEPARATOR . 'Temp/'); // 4. 清除 F3 的缓存 $f3->clear('CACHE'); printLog('ResetData Done', 'ResetData'); }
public function run(array $params) { global $f3; $goodsBasicService = new GoodsBasicService(); $goods = $goodsBasicService->loadGoodsById('20'); $sql = 'update ' . DataMapper::tableName('goods') . ' set goods_after_service = ? '; $dbEngine = DataMapper::getDbEngine(); $dbEngine->exec($sql, array(1 => $goods['goods_after_service'])); }
public function run(array $params) { global $f3; // 每次处理多少条记录 $batchProcessCount = 100; $baseService = new BaseService(); $totalGoodsCount = $baseService->_countArray('goods', null); // 记录处理开始 for ($offset = 0; $offset < $totalGoodsCount; $offset += $batchProcessCount) { $goodsArray = $baseService->_fetchArray('goods', 'goods_id', null, array('order' => 'goods_id asc'), $offset, $batchProcessCount); foreach ($goodsArray as $goodsItem) { $sql = "update " . DataMapper::tableName('goods') . ' set ' . ' user_buy_number = (select sum(goods_number) from ' . DataMapper::tableName('order_goods') . ' where goods_id = ? )' . ' ,user_pay_number = (select sum(goods_number) from ' . DataMapper::tableName('order_goods') . ' where goods_id = ? and order_goods_status > 0)' . ' where goods_id = ? order by goods_id asc limit 1 '; $dbEngine = DataMapper::getDbEngine(); $dbEngine->exec($sql, array(1 => $goodsItem['goods_id'], $goodsItem['goods_id'], $goodsItem['goods_id'])); } unset($goodsArray); printLog('calculate goods buy number offset : ' . $offset); } printLog('calculate goods buy number finished , offset : ' . $offset); }
/** * 把购物车中的信息保存到数据库订单中,如果订单已经存在,则更新订单数据, * 注意:这个方法必须在购物车计算完成之后调用,否则无法正确保存计算之后的数据 * * @return mixed 失败返回 false,成功返回订单记录 * * @param int $userId 用户的数字 ID * @param string $username 用户名 */ public function saveOrder($userId, $username) { // 参数验证 $validator = new Validator(array('userId' => $userId)); $userId = $validator->required()->digits()->min(1)->validate('userId'); $this->validate($validator); $orderBasicService = new OrderBasicService(); $orderId = isset($this->cartContext->orderInfo) ? $this->cartContext->orderInfo['order_id'] : null; // 不允许创建空订单 if (!$orderId && $this->cartContext->isEmpty()) { return false; } // 是否需要新建订单 $isNewOrder = false; //检查这个 order_info 是否合法 if ($orderId) { $orderInfo = $orderBasicService->loadOrderInfoById($orderId); // 不存在的 order_info 或者 已经付款了的订单不能再用了 if ($orderInfo->isEmpty() || OrderBasicService::PS_UNPAYED != $orderInfo->pay_status) { $orderId = null; $isNewOrder = true; } } else { $isNewOrder = true; } // 创建 order_info 记录 $orderInfoArray = $this->cartContext->orderInfoValue; $orderInfoArray['user_id'] = $userId; $orderInfoArray['order_status'] = OrderBasicService::OS_UNCONFIRMED; $orderInfoArray['pay_status'] = OrderBasicService::PS_UNPAYED; if (!$orderId) { // 新订单,生成 add_time 和 order_sn $orderInfoArray['add_time'] = Time::gmTime(); $orderInfoArray['order_sn'] = OrderBasicService::generateOrderSn(); $orderInfoArray['system_id'] = Cart::$cartSystemId; // 记录订单来自于哪个系统 } elseif ($this->cartContext->isOrderAmountChange()) { // 去支付网关支付,如果订单金额发生变化都需要重新生成一次 order_sn ,因为订单金额如果发生变化,支付网关会拒绝支付 $orderInfoArray['order_sn'] = OrderBasicService::generateOrderSn(); } else { // do nothing } // 我们需要数据库事务的保障 $dbEngine = DataMapper::getDbEngine(); $dbEngine->begin(); // 记录余额支付 $oldSurplus = $this->cartContext->orderInfo ? $this->cartContext->orderInfo['surplus'] : 0; $newSurplus = $this->cartContext->getValue('surplus') > 0 ? $this->cartContext->getValue('surplus') : 0; // 记录使用红包 $oldBonusId = $this->cartContext->orderInfo ? $this->cartContext->orderInfo['bonus_id'] : 0; $newBonusId = $this->cartContext->getValue('bonus_id') > 0 ? $this->cartContext->getValue('bonus_id') : 0; // 创建订单或者更新 order_info $orderInfo = $orderBasicService->saveOrderInfo($orderId, $orderInfoArray); // 创建订单失败,返回 false if ($orderInfo->isEmpty()) { goto out_fail; } // 处理余额支付 if ($oldSurplus != $newSurplus) { // 前后发生了支付余额的改变 $accountLog = new AccountLog(); if ($oldSurplus > 0) { // 把之前的余额退还 $accountLog->logChange($userId, $oldSurplus, 0, 0, 0, '退还余额,订单:' . $orderInfo['order_id'], AccountLog::ACT_OTHER); } if ($newSurplus > 0) { // 使用余额 $accountLog->logChange($userId, -1 * $newSurplus, 0, 0, 0, '使用余额,订单:' . $orderInfo['order_id'], AccountLog::ACT_OTHER); } // 由于修改了用户信息,需要 reload 用户数据 AuthHelper::reloadAuthUser(); } // 处理红包支付 if ($oldBonusId != $newBonusId) { // 红包支付前后发生了变化 $bonusService = new Bonus(); if ($oldBonusId > 0) { //退还之前使用的红包 $bonusService->unUseBonus($oldBonusId); } if ($newBonusId > 0) { // 使用新的红包 $bonusService->useBonus($newBonusId, $orderInfo['order_id']); } } // 创建 orderRefer 对象,记录订单的来源 $orderReferService = new OrderReferService(); $orderRefer = $orderReferService->loadOrderReferByOrderId($orderInfo['order_id']); // order_refer 记录创建一次之后就不会再修改了 if ($orderRefer->isEmpty()) { // 新的 order_refer 记录,设置 order_id 值 $orderRefer->order_id = $orderInfo['order_id']; $orderRefer->create_time = Time::gmTime(); $orderRefer->login_type = AuthHelper::getLoginType(); global $f3; $orderReferArray = ReferHelper::parseOrderRefer($f3); if (!empty($orderReferArray)) { unset($orderReferArray['refer_id']); //清除掉危险字段 unset($orderReferArray['order_id']); //清除掉危险字段 $orderRefer->copyFrom($orderReferArray); } $orderRefer->save(); // 保存 order_refer 记录 } // 取得数据库中已经存在的 order_goods 列表 $dbOrderGoodsArray = array(); if ($orderId > 0) { $dbOrderGoodsArray = $orderBasicService->fetchOrderGoodsArray($orderId); } $stillExistOrderGoodsIdArray = array(); // 在购物车中仍然存在的 orderGoods 对象 // 创建 orderInfo 对应的 order_goods 对象 foreach ($this->cartContext->orderGoodsArray as $orderGoodsItem) { $orderGoodsValueArray = array(); $orderGoodsValueArray['order_id'] = $orderInfo['order_id']; //从 goods 中复制属性 $orderGoodsValueArray['goods_id'] = $orderGoodsItem->goods['goods_id']; $orderGoodsValueArray['goods_admin_user_id'] = $orderGoodsItem->goods['admin_user_id']; $orderGoodsValueArray['goods_admin_user_name'] = $orderGoodsItem->goods['admin_user_name']; $orderGoodsValueArray['goods_name'] = $orderGoodsItem->goods['goods_name_short']; $orderGoodsValueArray['goods_sn'] = $orderGoodsItem->goods['goods_sn']; $orderGoodsValueArray['warehouse'] = $orderGoodsItem->goods['warehouse']; $orderGoodsValueArray['shelf'] = $orderGoodsItem->goods['shelf']; $orderGoodsValueArray['market_price'] = $orderGoodsItem->goods['market_price']; $orderGoodsValueArray['shop_price'] = $orderGoodsItem->goods['shop_price']; $orderGoodsValueArray['shipping_fee'] = $orderGoodsItem->goods['shipping_fee']; $orderGoodsValueArray['is_real'] = $orderGoodsItem->goods['is_real']; $orderGoodsValueArray['extension_code'] = $orderGoodsItem->goods['extension_code']; $orderGoodsValueArray['suppliers_id'] = $orderGoodsItem->goods['suppliers_id']; $orderGoodsValueArray['suppliers_price'] = $orderGoodsItem->goods['suppliers_price']; $orderGoodsValueArray['suppliers_shipping_fee'] = $orderGoodsItem->goods['suppliers_shipping_fee']; // 合并一些因为计算而覆盖的值 $orderGoodsValueArray = array_merge($orderGoodsValueArray, $orderGoodsItem->orderGoodsValue); $orderGoodsId = null; if (!$isNewOrder && $orderGoodsItem->orderGoods) { // 如果不是新订单,并且已经存在的 order_goods,做更新 $orderGoodsId = $orderGoodsItem->orderGoods['rec_id']; $stillExistOrderGoodsIdArray[] = $orderGoodsId; } else { // 新建的 order_goods,我们需要取得它的 CPS 信息,CPS 信息只在一开始加入,后面不会再被修改了 $cpsArray = ReferHelper::getCpsParam($orderRefer, $orderInfo, $orderGoodsValueArray); if (!empty($cpsArray)) { $orderGoodsValueArray['cps_rate'] = isset($cpsArray['cps_rate']) ? $cpsArray['cps_rate'] : 0; $orderGoodsValueArray['cps_fix_fee'] = isset($cpsArray['cps_fix_fee']) ? $cpsArray['cps_fix_fee'] : 0; } } $orderGoods = $orderBasicService->saveOrderGoods($orderGoodsId, $orderInfo['order_id'], $orderGoodsValueArray); if ($orderGoods->isEmpty()) { //创建失败 goto out_fail; } } // 删除已经被用户删除的 order_goods foreach ($dbOrderGoodsArray as $dbOrderGoodsItem) { // 这个 order_goods 已经不存在了,删除它 if (!in_array($dbOrderGoodsItem['rec_id'], $stillExistOrderGoodsIdArray)) { $orderBasicService->removeOrderGoods($dbOrderGoodsItem['rec_id']); } } // 记录订单操作日志 $orderActionService = new OrderActionService(); $orderActionService->logOrderAction($orderInfo['order_id'], 0, OrderBasicService::OS_UNCONFIRMED, OrderBasicService::PS_UNPAYED, OrderGoodsService::OGS_UNPAY, '订单创建或更新', $username, 0, 0); $dbEngine->commit(); return $orderInfo; // 返回创建的订单 out_fail: $dbEngine->rollback(); return false; }
/** * 统计每个商品分类有多少商品,不计算子分类的商品数量(比如 A 下面有 B, C 分类, * 这里计算的 A 包含的商品数量不计算 B, C 的在内) * * @param int $ttl 缓存时间 * * @return array * 格式 array(array(cat_id, goods_count), ...) */ public function calcCategoryGoodsCount($ttl = 0) { $dbEngine = DataMapper::getDbEngine(); return $dbEngine->exec('select cat_id, count(1) as goods_count from ' . DataMapper::tableName('goods') . ' group by cat_id ', null, $ttl); }
/** * 用户认证,检查用户名密码是否正确 * * @return mixed 失败-返回false,成功-返回用户信息 * * @param string $username 用户名 * @param string $email 邮箱 * @param string $password 密码原文 * */ public function doAuthAdmin($username, $email, $password) { // 参数验证 if (Utils::isBlank($username) && Utils::isBlank($email)) { throw new \InvalidArgumentException('user_name, email can not both empty'); } $validator = new Validator(array('password' => $password)); $password = $validator->required()->validate('password'); $this->validate($validator); $sqlPrepare = array(); $sqlParam = array(); $sqlParam[0] = ''; // 查询语句 if (!Utils::isBlank($username)) { $sqlPrepare[] = 'user_name=?'; $sqlParam[] = $username; } if (!Utils::isBlank($email)) { $sqlPrepare[] = 'email=?'; $sqlParam[] = $email; } $sqlParam[0] = implode(' or ', $sqlPrepare); $admin = new DataMapper('admin_user'); $admin->loadOne($sqlParam); if ($admin->isEmpty()) { return false; } // 禁止登陆 if ($admin['disable']) { return false; } // 验证密码 if ($admin->password !== $this->encryptPassword($password, $admin->ec_salt)) { return false; } return $admin; }
/** * * 对 order_info , order_goods 做 inner_join 查询 * * @param array $condArray * @param int $offset * @param int $limit * @param int $ttl * * @return array */ public function fetchOrderInfoOrderGoodsArray(array $condArray, $offset = 0, $limit = 10, $ttl = 0) { // 参数验证 $validator = new Validator(array('condArray' => $condArray), ''); $condArray = $validator->requireArray(true)->validate('condArray'); $this->validate($validator); $tableInnerJoinStr = DataMapper::tableName('order_goods') . ' as og INNER JOIN ' . DataMapper::tableName('order_info') . ' as oi ON og.order_id = oi.order_id'; return $this->_fetchArray($tableInnerJoinStr, 'og.*, oi.user_id, oi.pay_time, oi.add_time, oi.order_sn, ' . 'oi.consignee, oi.address, oi.mobile', $condArray, array('order' => 'og.order_id desc, og.rec_id desc'), $offset, $limit, $ttl); }
/** * 重设 auto_increment 的值,自动计算最大的值 * * @string string $primaryKey 主键名称 * */ public function resetAutoIncValue(DataMapper $dataMapper, $primaryKey) { list($result) = $dataMapper->select('max(' . $primaryKey . ') as mvalue', null, null, 0); $autoIncValue = $result->getAdhocValue('mvalue') + 1; $this->setAutoIncValue($dataMapper, $autoIncValue); }
public function doUpdate($currentVersion) { // 更新数据库表 $sqlFileContent = <<<SQL -- 创建 cron 任务列表 CREATE TABLE IF NOT EXISTS `bzf_cron_task` ( `task_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, `user_name` varchar(32) DEFAULT NULL COMMENT '哪个用户添加的', `task_name` varchar(16) DEFAULT NULL COMMENT '任务名称', `task_desc` varchar(128) DEFAULT NULL COMMENT '任务描述', `task_time` int(10) unsigned NOT NULL DEFAULT 0 COMMENT '任务设定时间', `task_run_time` int(10) unsigned NOT NULL DEFAULT 0 COMMENT '任务实际运行时间', `task_class` varchar(128) NOT NULL COMMENT '任务的PHP Class', `task_param` text DEFAULT NULL, `search_param` varchar(64) DEFAULT NULL COMMENT '用于任务搜索', `return_code` int DEFAULT 0 COMMENT '任务设定时间', `return_message` varchar(128) DEFAULT NULL COMMENT '任务返回消息', PRIMARY KEY (`task_id`) ) DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; ALTER TABLE `bzf_cron_task` ADD INDEX ( `task_name` ) ; ALTER TABLE `bzf_cron_task` ADD INDEX ( `task_time` ) ; ALTER TABLE `bzf_cron_task` ADD INDEX ( `task_run_time` ) ; ALTER TABLE `bzf_cron_task` ADD INDEX ( `search_param` ) ; ALTER TABLE `bzf_cron_task` ADD INDEX ( `return_code` ) ; -- 记录管理员的行为 CREATE TABLE IF NOT EXISTS `bzf_admin_log` ( `log_id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` mediumint(8) unsigned NOT NULL , `user_name` varchar(60) DEFAULT NULL , `operate` varchar(16) DEFAULT NULL COMMENT '操作名称', `operate_desc` varchar(128) DEFAULT NULL COMMENT '操作描述', `operate_time` int(10) unsigned NOT NULL DEFAULT 0 COMMENT '操作时间', `operate_data` text DEFAULT NULL COMMENT '操作的数据记录', PRIMARY KEY (`log_id`) ) DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; ALTER TABLE `bzf_admin_log` ADD INDEX ( `user_id` ) ; ALTER TABLE `bzf_admin_log` ADD INDEX ( `operate` ) ; ALTER TABLE `bzf_admin_log` ADD INDEX ( `operate_time` ) ; -- 修改价格表,增加价格说明 ALTER TABLE `bzf_goods` ADD `shop_price_notice` VARCHAR( 32 ) NULL DEFAULT NULL COMMENT '价格说明' AFTER `shop_price`; ALTER TABLE `bzf_goods` ADD `type_id` SMALLINT( 5 ) NOT NULL DEFAULT '0' COMMENT '商品类型' AFTER `cat_id`; -- 修改 brand 表 ALTER TABLE `bzf_brand` CHANGE `sort_order` `sort_order` TINYINT( 3 ) UNSIGNED NOT NULL DEFAULT '0'; ALTER TABLE `bzf_brand` CHANGE `brand_logo` `brand_logo` VARCHAR( 128 ) NULL DEFAULT NULL ; ALTER TABLE `bzf_brand` CHANGE `brand_desc` `brand_desc` VARCHAR( 255 ) NULL DEFAULT NULL ; ALTER TABLE `bzf_brand` ADD `is_custom` int NULL DEFAULT 0 COMMENT '是否自定义页面'; ALTER TABLE `bzf_brand` ADD `custom_page` TEXT NULL DEFAULT NULL COMMENT '品牌自定义页面'; -- 增加 goods_attr 表记录商品的属性值 CREATE TABLE IF NOT EXISTS `bzf_goods_attr` ( `goods_attr_id` int(10) unsigned NOT NULL AUTO_INCREMENT, `goods_id` int(10) unsigned NOT NULL DEFAULT '0', `attr_item_id` int(10) unsigned NOT NULL DEFAULT '0', `attr_item_value` varchar(128) NULL, PRIMARY KEY (`goods_attr_id`), KEY `goods_id` (`goods_id`), KEY `attr_item_id` (`attr_item_id`), KEY `attr_item_value` (`attr_item_value`) ) DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; SQL; $dbEngine = DataMapper::getDbEngine(); // 解析 sql 文件,导入数据 $sqlFileContent = SqlHelper::removeComment($sqlFileContent); $sqlArray = SqlHelper::splitToSqlArray($sqlFileContent, ';'); unset($sqlFileContent); foreach ($sqlArray as $sqlQuery) { $queryObject = $dbEngine->prepare($sqlQuery); $queryObject->execute(); unset($sqlQuery); unset($queryObject); } unset($sqlArray); // 权限管理 $metaPrivilegeService = new MetaPrivilegeService(); // 删除不用的权限 $metaPrivilegeService->removePrivilegeItem('manage_goods_attrgroup_listattrgroup'); $metaPrivilegeService->removePrivilegeItem('manage_goods_attrgroup_create'); $metaPrivilegeService->removePrivilegeItem('manage_goods_attrgroup_edit'); // 添加执行权限 $privilegeGroup = $metaPrivilegeService->loadPrivilegeGroup('manage_misc'); $metaPrivilegeService->savePrivilegeItem($privilegeGroup['meta_id'], 'manage_misc_cron', '定时任务', '管理系统的定时任务'); $privilegeGroup = $metaPrivilegeService->loadPrivilegeGroup('manage_account'); $metaPrivilegeService->savePrivilegeItem($privilegeGroup['meta_id'], 'manage_account_admin_listlog', '管理员日志', '查看管理员的操作日志'); $privilegeGroup = $metaPrivilegeService->loadPrivilegeGroup('manage_goods'); $metaPrivilegeService->savePrivilegeItem($privilegeGroup['meta_id'], 'manage_goods_brand_listbrand', '商品品牌', '管理商品品牌'); $metaPrivilegeService->savePrivilegeItem($privilegeGroup['meta_id'], 'manage_goods_type_listtype', '商品类型', '管理商品类型'); // 把版本设置为 1.0.1 ManageThemePlugin::saveOptionValue('version', $this->targetVersion); return true; }
/** * 删除订单 order_info 已经后面对应的所有 order_goods 记录 * * @return boolean 成功 true,失败 false * * @param int $orderId 订单ID号 * */ public function removeOrderInfo($orderId) { // 参数验证 $validator = new Validator(array('orderId' => $orderId)); $orderId = $validator->required()->digits()->min(1)->validate('orderId'); $this->validate($validator); $orderInfo = $this->loadOrderInfoById($orderId); if (Order::OS_UNCONFIRMED != $orderInfo['order_status']) { //只有 OS_UNCONFIRMED 的订单才允许删除 return false; } $dbEngine = DataMapper::getDbEngine(); try { $dbEngine->begin(); // 先删除所有的 order_goods 记录 $this->removeAllOrderGoods($orderId); // 删除 orderInfo 记录 $orderInfo->erase(); $dbEngine->commit(); } catch (Exception $e) { $dbEngine->rollback(); return false; } return true; }
public function __construct() { $this->searchTable = DataMapper::tableName('goods_attr') . ' as ga INNER JOIN ' . DataMapper::tableName('goods') . ' as g on ga.goods_id = g.goods_id'; }
/** * 根据 meta_type 和 meta_id 取得唯一的值 * * @param string $meta_type * @param int $meta_id * @param int $ttl * * @return DataMapper * @throws \InvalidArgumentException */ public function loadMetaByTypeAndId($meta_type, $meta_id, $ttl = 0) { $meta_id = abs(intval($meta_id)); if (empty($meta_type)) { throw new \InvalidArgumentException('meta_type can not be empty'); } $dataMapper = new DataMapper('meta'); $dataMapper->loadOne(array('meta_type = ? and meta_id = ?', $meta_type, $meta_id), null, $ttl); return $dataMapper; }
/** * 删除商品的所有属性值 * * @param int $goods_id 商品ID */ public function removeAllGoodsAttrItemValue($goods_id) { // 首先验证参数 $validator = new Validator(array('goods_id' => $goods_id)); $goods_id = $validator->required()->digits()->min(1)->validate('goods_id'); $this->validate($validator); $DataMapper = new DataMapper('goods_attr'); $DataMapper->erase(array('goods_id = ?', $goods_id)); }
/** * * 清除所有的定义,请谨慎使用这个方法 * */ public function clearPrivilege() { $dataMapper = new DataMapper('meta'); $dataMapper->erase(array('meta_type = ?'), Privilege::META_TYPE_PRIVILEGE_ITEM); $dataMapper->erase(array('meta_type = ?'), Privilege::META_TYPE_PRIVILEGE_GROUP); }
/** * * 取得一组记录的数目,用于分页 * * @return int 查询条数 * * @param mixed $table 需要查询的数据表,可以是单个表,例如:'user', * 也可以是多个表的数组,例如:array('user' ,'order_info' => 'oi') * * @param array $condArray 查询条件数组,例如: * array( * array('supplier_id = ?', $supplier_id) * array('is_on_sale = ?', 1) * array('supplier_price > ? or supplier_price < ?', $priceMin, $priceMax) * ) * 这些查询条件最终会用 and 拼接起来 * @param array $optionArray 目前不支持 Having 查询,留待以后扩展 * @param int $ttl 缓存多少时间 * */ public function _countArray($table, array $condArray = null, array $optionArray = null, $ttl = 0) { // 构造参数验证数组 $validatorArray = array(); $validatorArray['table'] = $table; $validatorArray['ttl'] = $ttl; if (null != $condArray) { $validatorArray['condArray'] = $condArray; } if (null != $optionArray) { $validatorArray['optionArray'] = $optionArray; } // 参数验证 $validator = new Validator($validatorArray, ''); $table = $validator->required()->validate('table'); $ttl = $validator->digits()->min(0)->validate('ttl'); if (null != $condArray) { $condArray = $validator->requireArray(false)->validate('condArray'); } if (null != $optionArray) { $optionArray = $validator->requireArray(false)->validate('optionArray'); } $this->validate($validator); // 构造查询条件 $filter = null; if (!empty($condArray)) { $filter = QueryBuilder::buildAndFilter($condArray); } // 创建 DataMapper $dataMapper = new DataMapper($table); if (is_string($table)) { //简单的单表查询 $table = array($table); } if (is_array($table)) { // 复杂的多表查询 return $dataMapper->selectCount($table, $filter, $optionArray, $ttl); } throw new \InvalidArgumentException('table should be string or array'); }
/** * Bonus 是否可用 * * @return string 枚举类型 BONUS_XXXX,见常量定义 * * @param string $sn SN号码 */ public function isBonusAvailable($sn) { // 参数验证 $validator = new Validator(array('sn' => $sn)); $sn = $validator->required()->digits()->validate('sn'); $this->validate($validator); // 需要联表查询 $dataMapper = new DataMapper(null); $result = $dataMapper->selectComplex(array('user_bonus' => 'ub', 'bonus_type' => 'bt'), '*', array('ub.bonus_type_id = bt.type_id and ub.bonus_sn= ?', $sn), array('order' => 'bonus_id', 'offset' => 0, 'limit' => 1)); if (empty($result) || empty($result[0])) { return Bonus::BONUS_NOT_EXIST; } $result = $result[0]; if (!empty($result['user_id'])) { return Bonus::BONUS_OCCUPIED; } if ($result['use_end_date'] <= Time::gmTime()) { return Bonus::BONUS_EXPIRED; } return Bonus::BONUS_AVAILABLE; }
protected function prepareSearchParam($searchParamArray) { if (!is_array($searchParamArray)) { throw new \InvalidArgumentException('searchParam illegal : ' . var_export($searchParamArray, true)); } // 调用父类先处理 $searchParamArray = parent::prepareSearchParam($searchParamArray); $resultParamArray = array(); foreach ($searchParamArray as $searchParam) { $addParam = true; if (is_array($searchParam) && count($searchParam) == 3) { switch ($searchParam[0]) { /** 根据过滤规则,我们构造子查询 * 结构 array('ga.filter', '123.321.45', '100_20.34.67_78') * 其中 123.321.45 为 attr_item_id * 100_20.34.67_78 为 goods_attr_id 对应的值 */ case 'ga.filter': // 不加入这个参数 $addParam = false; // 没有值,不需要过滤 $trimSearchParam2 = trim(str_replace('.', '', $searchParam[2])); // 有可能没有值,全部为点 "..." if (empty($searchParam[1]) || empty($searchParam[2]) || empty($trimSearchParam2)) { break; } $goodsTypeService = new GoodsTypeService(); // 构造子查询 $queryJoinTable = ''; $firstJoinTable = ''; $queryCondArray = array(); // 构造子查询 $attrItemIdArray = explode('.', $searchParam[1]); $goodsAttrIdStrArray = explode('.', $searchParam[2]); $count = min(count($attrItemIdArray), count($goodsAttrIdStrArray)); for ($index = 0; $index < $count; $index++) { $attrItemId = abs(intval($attrItemIdArray[$index])); $goodsAttrIdArray = explode('_', $goodsAttrIdStrArray[$index]); // 跳过无效值 if ($attrItemId <= 0 || empty($goodsAttrIdArray)) { continue; } $goodsAttrItemCond = array(); foreach ($goodsAttrIdArray as $goodsAttrId) { $goodsAttrId = abs(intval($goodsAttrId)); $goodsAttr = $goodsTypeService->loadGoodsAttrById($goodsAttrId); // 无效的属性,返回 if ($goodsAttr->isEmpty()) { continue; } $goodsAttrItemCond[] = array("attr_item_value = ?", $goodsAttr['attr_item_value']); } if (!empty($goodsAttrItemCond)) { $condArray = QueryBuilder::buildAndFilter(array(array('attr_item_id = ?', $attrItemId), QueryBuilder::buildOrFilter($goodsAttrItemCond))); $tmpTableName = 'ga' . $index; $tmpTable = '(select distinct(goods_id) from ' . DataMapper::tableName('goods_attr') . ' where ' . array_shift($condArray) . ') as ' . $tmpTableName; $queryCondArray = array_merge($queryCondArray, $condArray); if (empty($queryJoinTable)) { $queryJoinTable = $tmpTable; $firstJoinTable = $tmpTableName; } else { $queryJoinTable .= ' INNER JOIN ' . $tmpTable . ' on ' . $firstJoinTable . '.goods_id = ' . $tmpTableName . '.goods_id '; } } } // 构造子查询 $this->searchTable = DataMapper::tableName('goods') . ' as g INNER JOIN ' . '(select distinct(' . $firstJoinTable . '.goods_id) from (' . $queryJoinTable . ')) as ga on g.goods_id = ga.goods_id'; /** * 这里是一个很 tricky 的构造查询的方法 * * 我们不想拼接 SQL 语句,比如 attr_item_value = $attr_item_value, * 而是采用 array('attr_item_value = ?', $attr_item_value),这样可以 SQL Bind 避免 SQL 注入 * * 由于前面的 子查询带了很多 ? 查询,所以我们需要把参数值 unshift 到第一个的位置 * */ // 头部压入一个空条件 array_unshift($queryCondArray, '1=1'); // 把这个参数压入到头部 array_unshift($resultParamArray, $queryCondArray); break; default: break; } } // 是否加入参数 if ($addParam) { $resultParamArray[] = $searchParam; } } return $resultParamArray; }
/** * 标记订单已经支付 * * @param int $orderId 订单数字ID * @param int $payId 支付类型,比如 4 代表财付通,5代表支付宝 * @param string $payType 支付类型,比如 alipay, tenpay * @param string $payNo 支付方返回的交易编号,比如支付宝返回的交易号 */ public function markOrderInfoPay($orderId, $payId, $payType, $payNo, $note = '', $username = '******') { global $logger; // 参数验证 $validator = new Validator(array('orderId' => $orderId, 'payId' => $payId)); $orderId = $validator->required()->digits()->min(1)->validate('orderId'); $payId = $validator->required()->digits()->min(1)->validate('payId'); $this->validate($validator); // 订单操作,需要保证事务 $dbEngine = DataMapper::getDbEngine(); try { $dbEngine->begin(); // 更新 order_info $orderBasicService = new Order(); $orderInfo = $orderBasicService->loadOrderInfoById($orderId); if ($orderInfo->isEmpty()) { $logger->addLogInfo(\Core\Log\Base::ERROR, 'PAYMENT', __CLASS__ . '-' . __FUNCTION__ . ' invalid order_id [' . $orderId . ']'); throw new \InvalidArgumentException('invalid order_id [' . $orderId . ']'); } $currentGmTime = Time::gmTime(); $orderInfo->order_status = Order::OS_CONFIRMED; $orderInfo->pay_status = Order::PS_PAYED; $orderInfo->update_time = $currentGmTime; $orderInfo->confirm_time = $currentGmTime; $orderInfo->pay_time = $currentGmTime; $orderInfo->pay_id = $payId; $orderInfo->pay_type = $payType; $orderInfo->pay_no = $payNo; $orderInfo->money_paid = $orderInfo->order_amount; $orderInfo->save(); // 更新 order_goods $orderGoodsService = new Goods(); $orderGoodsService->markOrderGoodsPay($orderInfo); if (empty($note)) { $note = '[' . $payType . ']付款确认'; } //记录订单操作日志 $orderActionService = new Action(); $orderActionService->logOrderAction($orderId, 0, Order::OS_CONFIRMED, Order::PS_PAYED, Goods::OGS_PAY, $note, $username, 0, $orderInfo['shipping_status']); // 提交事务 $dbEngine->commit(); // 记录成功日志 $logger->addLogInfo(\Core\Log\Base::INFO, 'PAYMENT', __CLASS__ . '-' . __FUNCTION__ . ' success order_id [' . $orderId . ']'); } catch (Exception $e) { // 记录异常日志 $logger->addLogInfo(\Core\Log\Base::ERROR, 'PAYMENT', print_r($e->getTrace(), true)); $dbEngine->rollback(); } // 由于商品库存发生变化,我们需要清除商品缓存,显示新的库存 // 注意: 这个操作绝对不能在前面的 Transaction 中操作,防止对数据库性能造成巨大影响 $orderGoodsArray = $orderBasicService->fetchOrderGoodsArray($orderId); $goodsIdArray = array(); foreach ($orderGoodsArray as $orderGoodsItem) { $goodsIdArray[] = $orderGoodsItem['goods_id']; } $goodsIdArray = array_unique($goodsIdArray); foreach ($goodsIdArray as $goodsId) { // 清除商品的缓存,确保库存数据显示是正确的 ClearHelper::clearGoodsCacheById($goodsId); } }
/** * 取得一个商品在某个属性组中的属性 * * @param int $groupId * @param int $goods_id * @param int $ttl * * @return array|null */ public function fetchGoodsAttributeArrayOfAttrGroup($groupId, $goods_id, $ttl = 0) { // 参数验证 $validator = new Validator(array('groupId' => $groupId, 'goods_id' => $goods_id, 'ttl' => $ttl)); $groupId = $validator->required()->digits()->min(1)->validate('groupId'); $goods_id = $validator->required()->digits()->min(1)->validate('goods_id'); $ttl = $validator->digits()->min(0)->validate('ttl'); $this->validate($validator); // 取得商品的属性 $sql = "SELECT a.*, " . "g.goods_attr_id, g.attr_value, g.attr_price " . 'FROM ' . DataMapper::tableName('meta') . ' AS a ' . 'LEFT JOIN ' . DataMapper::tableName('goods_attr') . ' AS g ON a.meta_id = g.attr_id and g.goods_id = ? ' . "WHERE a.parent_meta_id = ? and a.meta_type = ? " . 'ORDER BY a.meta_sort_order, g.attr_price, g.goods_attr_id'; $dbEngine = DataMapper::getDbEngine(); $result = $dbEngine->exec($sql, array(1 => $goods_id, $groupId, GoodsAttrItem::META_TYPE), $ttl); if (empty($result)) { // 没有属性,则返回 return null; } // 处理属性,属性分为 2 类,一类用于显示,一类用于选择价格 $attrubuteArray = array(); $attrubuteArray['prop'] = array(); //属性 0: 直接用于显示的属性 $attrubuteArray['spec'] = array(); //规格 1: 用户单选属性,不同价格 2: 用户多选属性,不同价格 foreach ($result as $attrItem) { $attrData = GoodsAttrItem::decodeGoodsAttrItemData($attrItem['meta_data']); if (GoodsAttrItem::ATTR_TYPE_DISPLAY == $attrData['attr_type']) { // 只是用于显示的属性 $attrubuteArray['prop'][$attrItem['meta_id']] = array('name' => $attrItem['meta_name'], 'value' => $attrItem['attr_value'], 'goods_attr_id' => $attrItem['goods_attr_id'], 'attr_input_type' => $attrData['attr_input_type'], 'attr_type' => $attrData['attr_type'], 'attr_desc' => $attrItem['meta_desc'], 'meta_id' => $attrItem['meta_id']); } else { // 用于选择不同价格的属性 $attrubuteArray['spec'][$attrItem['meta_id']]['meta_id'] = $attrItem['meta_id']; $attrubuteArray['spec'][$attrItem['meta_id']]['attr_input_type'] = $attrData['attr_input_type']; $attrubuteArray['spec'][$attrItem['meta_id']]['attr_type'] = $attrData['attr_type']; $attrubuteArray['spec'][$attrItem['meta_id']]['attr_desc'] = $attrItem['meta_desc']; $attrubuteArray['spec'][$attrItem['meta_id']]['name'] = $attrItem['meta_name']; $attrubuteArray['spec'][$attrItem['meta_id']]['values'][] = array('label' => $attrItem['attr_value'], 'price' => $attrItem['attr_price'], 'goods_attr_id' => $attrItem['goods_attr_id']); } } return $attrubuteArray; }
public function __construct() { $this->searchTable = DataMapper::tableName('order_info') . ' as oi LEFT JOIN ' . DataMapper::tableName('order_refer') . ' as orf on oi.order_id = orf.order_id'; }
/** * 取得下一个还没有执行的 Cron Task * * @param int $task_time * * @return DataMapper */ public function loadNextUnRunCronTask($task_time) { $dataMapper = new DataMapper('cron_task'); $dataMapper->load(array('task_run_time = 0'), array('order' => 'task_time asc, task_id asc', 'limit' => '1')); return $dataMapper; }
/** * 商品数据转化 */ private function convertGoods() { global $f3; // 在这里配置源商品图片的路径前缀 $f3->set('srcImagePrefix', "http://img.bangzhufu.com/static/"); $tableMigrate = new TableMigrate(); $tableMigrate->batchProcessCount = 100; // 每次批处理 100 个商品,防止商品过多搞死系统 // 清空数据 $dstTable = new DstDataMapper('goods'); $tableMigrate->clearTable($dstTable); $goodsGalleryTable = new DstDataMapper('goods_gallery'); $tableMigrate->clearTable($goodsGalleryTable); $tableMigrate->setAutoIncValue($goodsGalleryTable, 1); $goodsAttrTable = new DstDataMapper('goods_attr'); $tableMigrate->clearTable($goodsAttrTable); $tableMigrate->setAutoIncValue($goodsAttrTable, 1); //转化数据 $currentTime = time(); $tableMigrate->convertTable('team', array(array('begin_time < ? and end_time > ?', $currentTime, $currentTime)), array('order' => 'id asc'), 'goods', array('id' => 'goods_id', 'user_id' => 'goods_sn', 'title' => 'goods_name', 'summary' => 'goods_brief', 'group_id' => 'cat_id', 'partner_id' => 'suppliers_id', 'team_price' => 'shop_price', 'market_price' => 'market_price', 'agent_price' => 'suppliers_price', 'product' => 'goods_name_short', 'condbuy' => 'condbuy', 'image' => null, 'image1' => null, 'image2' => null, 'agent_fare' => 'suppliers_shipping_fee', 'farefree' => 'shipping_free_number', 'detail' => 'goods_desc', 'notice' => 'goods_notice', 'sort_order' => 'sort_order', 'seo_title' => 'seo_title', 'seo_keyword' => 'seo_keyword', 'seo_description' => 'seo_description', 'express_relate' => 'shipping_fee', 'city_id' => 'goods_number'), array('user_id' => function ($user_id, $record) { global $f3; //在这里生成 goods_sn return $f3->get('sysConfig[goods_sn_prefix]') . $record->id; }, 'express_relate' => function ($express_relate, $record) { // 最土系统 -1 表示免邮费,我们这里修改邮费为 0 if ($record['farefree'] < 0) { return 0; } $dataArray = unserialize($express_relate); $maxShippingFee = 0; // 取最大的快递费 foreach ($dataArray as $data) { $maxShippingFee = $data['price'] > $maxShippingFee ? $data['price'] : $maxShippingFee; } return $maxShippingFee; }, 'farefree' => function ($farefree, $record) { // 最土 -1 表示免运费,我们这里一律改成不免邮费 if ($farefree < 0) { return 0; } return $farefree; }, 'city_id' => function ($city_id, $record) { return 1000; // 所有库存缺省都设置为 1000 }), function ($srcRecord) { global $f3; $srcImagePrefix = $f3->get('srcImagePrefix'); $fetchImageArray = array(); if (!empty($srcRecord->image)) { $fetchImageArray[] = $srcImagePrefix . $srcRecord->image; } if (!empty($srcRecord->image1)) { $fetchImageArray[] = $srcImagePrefix . $srcRecord->image1; } if (!empty($srcRecord->image2)) { $fetchImageArray[] = $srcImagePrefix . $srcRecord->image2; } if (!empty($fetchImageArray)) { // 设置 fetchImageArray 的值,用于后面图片抓取 $f3->set('fetchImageArray_' . $srcRecord->id, $fetchImageArray); } }, function ($srcRecord, $dstRecord) { global $f3; $fetchImageArray = $f3->get('fetchImageArray_' . $srcRecord->id); if (empty($fetchImageArray)) { return; } // 我们在这里做图片的抓取操作 foreach ($fetchImageArray as $fetchImageUrl) { fetchGoodsImage($srcRecord->id, $fetchImageUrl); //usleep(200000); // 睡 200 ms,防止抓取太快服务器不响应 } // 释放资源 $f3->clear('fetchImageArray_' . $srcRecord->id); // 处理 condbuy 字段 if (empty($srcRecord->condbuy)) { return; } // 需要更新商品的选择 $dstRecord->goods_type = $f3->get('sysConfig[condbuy_goods_type]'); // 删除旧的数据 $sql = 'delete from ' . DataMapper::tableName('goods_attr') . ' where goods_id = ?'; $dbEngine = DstDataMapper::getDbEngine(); $dbEngine->exec($sql, $srcRecord->id); // 解析 condbuy {红色}{绿色}{蓝色} $condBuyArray = explode('}{', '}' . $srcRecord->condbuy . '{'); foreach ($condBuyArray as $condBuyItem) { if (empty($condBuyItem)) { continue; } $dataMapper = new DataMapper('goods_attr'); $dataMapper->goods_id = $srcRecord->id; $dataMapper->attr_id = $f3->get('sysConfig[condbuy_attr_id]'); $dataMapper->attr_value = $condBuyItem; $dataMapper->attr_price = 0; $dataMapper->save(); unset($dataMapper); } }); // 重设表的 AUTO_INCREMENT 值 $tableMigrate->resetAutoIncValue($dstTable, 'goods_id'); // 清理数据 unset($tableMigrate); unset($dstTable); unset($result); }
public function get($f3) { // 权限检查 $this->requirePrivilege('manage_goods_create'); // 参数验证 $validator = new Validator($f3->get('GET')); $goods_id = $validator->required('商品ID不能为空')->digits()->min(1)->validate('goods_id'); if (!$this->validate($validator)) { goto out_fail; } // 取得商品信息 $goodsBasicService = new GoodsBasicService(); $goods = $goodsBasicService->loadGoodsById($goods_id); if ($goods->isEmpty()) { $this->addFlashMessage('非法商品ID'); goto out_fail; } $authAdminUser = AuthHelper::getAuthUser(); // 1. 复制 goods 信息 $goodsArray = $goods->toArray(); unset($goodsArray['goods_id']); // 清除主键 // 新商品缺省为下线状态 $goodsArray['is_on_sale'] = 0; // 清除购买数量统计 $goodsArray['user_buy_number'] = 0; $goodsArray['user_pay_number'] = 0; // 设置复制人 $goodsArray['admin_user_id'] = $authAdminUser['user_id']; $goodsArray['admin_user_name'] = $authAdminUser['user_name']; // 处理商品的规格 if (!empty($goodsArray['goods_spec'])) { $goodsSpecService = new GoodsSpecService(); $goodsSpecService->initWithJson($goodsArray['goods_spec']); $goodsSpecService->clearGoodsSpecImgIdArray(); // 清除图片 ID 的关联 $goodsArray['goods_spec'] = $goodsSpecService->getJsonStr(); unset($goodsSpecService); } $goodsArray['add_time'] = Time::gmTime(); $newGoods = $goodsBasicService->loadGoodsById(0); $newGoods->copyFrom($goodsArray); $newGoods->save(); // 更新 goods_sn $newGoods->goods_sn = $f3->get('sysConfig[goods_sn_prefix]') . $newGoods['goods_id']; $newGoods->save(); unset($goodsArray); // 2. 复制 goods_attr 信息 if ($goods->type_id > 0) { $goodsTypeService = new GoodsTypeService(); $goodsAttrValueArray = $goodsTypeService->fetchGoodsAttrItemValueArray($goods->goods_id, $goods->type_id); foreach ($goodsAttrValueArray as $goodsAttrValue) { $goodsAttr = $goodsTypeService->loadGoodsAttrById(0); $goodsAttr->goods_id = $newGoods->goods_id; $goodsAttr->attr_item_id = $goodsAttrValue['meta_id']; $goodsAttr->attr_item_value = $goodsAttrValue['attr_item_value']; $goodsAttr->save(); unset($goodsAttr); } unset($goodsAttrValueArray); unset($goodsTypeService); } // 3. 复制 goods_gallery 信息 $goodsGalleryService = new GoodsGalleryService(); $goodsGalleryArray = $goodsGalleryService->fetchGoodsGalleryArrayByGoodsId($goods_id); foreach ($goodsGalleryArray as $goodsGalleryItem) { // 新建一个 goods_gallery 记录 $goodsGallery = $goodsGalleryService->loadGoodsGalleryById(0); unset($goodsGalleryItem['img_id']); $goodsGallery->copyFrom($goodsGalleryItem); $goodsGallery->goods_id = $newGoods['goods_id']; $goodsGallery->save(); unset($goodsGallery); } unset($goodsGalleryArray); unset($goodsGalleryService); // 4. 复制 goods_team 信息 $goodsTeam = $goodsBasicService->loadGoodsTeamByGoodsId($goods_id); if (!$goodsTeam->isEmpty()) { $goodsTeamInfo = $goodsTeam->toArray(); unset($goodsTeamInfo['team_id']); $goodsTeamInfo['goods_id'] = $newGoods['goods_id']; $newGoodsTeam = new DataMapper('goods_team'); $newGoodsTeam->copyFrom($goodsTeamInfo); $newGoodsTeam->save(); unset($newGoodsTeam); unset($goodsTeamInfo); unset($goodsTeam); } // 5. 复制 link_goods 信息 $linkGoodsArray = $goodsBasicService->fetchSimpleLinkGoodsArray($goods_id); foreach ($linkGoodsArray as $linkGoodsItem) { unset($linkGoodsItem['link_id']); $linkGoodsItem['goods_id'] = $newGoods['goods_id']; $linkGoodsItem['admin_id'] = $authAdminUser['user_id']; $linkGoods = new DataMapper('link_goods'); $linkGoods->copyFrom($linkGoodsItem); $linkGoods->save(); unset($linkGoods); } unset($linkGoodsArray); // 6. 复制 goods_promote 信息 $goodsPromote = $goodsBasicService->loadGoodsPromoteByGoodsId($goods_id); if (!$goodsPromote->isEmpty()) { $goodsPromoteInfo = $goodsPromote->toArray(); unset($goodsPromoteInfo['promote_id']); $goodsPromoteInfo['goods_id'] = $newGoods['goods_id']; $newGoodspromote = new DataMapper('goods_promote'); $newGoodspromote->copyFrom($goodsPromoteInfo); $newGoodspromote->save(); unset($newGoodspromote); } unset($goodsPromote); // 记录编辑日志 $goodsLogContent = '从 [' . $goods_id . '] 复制过来'; $goodsLogService = new GoodsLogService(); $goodsLogService->addGoodsLog($newGoods['goods_id'], $authAdminUser['user_id'], $authAdminUser['user_name'], '复制商品', $goodsLogContent); $this->addFlashMessage('复制新建商品成功'); RouteHelper::reRoute($this, RouteHelper::makeUrl('/Goods/Edit/Edit', array('goods_id' => $newGoods['goods_id']), true)); return; //正常返回 out_fail: RouteHelper::reRoute($this, '/Goods/Search'); }
/** * 取得用户的 account_log 列表 * * @return array 格式 array(array('key'=>'value', 'key'=>'value', ...)) * * @param int $userId 用户 ID * @param string $filter 查询条件 * @param int $offset 用于分页的开始 >= 0 * @param int $limit 每页多少条 * @param int $ttl 缓存多少时间 */ public function fetchUserAccountLogArray($userId, $filter, $offset = 0, $limit = 10, $ttl = 0) { // 参数验证 $validator = new Validator(array('userId' => $userId, 'filter' => $filter, 'offset' => $offset, 'limit' => $limit, 'ttl' => $ttl)); $userId = $validator->required()->digits()->min(1)->validate('userId'); $filter = $validator->validate('filter'); $offset = $validator->digits()->min(0)->validate('offset'); $limit = $validator->required()->digits()->min(1)->validate('limit'); $ttl = $validator->digits()->min(0)->validate('ttl'); $this->validate($validator); // 需要联表查询 $accountLog = new DataMapper('account_log'); if (!empty($filter)) { $filter .= ' and user_id = ?'; } else { $filter = 'user_id = ?'; } return $accountLog->find(array($filter, $userId), array('order' => 'log_id desc', 'offset' => $offset, 'limit' => $limit), $ttl); }
/** * 增加商品关联 * * @param $f3 */ public function ajaxAddLink($f3) { // 权限检查 $this->requirePrivilege('manage_goods_edit_edit_post', true); // 首先做参数验证 $validator = new Validator($f3->get('GET')); $errorMessage = ''; $goods_id = $validator->required()->digits()->min(1)->validate('goods_id'); $link_goods_id = $validator->required()->digits()->min(1)->validate('link_goods_id'); if (!$this->validate($validator)) { $errorMessage = implode('|', $this->flashMessageArray); goto out_fail; } $dataMapper = new DataMapper('link_goods'); $dataMapper->loadOne(array('goods_id = ? and link_goods_id = ?', $goods_id, $link_goods_id)); // 已经关联了,不要重复关联 if (!$dataMapper->isEmpty()) { goto out; } $authAdminUser = AuthHelper::getAuthUser(); // 添加记录 $dataMapper->goods_id = $goods_id; $dataMapper->link_goods_id = $link_goods_id; $dataMapper->admin_id = $authAdminUser['user_id']; $dataMapper->save(); //清除缓存,确保商品显示正确 ClearHelper::clearGoodsCacheById($goods_id); // 记录商品编辑日志 $goodsLogService = new GoodsLogService(); $goodsLogService->addGoodsLog($goods_id, $authAdminUser['user_id'], $authAdminUser['user_name'], '添加商品关联', $link_goods_id); out: Ajax::header(); echo Ajax::buildResult(null, null, null); return; out_fail: // 失败,返回出错信息 Ajax::header(); echo Ajax::buildResult(-1, $errorMessage, null); }