$areaId, 'store_id' => $storeId, 'action_type' => $actionType, 'old_data' => $oldData ? json_encode($oldData, JSON_UNESCAPED_UNICODE) : '', 'new_data' => $newData ? json_encode($newData, JSON_UNESCAPED_UNICODE) : '', 'operator_id' => $operatorId, 'operator_name' => $operatorName, 'create_time' => time(), 'ip_address' => $this->getClientIp(), 'user_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '' ); return $this->add($data); } /** * 获取服务区域操作日志 * @param int $areaId 服务区域ID * @param int $limit 限制条数 * @return array */ public function getAreaLogs($areaId, $limit = 50) { return $this->where(array('area_id' => $areaId)) ->order('create_time DESC') ->limit($limit) ->select(); } /** * 获取门店所有服务区域操作日志 * @param int $storeId 门店ID * @param int $limit 限制条数 * @return array */ public function getStoreLogs($storeId, $limit = 100) { return $this->where(array('store_id' => $storeId)) ->order('create_time DESC') ->limit($limit) ->select(); } /** * 获取操作类型描述 * @param int $actionType 操作类型 * @return string */ public function getActionTypeDesc($actionType) { $types = array( self::ACTION_CREATE => '创建服务区域', self::ACTION_UPDATE => '修改服务区域', self::ACTION_DELETE => '删除服务区域', self::ACTION_ENABLE => '启用服务区域', self::ACTION_DISABLE => '禁用服务区域' ); return isset($types[$actionType]) ? $types[$actionType] : '未知操作'; } /** * 获取客户端IP地址 * @return string */ private function getClientIp() { $ip = ''; if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); $ip = trim($ips[0]); } elseif (isset($_SERVER['HTTP_X_REAL_IP']) && !empty($_SERVER['HTTP_X_REAL_IP'])) { $ip = $_SERVER['HTTP_X_REAL_IP']; } elseif (isset($_SERVER['REMOTE_ADDR'])) { $ip = $_SERVER['REMOTE_ADDR']; } return $ip; } /** * 清理过期日志 * @param int $days 保留天数,默认90天 * @return bool */ public function cleanExpiredLogs($days = 90) { $expireTime = time() - ($days * 24 * 3600); return $this->where(array('create_time' => array('lt', $expireTime)))->delete(); } /** * 获取操作统计 * @param int $storeId 门店ID * @param int $startTime 开始时间 * @param int $endTime 结束时间 * @return array */ public function getOperationStats($storeId, $startTime = null, $endTime = null) { $map = array('store_id' => $storeId); if ($startTime) { $map['create_time'][] = array('egt', $startTime); } if ($endTime) { $map['create_time'][] = array('elt', $endTime); } $stats = $this->where($map) ->field('action_type, COUNT(*) as count') ->group('action_type') ->select(); $result = array(); foreach ($stats as $stat) { $result[$stat['action_type']] = array( 'count' => $stat['count'], 'desc' => $this->getActionTypeDesc($stat['action_type']) ); } return $result; } }