签入版本
This commit is contained in:
@@ -0,0 +1,398 @@
|
||||
# +======================================================================
|
||||
# | DjangoAdmin 企业数字化开发平台 [ 赋能开发者,助力企业发展 ]
|
||||
# +----------------------------------------------------------------------
|
||||
# | Copyright (c) 2021-2026 小蚂蚁云团队 版权所有
|
||||
# +----------------------------------------------------------------------
|
||||
# | 开源协议: Apache-2.0
|
||||
# | 重要声明: 未经书面许可,不得移除或修改本框架相关版权标识。
|
||||
# +----------------------------------------------------------------------
|
||||
# | 官方网站: https://www.djangoadmin.cn
|
||||
# +----------------------------------------------------------------------
|
||||
# | 研发团队: 小蚂蚁云团队 荣誉出品
|
||||
# +======================================================================
|
||||
# | 版权和免责声明:
|
||||
# | 一、知识产权声明
|
||||
# | 本团队对该软件框架产品(以下简称“本产品”)拥有完整知识产权,包括但不限于商标权、专利权、
|
||||
# | 著作权、商业秘密等。前述权利均受中华人民共和国及相关国际法律法规保护。未经本团队书面授权,
|
||||
# | 任何个人或单位不得基于本产品本身申请任何形式的知识产权。
|
||||
# | 二、使用限制与禁止条款
|
||||
# | 您理解并同意,禁止将本产品用于以下任何行为:
|
||||
# | 1. 任何违反中华人民共和国法律法规的用途;
|
||||
# | 2. 任何侵害他人合法权益(包括但不限于人身权、财产权、知识产权等)的行为;
|
||||
# | 3. 任何危害国家安全、公共利益及社会道德风尚的行为。
|
||||
# | 三、责任豁免
|
||||
# | 因使用本产品而产生的任何损失或法律纠纷(包括但不限于直接损失、间接损失、附带损失、衍生损失
|
||||
# | 以及因违约、侵权等引发的责任),本团队均不承担任何法律责任。若因违规使用本产品导致任何第三
|
||||
# | 方提起索赔或行政机关进行调查,您应独立承担全部责任。
|
||||
# | 四、违约与法律责任
|
||||
# | 如发现任何违反本声明的行为,本团队有权:
|
||||
# | 1. 无条件配合公安机关及其他有权机关的调查取证工作;
|
||||
# | 2. 依法追究相关方的民事责任,并要求赔偿全部损失;
|
||||
# | 3. 保留进一步采取刑事控告等法律措施的权利。
|
||||
# | 五、许可范围说明
|
||||
# | 1、被授权方应视本产品源代码为核心机密信息,负有最高标准的保密与保管义务。禁止以任何形式(包
|
||||
# | 括但不限于直接或间接的分享、复制、传播、分发、转售、出租、开源、反向工程、反编译、反汇编或通
|
||||
# | 过网络服务提供给任何第三方)泄露、披露或处置源代码的全部或部分内容。任何未经授权的复制、使用、
|
||||
# | 传播行为均构成对本团队知识产权的严重侵权,本团队有权依法追究其全部法律责任,并要求赔偿因此造
|
||||
# | 成的一切经济损失及商誉损害。
|
||||
# | 2、本产品仅限于公司或个人在法律允许范围内,用于内部且合规的软件产品研发。具体权利义务以《软件
|
||||
# | 许可协议》附件为准。
|
||||
# +======================================================================
|
||||
|
||||
"""
|
||||
城市管理服务模块
|
||||
=============================================================
|
||||
|
||||
该模块实现了城市管理相关的所有业务逻辑。
|
||||
包括城市的增删改查、列表查询、子级城市获取、城市JSON数据生成等功能。
|
||||
城市数据通常包含层级关系,通过parentCode或pid关联上级城市。
|
||||
|
||||
命名规范:
|
||||
- 函数参数使用驼峰命名(如 cityId, cityCode)
|
||||
- 表单字段使用下划线命名(如 city_code, area_code)- 与数据库字段保持一致
|
||||
- 返回数据使用驼峰命名(如 cityCode, areaCode)- 与前端规范保持一致
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from application.city import forms
|
||||
from application.city.models import City
|
||||
from utils import R, regular
|
||||
from utils.common import format_datetime, parse_request_body
|
||||
from utils.security import get_username
|
||||
|
||||
|
||||
# =============================================================
|
||||
# 列表查询服务
|
||||
# =============================================================
|
||||
|
||||
def get_city_list(request):
|
||||
"""
|
||||
查询城市数据列表
|
||||
|
||||
根据请求参数查询城市列表,支持按上级ID和城市名称筛选。
|
||||
返回的数据包含城市的详细信息,并标记是否有子节点。
|
||||
|
||||
Args:
|
||||
request: HttpRequest对象,包含查询参数
|
||||
- pid: 上级城市ID(可选,默认为0)
|
||||
- name: 城市名称(可选,模糊查询)
|
||||
|
||||
Returns:
|
||||
R: 包含城市列表数据的JSON响应
|
||||
"""
|
||||
try:
|
||||
# 构建基础查询(只查询未删除的记录)
|
||||
query = City.objects.filter(is_delete=False)
|
||||
|
||||
# 上级ID筛选(用于查询特定父级下的子城市)
|
||||
pid = request.GET.get('pid', 0)
|
||||
if pid:
|
||||
query = query.filter(pid=pid)
|
||||
|
||||
# 城市名称模糊筛选(不区分大小写)
|
||||
name = request.GET.get('name')
|
||||
if name:
|
||||
query = query.filter(name__icontains=name)
|
||||
|
||||
# 按ID排序,保证数据顺序稳定
|
||||
city_list = query.order_by('id').all()
|
||||
|
||||
# 构建返回数据
|
||||
result = []
|
||||
for item in city_list:
|
||||
data = {
|
||||
'id': item.id,
|
||||
'cityCode': item.city_code,
|
||||
'areaCode': item.area_code,
|
||||
'parentCode': item.parent_code,
|
||||
'zipCode': item.zip_code,
|
||||
'level': item.level,
|
||||
'pid': item.pid,
|
||||
'name': item.name,
|
||||
'shortName': item.short_name,
|
||||
'fullName': item.full_name,
|
||||
'pinyin': item.pinyin,
|
||||
'lng': item.lng,
|
||||
'lat': item.lat,
|
||||
'createUser': item.create_user,
|
||||
'createTime': format_datetime(item.create_time),
|
||||
'updateUser': item.update_user,
|
||||
'updateTime': format_datetime(item.update_time),
|
||||
}
|
||||
result.append(data)
|
||||
|
||||
return R.ok(data=result)
|
||||
|
||||
except Exception as e:
|
||||
logging.error(f"查询城市列表异常: {str(e)}")
|
||||
return R.failed(msg="查询失败,请稍后重试")
|
||||
|
||||
|
||||
# =============================================================
|
||||
# 详情查询服务
|
||||
# =============================================================
|
||||
|
||||
def get_city_detail(city_id):
|
||||
"""
|
||||
根据城市ID获取城市详情
|
||||
|
||||
Args:
|
||||
city_id: 城市ID
|
||||
|
||||
Returns:
|
||||
dict/None: 城市详情字典,不存在时返回None
|
||||
"""
|
||||
try:
|
||||
# 查询未删除的城市记录
|
||||
city = City.objects.filter(is_delete=False, id=city_id).first()
|
||||
if not city:
|
||||
return None
|
||||
|
||||
# 获取父级城市名称(用于前端展示层级关系)
|
||||
parent_name = None
|
||||
if city.pid and city.pid > 0:
|
||||
parent_city = City.objects.filter(is_delete=False, id=city.pid).first()
|
||||
if parent_city:
|
||||
parent_name = parent_city.name
|
||||
|
||||
# 返回详情数据
|
||||
data = {
|
||||
'id': city.id,
|
||||
'name': city.name,
|
||||
'cityCode': city.city_code,
|
||||
'areaCode': city.area_code,
|
||||
'parentCode': city.parent_code,
|
||||
'level': city.level,
|
||||
'zipCode': city.zip_code,
|
||||
'shortName': city.short_name,
|
||||
'pinyin': city.pinyin,
|
||||
'lng': city.lng,
|
||||
'lat': city.lat,
|
||||
'pid': city.pid,
|
||||
'parentName': parent_name,
|
||||
}
|
||||
return data
|
||||
except Exception as e:
|
||||
logging.error(f"查询城市详情异常,ID: {city_id}, 错误: {str(e)}")
|
||||
return None
|
||||
|
||||
|
||||
# =============================================================
|
||||
# 添加服务
|
||||
# =============================================================
|
||||
|
||||
def add_city(request):
|
||||
"""
|
||||
添加城市
|
||||
|
||||
处理流程:
|
||||
1. 解析请求体中的JSON数据
|
||||
2. 表单验证
|
||||
3. 创建数据库记录
|
||||
|
||||
Args:
|
||||
request: HttpRequest对象,包含城市信息的JSON数据
|
||||
|
||||
Returns:
|
||||
R: 操作结果(成功/失败)
|
||||
"""
|
||||
# 解析请求参数
|
||||
data, error = parse_request_body(request)
|
||||
if error:
|
||||
return R.failed(msg=error)
|
||||
|
||||
# 表单验证
|
||||
form = forms.CityForm(data)
|
||||
if not form.is_valid():
|
||||
return R.failed(msg=regular.get_err(form))
|
||||
|
||||
try:
|
||||
# 获取清洗后的数据
|
||||
cleaned_data = form.cleaned_data
|
||||
|
||||
# 创建城市记录
|
||||
City.objects.create(
|
||||
city_code=cleaned_data.get('cityCode'),
|
||||
area_code=cleaned_data.get('areaCode'),
|
||||
parent_code=cleaned_data.get('parentCode'),
|
||||
zip_code=cleaned_data.get('zipCode'),
|
||||
level=int(cleaned_data.get('level')),
|
||||
pid=int(cleaned_data.get('pid')),
|
||||
name=cleaned_data.get('name'),
|
||||
short_name=cleaned_data.get('shortName'),
|
||||
lng=cleaned_data.get('lng'),
|
||||
lat=cleaned_data.get('lat'),
|
||||
create_user=get_username(request),
|
||||
update_user=get_username(request)
|
||||
)
|
||||
return R.ok(msg="创建成功")
|
||||
except Exception as e:
|
||||
logging.error(f"添加城市异常: {str(e)}")
|
||||
return R.failed(msg="添加失败,请稍后重试")
|
||||
|
||||
|
||||
# =============================================================
|
||||
# 更新服务
|
||||
# =============================================================
|
||||
|
||||
def update_city(request):
|
||||
"""
|
||||
更新城市
|
||||
|
||||
处理流程:
|
||||
1. 解析请求体中的JSON数据
|
||||
2. 验证城市ID
|
||||
3. 表单验证
|
||||
4. 查询现有记录
|
||||
5. 更新各字段
|
||||
6. 保存更新
|
||||
|
||||
Args:
|
||||
request: HttpRequest对象,包含城市ID和更新信息的JSON数据
|
||||
|
||||
Returns:
|
||||
R: 操作结果(成功/失败)
|
||||
"""
|
||||
# 解析请求参数
|
||||
data, error = parse_request_body(request)
|
||||
if error:
|
||||
return R.failed(msg=error)
|
||||
|
||||
# 验证城市ID
|
||||
city_id = data.get('id')
|
||||
if not city_id or not str(city_id).isdigit() or int(city_id) <= 0:
|
||||
return R.failed("城市ID无效")
|
||||
city_id = int(city_id)
|
||||
|
||||
# 表单验证
|
||||
form = forms.CityForm(data)
|
||||
if not form.is_valid():
|
||||
return R.failed(msg=regular.get_err(form))
|
||||
|
||||
try:
|
||||
# 获取清洗后的数据
|
||||
cleaned_data = form.cleaned_data
|
||||
|
||||
# 查询城市记录
|
||||
city = City.objects.filter(id=city_id, is_delete=False).first()
|
||||
if not city:
|
||||
return R.failed("城市不存在")
|
||||
|
||||
# 更新各字段
|
||||
city.city_code = cleaned_data.get('cityCode')
|
||||
city.area_code = cleaned_data.get('areaCode')
|
||||
city.parent_code = cleaned_data.get('parentCode')
|
||||
city.zip_code = cleaned_data.get('zipCode')
|
||||
city.level = int(cleaned_data.get('level'))
|
||||
city.pid = int(cleaned_data.get('pid'))
|
||||
city.name = cleaned_data.get('name')
|
||||
city.short_name = cleaned_data.get('shortName')
|
||||
city.lng = cleaned_data.get('lng')
|
||||
city.lat = cleaned_data.get('lat')
|
||||
city.update_user = get_username(request)
|
||||
city.save()
|
||||
|
||||
return R.ok(msg="更新成功")
|
||||
except Exception as e:
|
||||
logging.error(f"更新城市异常,ID: {city_id}, 错误: {str(e)}")
|
||||
return R.failed(msg="更新失败,请稍后重试")
|
||||
|
||||
|
||||
# =============================================================
|
||||
# 删除服务(支持批量)
|
||||
# =============================================================
|
||||
|
||||
def delete_cities(city_ids):
|
||||
"""
|
||||
删除城市(批量删除)
|
||||
|
||||
采用逻辑删除方式(is_delete=True),而非物理删除。
|
||||
删除前会检查是否存在子级城市,如果有则阻止删除。
|
||||
|
||||
Args:
|
||||
city_ids: 城市ID字符串,多个ID用逗号分隔
|
||||
例如: "1" 或 "1,2,3"
|
||||
|
||||
Returns:
|
||||
R: 操作结果,包含删除数量
|
||||
"""
|
||||
if not city_ids:
|
||||
return R.failed("记录ID不存在")
|
||||
|
||||
try:
|
||||
# 解析ID列表
|
||||
id_list = [int(id_str.strip()) for id_str in city_ids.split(',') if id_str.strip()]
|
||||
if not id_list:
|
||||
return R.failed("无效的记录ID")
|
||||
|
||||
# 检查是否有子级城市(防止删除有子级的父级城市)
|
||||
has_children = City.objects.filter(pid__in=id_list, is_delete=False).exists()
|
||||
if has_children:
|
||||
return R.failed("请先删除子级城市")
|
||||
|
||||
# 批量更新删除标识(逻辑删除)
|
||||
updated_count = City.objects.filter(
|
||||
id__in=id_list,
|
||||
is_delete=False
|
||||
).update(is_delete=True)
|
||||
|
||||
return R.ok(msg=f"本次共删除{updated_count}条数据")
|
||||
except ValueError:
|
||||
return R.failed("记录ID格式错误")
|
||||
except Exception as e:
|
||||
logging.error(f"删除城市异常,IDs: {city_ids}, 错误: {str(e)}")
|
||||
return R.failed(msg="删除失败,请稍后重试")
|
||||
|
||||
|
||||
# =============================================================
|
||||
# 子级城市列表查询服务
|
||||
# =============================================================
|
||||
|
||||
def get_child_cities(city_code):
|
||||
"""
|
||||
根据上级城市编码获取子级城市列表
|
||||
|
||||
用于前端级联选择器,根据上级编码加载下级城市数据。
|
||||
|
||||
Args:
|
||||
city_code: 上级城市编码(如省份编码)
|
||||
|
||||
Returns:
|
||||
list: 子级城市列表,每个元素为城市模型字典
|
||||
查询失败时返回空列表
|
||||
"""
|
||||
try:
|
||||
# 查询指定上级编码下的所有子级城市
|
||||
child_list = City.objects.filter(
|
||||
is_delete=False,
|
||||
parent_code=city_code
|
||||
).values()
|
||||
|
||||
# 转换为驼峰命名格式
|
||||
result = []
|
||||
for item in child_list:
|
||||
data = {
|
||||
'id': item['id'],
|
||||
'cityCode': item['city_code'],
|
||||
'areaCode': item['area_code'],
|
||||
'parentCode': item['parent_code'],
|
||||
'zipCode': item['zip_code'],
|
||||
'level': item['level'],
|
||||
'pid': item['pid'],
|
||||
'name': item['name'],
|
||||
'shortName': item['short_name'],
|
||||
'fullName': item['full_name'],
|
||||
'pinyin': item['pinyin'],
|
||||
'lng': item['lng'],
|
||||
'lat': item['lat'],
|
||||
'createUser': item['create_user'],
|
||||
'createTime': format_datetime(item['create_time']),
|
||||
'updateUser': item['update_user'],
|
||||
'updateTime': format_datetime(item['update_time']),
|
||||
}
|
||||
result.append(data)
|
||||
return result
|
||||
except Exception as e:
|
||||
logging.error(f"获取子级城市列表异常,cityCode: {city_code}, 错误: {str(e)}")
|
||||
return []
|
||||
Reference in New Issue
Block a user