6 Commits

Author SHA1 Message Date
cnbugs 9b79c14267 feat: 新增软件资产(软资产)管理模块
- 新增 SoftwareCategory/SoftwareAsset/SoftwareChangeLog 模型与迁移0010
- 软资产CRUD:编号/名称/分类/供应商/版本/许可类型/授权数量/许可密钥/账号/费用/起止日期/负责人/部门/状态
- 许可类型:永久授权/订阅/开源免费/按需付费;状态:在用/闲置/已过期/已注销
- 到期提醒:已过期/即将到期(30天)自动标识
- Excel导入导出:模板下载、ID存在时更新、分类自动创建、空白行跳过、缺编号/名称报错
- 软件分类独立管理,分类下有资产时禁止删除
- 独立软件变更记录页;仪表盘增加软件统计卡片、软件分类统计、许可类型分布
- 导航栏改造:资产管理/分类管理/变更记录/导入导出下拉菜单
- 全流程15项功能验证通过(CRUD/导入导出/权限/仪表盘)
2026-11-11 17:22:23 +08:00
cnbugs e894f61ddf fix: 按资产编号导出时遵循用户输入顺序而非ID顺序 2026-11-06 13:15:05 +08:00
cnbugs 095cf11637 feat: 资产列表支持按资产编号导出Excel
- 导出接口新增 asset_numbers 参数,支持逗号/顿号/空格/换行分隔多个编号,精确匹配并自动去重
- 未找到的编号记入消息提示
- 资产列表页新增按编号导出输入框,支持回车触发下载
2026-11-06 13:03:53 +08:00
cnbugs 8dc11b4857 fix: 补充与当前模型一致的0009迁移
- a07b390 将面值/日期/IP/卡数等字段改为CharField,但缺少对应迁移
- status默认值修正为in_use(之前错误的0009用了中文'在用')
- 升级演练验证旧数据完整保留
2026-10-15 19:10:01 +08:00
cnbugs 96023431fc feat: 新增超级管理员重置用户密码功能
- 用户列表页 /users/:支持按用户名/姓名/邮箱搜索、按状态筛选、分页
- 重置密码页 /users/<id>/password/:仅超级管理员可访问
- 复用 Django 密码校验器(一致性、长度、相似度、常见/纯数字密码)
- 管理员重置自身密码时保持登录会话不失效
- settings 补充 AUTH_PASSWORD_VALIDATORS 配置
2026-10-15 18:59:34 +08:00
cnbugs a07b390995 fix: 修复资产编辑无法保存的bug
- 恢复Asset模型STATUS_CHOICES定义,状态字段使用下拉选择而非文本输入
- 修复status默认值从中文'在用'改为英文key'in_use',与数据库存储一致
- 编辑表单新增资产面值(asset_value)字段
- excel_utils适配字段类型变更(DecimalField→CharField, DateField→CharField等)
2026-05-26 16:48:01 +08:00
25 changed files with 2463 additions and 145 deletions
+48 -4
View File
@@ -1,16 +1,18 @@
# 希姆计算资产管理管理系统 # 希姆计算资产管理管理系统
基于 Django + MySQL 的企业级硬件资产管理系统,支持 Excel 批量导入导出。 基于 Django + MySQL 的企业级资产管理管理系统,支持硬件资产与软件资产(软资产)管理、Excel 批量导入导出。
## ✨ 功能特性 ## ✨ 功能特性
- **仪表盘** — 资产统计总览、分类统计、状态分布、最近变更记录 - **仪表盘** — 硬件/软件资产统计总览、分类统计、状态分布、最近变更记录
- **软件资产管理** — 许可证/订阅/域名/证书等软资产全生命周期管理,许可类型与到期提醒
- **资产管理** — 设备增删改查、资产编号/品牌/型号/序列号/资产面值等完整字段 - **资产管理** — 设备增删改查、资产编号/品牌/型号/序列号/资产面值等完整字段
- **分类管理** — 自定义设备分类(服务器、网络设备、存储设备等) - **分类管理** — 自定义设备分类(服务器、网络设备、存储设备等)
- **变更追踪** — 资产信息修改自动记录变更历史 - **变更追踪** — 资产信息修改自动记录变更历史
- **Excel 导入导出** — 批量导入(分类不存在自动创建)、筛选导出、模板下载 - **Excel 导入导出** — 批量导入(分类不存在自动创建)、筛选导出、模板下载
- **多维度搜索** — 按编号/名称/部门/维护人/位置搜索,按分类/状态/位置筛选 - **多维度搜索** — 按编号/名称/部门/维护人/位置搜索,按分类/状态/位置筛选
- **质保提醒** — 已过保/即将过保状态标识 - **质保提醒** — 已过保/即将过保状态标识
- **用户管理** — 超级管理员可查看用户列表、搜索筛选、为任意用户重置密码(密码强度校验,重置自身不掉登录)
- **用户认证** — 登录/退出,管理员权限控制 - **用户认证** — 登录/退出,管理员权限控制
- **深色主题** — 护眼深色 UI,适合长时间使用 - **深色主题** — 护眼深色 UI,适合长时间使用
@@ -120,6 +122,25 @@ DATABASES = {
| DJANGO_DEBUG | False | 调试模式 | | DJANGO_DEBUG | False | 调试模式 |
| DJANGO_SECRET_KEY | your-secret-key... | Django 密钥 | | DJANGO_SECRET_KEY | your-secret-key... | Django 密钥 |
## 👥 用户管理
- 超级管理员登录后,导航栏可见 **用户管理** 入口(路径 `/users/`)
- 支持按用户名 / 姓名 / 邮箱搜索,按账号状态(正常/已禁用)筛选
- 点击"重置密码"可为任意用户设置新密码:
- 两次密码必须一致
- 应用 Django 密码强度校验(最少 8 位、不能与用户信息过于相似、不能是常见/纯数字密码)
- 管理员重置自己的密码后当前登录不会失效
- 该功能仅 **超级管理员(is_superuser)** 可访问,其他用户访问会被拒绝
## 🖥️ 软件资产管理
- 导航栏 **资产管理 → 软件资产**(路径 `/software/`)
- 字段:资产编号、软件名称、软件分类、供应商、版本、许可类型(永久授权/订阅/开源免费/按需付费)、授权数量、许可密钥/激活码、账号、费用、启用/到期日期、负责人、使用部门、状态(在用/闲置/已过期/已注销)、备注
- 到期提醒:已过期/即将到期(30天内)自动标识
- 软件分类独立管理(路径 `/software/categories/`),分类下有资产时禁止删除
- 变更记录:创建/更新/删除/导入/导出全程留痕(路径 `/software/changelog/`)
- Excel 导入导出与硬件一致:模板下载、ID 存在时更新、分类自动创建
## 📊 Excel 导入格式 ## 📊 Excel 导入格式
| 资产编号 | 设备名称 | 分类 | 品牌 | 型号 | 资产面值 | 序列号 | 状态 | IP地址 | BMC地址 | 设备位置 | 负责人 | 使用部门 | 维护人 | 采购日期 | 质保到期 | 备注 | | 资产编号 | 设备名称 | 分类 | 品牌 | 型号 | 资产面值 | 序列号 | 状态 | IP地址 | BMC地址 | 设备位置 | 负责人 | 使用部门 | 维护人 | 采购日期 | 质保到期 | 备注 |
@@ -130,6 +151,16 @@ DATABASES = {
- 日期格式:YYYY-MM-DD - 日期格式:YYYY-MM-DD
- 状态可选:在用、闲置、维修中、已报废 - 状态可选:在用、闲置、维修中、已报废
## 📊 软件资产导入格式
| ID | 资产编号 | 软件名称 | 软件分类 | 供应商 | 版本 | 许可类型 | 授权数量 | 许可密钥/激活码 | 账号 | 费用(元) | 启用日期 | 到期日期 | 负责人 | 使用部门 | 状态 | 备注 |
|----|---------|---------|---------|--------|------|---------|---------|----------------|------|---------|---------|---------|--------|---------|------|------|
- ID 列可选:ID 已存在时更新该记录,否则创建新记录
- 许可类型可选:永久授权、订阅、开源免费、按需付费
- 状态可选:在用、闲置、已过期、已注销
- 日期格式:YYYY-MM-DD
## 📁 项目结构 ## 📁 项目结构
``` ```
@@ -137,7 +168,7 @@ asset-management/
├── assetapp/ # 主应用 ├── assetapp/ # 主应用
│ ├── models.py # 数据模型 │ ├── models.py # 数据模型
│ ├── views.py # 视图逻辑 │ ├── views.py # 视图逻辑
│ ├── forms.py # 表单定义 │ ├── forms.py # 表单定义(含管理员重置密码表单)
│ ├── excel_utils.py # Excel 导入导出工具 │ ├── excel_utils.py # Excel 导入导出工具
│ ├── urls.py # URL 路由 │ ├── urls.py # URL 路由
│ ├── management/commands/ # 管理命令 │ ├── management/commands/ # 管理命令
@@ -147,7 +178,8 @@ asset-management/
│ ├── settings.py │ ├── settings.py
│ ├── urls.py │ ├── urls.py
│ └── wsgi.py │ └── wsgi.py
├── templates/assetapp/ # HTML 模板 │ ├── models.py # 数据模型(硬件资产 + 软件资产)
├── templates/assetapp/ # HTML 模板(含 user_list / software_* 系列)
├── static/css/ # 静态资源 ├── static/css/ # 静态资源
├── docker-compose.yml # Docker 编排 ├── docker-compose.yml # Docker 编排
├── Dockerfile # 容器构建 ├── Dockerfile # 容器构建
@@ -158,6 +190,18 @@ asset-management/
## 📝 版本历史 ## 📝 版本历史
### 1.0.1
- 新增软件资产(软资产)管理:软件分类、软件资产 CRUD、许可类型、到期提醒
- 软件资产 Excel 导入导出、模板下载、独立变更记录
- 仪表盘增加软件资产统计(总数/状态/许可类型分布)
- 导航栏改造:资产管理/分类管理/变更记录/导入导出下拉菜单
### v1.1.0
- 新增用户管理:超级管理员可查看用户列表、搜索筛选、重置任意用户密码
- 补充密码强度校验配置
### v1.0.0 ### v1.0.0
- 资产增删改查 - 资产增删改查
+27 -1
View File
@@ -1,5 +1,8 @@
from django.contrib import admin from django.contrib import admin
from .models import Asset, Category, AssetChangeLog from .models import (
Asset, Category, AssetChangeLog,
SoftwareAsset, SoftwareCategory, SoftwareChangeLog,
)
@admin.register(Category) @admin.register(Category)
@@ -22,3 +25,26 @@ class AssetChangeLogAdmin(admin.ModelAdmin):
list_filter = ['action'] list_filter = ['action']
search_fields = ['asset_number'] search_fields = ['asset_number']
readonly_fields = ['created_at'] readonly_fields = ['created_at']
@admin.register(SoftwareCategory)
class SoftwareCategoryAdmin(admin.ModelAdmin):
list_display = ['name', 'description', 'created_at']
search_fields = ['name']
@admin.register(SoftwareAsset)
class SoftwareAssetAdmin(admin.ModelAdmin):
list_display = ['asset_number', 'name', 'category', 'vendor', 'version',
'license_type', 'seats', 'status', 'expire_date', 'created_at']
list_filter = ['status', 'category', 'license_type']
search_fields = ['asset_number', 'name', 'vendor', 'license_key', 'account']
readonly_fields = ['created_at', 'updated_at']
@admin.register(SoftwareChangeLog)
class SoftwareChangeLogAdmin(admin.ModelAdmin):
list_display = ['asset_number', 'action', 'field_name', 'operator', 'created_at']
list_filter = ['action']
search_fields = ['asset_number']
readonly_fields = ['created_at']
+241 -30
View File
@@ -173,41 +173,26 @@ def import_assets_from_excel(ws, category_map, operator=None):
# 处理状态 # 处理状态
status = STATUS_MAP_REVERSE.get(data.get('status', '在用'), 'in_use') status = STATUS_MAP_REVERSE.get(data.get('status', '在用'), 'in_use')
# 处理日期 # 处理日期 - 直接存字符串
from datetime import datetime as dt purchase_date = data.get('purchase_date', '').strip() or ''
purchase_date = None warranty_expire = data.get('warranty_expire', '').strip() or ''
warranty_expire = None
if data.get('purchase_date'):
try:
purchase_date = dt.strptime(data['purchase_date'], '%Y-%m-%d').date()
except ValueError:
pass
if data.get('warranty_expire'):
try:
warranty_expire = dt.strptime(data['warranty_expire'], '%Y-%m-%d').date()
except ValueError:
pass
# 处理IP # 处理IP
bmc_address = data.get('bmc_address') or None bmc_address = data.get('bmc_address', '').strip() or ''
ip_address = data.get('ip_address') or None ip_address = data.get('ip_address', '').strip() or ''
# 处理资产面值 # 资产面值 - 直接存字符串
from decimal import Decimal, InvalidOperation asset_value = data.get('asset_value', '').strip() or ''
asset_value = None
if data.get('asset_value'):
try:
asset_value = Decimal(str(data['asset_value']).replace(',', ''))
except (InvalidOperation, ValueError):
pass
# 处理ID - 如果提供了ID且已存在,则更新该记录 # 处理ID - 如果提供了ID且已存在,则更新该记录
import_id = data.get('id', '').strip() import_id = data.get('id', '').strip()
asset = None asset = None
is_update = False is_update = False
if import_id: if import_id and import_id.isdigit():
try: try:
asset = Asset.objects.get(id=int(import_id)) id_val = int(import_id) if str(import_id).strip().isdigit() else None
if id_val:
asset = Asset.objects.get(id=id_val)
is_update = True is_update = True
except (Asset.DoesNotExist, ValueError): except (Asset.DoesNotExist, ValueError):
asset = None asset = None
@@ -228,7 +213,7 @@ def import_assets_from_excel(ws, category_map, operator=None):
asset.ip_address = ip_address asset.ip_address = ip_address
asset.gpu_type = data.get('gpu_type', '') asset.gpu_type = data.get('gpu_type', '')
gpu_count_str = data.get('gpu_count', '').strip() gpu_count_str = data.get('gpu_count', '').strip()
asset.gpu_count = int(gpu_count_str) if gpu_count_str else None asset.gpu_count = gpu_count_str if gpu_count_str else ''
asset.purchase_date = purchase_date asset.purchase_date = purchase_date
asset.warranty_expire = warranty_expire asset.warranty_expire = warranty_expire
asset.supplier = data.get('supplier', '') asset.supplier = data.get('supplier', '')
@@ -250,7 +235,7 @@ def import_assets_from_excel(ws, category_map, operator=None):
else: else:
# 创建新记录 # 创建新记录
gpu_count_str = data.get('gpu_count', '').strip() gpu_count_str = data.get('gpu_count', '').strip()
gpu_count = int(gpu_count_str) if gpu_count_str else None gpu_count = gpu_count_str if gpu_count_str else ''
# 创建参数 # 创建参数
create_kwargs = { create_kwargs = {
@@ -281,9 +266,10 @@ def import_assets_from_excel(ws, category_map, operator=None):
} }
# 如果Excel提供了ID,使用该ID创建 # 如果Excel提供了ID,使用该ID创建
if import_id: if import_id and import_id.isdigit():
try: try:
create_kwargs['id'] = int(import_id) if str(import_id).strip().isdigit():
create_kwargs['id'] = int(import_id)
except ValueError: except ValueError:
pass pass
@@ -303,3 +289,228 @@ def import_assets_from_excel(ws, category_map, operator=None):
results['errors'].append(f'第{row_idx}行: {str(e)}') results['errors'].append(f'第{row_idx}行: {str(e)}')
return results return results
# ─── 软资产(软件资产)Excel 支持 ─────────────────
# Excel列定义(顺序与软件资产列表一致)
SOFTWARE_EXPORT_COLUMNS = [
('id', 'ID', 8),
('asset_number', '资产编号', 18),
('name', '软件名称', 25),
('category', '软件分类', 12),
('vendor', '供应商', 18),
('version', '版本', 12),
('license_type', '许可类型', 12),
('seats', '授权数量', 10),
('license_key', '许可密钥/激活码', 30),
('account', '账号', 18),
('cost', '费用(元)', 12),
('start_date', '启用日期', 12),
('expire_date', '到期日期', 12),
('responsible_person', '负责人', 10),
('department', '使用部门', 15),
('status', '状态', 8),
('remark', '备注', 30),
]
SOFTWARE_LICENSE_TYPE_MAP = {
'permanent': '永久授权', 'subscription': '订阅',
'open_source': '开源免费', 'pay_as_you_go': '按需付费',
}
SOFTWARE_LICENSE_TYPE_REVERSE = {v: k for k, v in SOFTWARE_LICENSE_TYPE_MAP.items()}
SOFTWARE_STATUS_MAP = {
'in_use': '在用', 'idle': '闲置', 'expired': '已过期', 'cancelled': '已注销',
}
SOFTWARE_STATUS_MAP_REVERSE = {v: k for k, v in SOFTWARE_STATUS_MAP.items()}
def export_software_assets_to_excel(queryset):
"""导出软件资产到Excel"""
wb = Workbook()
ws = wb.active
ws.title = '软件资产'
for col_idx, (field, header, width) in enumerate(SOFTWARE_EXPORT_COLUMNS, 1):
cell = ws.cell(row=1, column=col_idx, value=header)
cell.fill = HEADER_FILL
cell.font = HEADER_FONT
cell.alignment = Alignment(horizontal='center', vertical='center')
cell.border = THIN_BORDER
ws.column_dimensions[get_column_letter(col_idx)].width = width
for row_idx, sw in enumerate(queryset, 2):
for col_idx, (field, _, _) in enumerate(SOFTWARE_EXPORT_COLUMNS, 1):
if field == 'id':
value = sw.id
elif field == 'category':
value = str(sw.category) if sw.category else ''
elif field == 'status':
value = SOFTWARE_STATUS_MAP.get(sw.status, sw.status)
elif field == 'license_type':
value = SOFTWARE_LICENSE_TYPE_MAP.get(sw.license_type, sw.license_type)
else:
value = getattr(sw, field, '') or ''
cell = ws.cell(row=row_idx, column=col_idx, value=value)
cell.font = CELL_FONT
cell.border = THIN_BORDER
cell.alignment = Alignment(vertical='center')
ws.freeze_panes = 'A2'
return wb
def generate_software_import_template():
"""生成软件资产导入模板"""
wb = Workbook()
ws = wb.active
ws.title = '软件资产导入模板'
for col_idx, (field, header, width) in enumerate(SOFTWARE_EXPORT_COLUMNS, 1):
cell = ws.cell(row=1, column=col_idx, value=header)
cell.fill = HEADER_FILL
cell.font = HEADER_FONT
cell.alignment = Alignment(horizontal='center', vertical='center')
cell.border = THIN_BORDER
ws.column_dimensions[get_column_letter(col_idx)].width = width
example_data = [
'1', 'SW-2026-0001', 'Windows Server 2022', '操作系统', '微软', '2022 Datacenter',
'永久授权', '50', 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX', 'it@company.com',
'120000', '2025-01-01', '2027-01-01', '张三', '研发部', '在用', '采购备注'
]
for col_idx, value in enumerate(example_data, 1):
cell = ws.cell(row=2, column=col_idx, value=value)
cell.font = Font(name='微软雅黑', size=10, color='666666')
cell.border = THIN_BORDER
ws.freeze_panes = 'A2'
return wb
def import_software_from_excel(ws, category_map, operator=None):
"""从Excel导入软件资产,返回结果统计"""
from .models import SoftwareAsset, SoftwareCategory, SoftwareChangeLog
header_row = [cell.value for cell in ws[1]]
field_map = {header: field for field, header, _ in SOFTWARE_EXPORT_COLUMNS}
results = {
'success': 0,
'skipped': 0,
'errors': [],
'total': 0,
}
for row_idx, row in enumerate(ws.iter_rows(min_row=2, values_only=True), 2):
# 跳过完全空白的行(ID 列可以为空)
if not row or all(v is None or str(v).strip() == '' for v in row):
continue
results['total'] += 1
try:
data = {}
for col_idx, value in enumerate(row):
if col_idx < len(header_row):
field = field_map.get(header_row[col_idx])
if field:
data[field] = str(value).strip() if value is not None else ''
# 资产编号必填
asset_number = data.get('asset_number', '').strip()
if not asset_number:
results['errors'].append(f'第{row_idx}行: 缺少资产编号')
continue
# 软件名称必填
sw_name = data.get('name', '').strip()
if not sw_name:
results['errors'].append(f'第{row_idx}行: 缺少软件名称')
continue
# 处理分类 - 不存在则自动创建
category_name = data.get('category', '').strip()
category = category_map.get(category_name)
if not category and category_name:
category = SoftwareCategory.objects.create(name=category_name)
category_map[category_name] = category
elif not category_name:
category = category_map.get('未分类')
if not category:
category = SoftwareCategory.objects.create(name='未分类')
category_map['未分类'] = category
# 许可类型
license_type = SOFTWARE_LICENSE_TYPE_REVERSE.get(
data.get('license_type', '订阅'), 'subscription')
# 状态
status = SOFTWARE_STATUS_MAP_REVERSE.get(data.get('status', '在用'), 'in_use')
# 处理ID - 如果提供了ID且已存在,则更新该记录
import_id = data.get('id', '').strip()
sw_asset = None
if import_id and import_id.isdigit():
try:
sw_asset = SoftwareAsset.objects.get(id=int(import_id))
except (SoftwareAsset.DoesNotExist, ValueError):
sw_asset = None
common_fields = {
'asset_number': asset_number,
'name': sw_name,
'category': category,
'vendor': data.get('vendor', ''),
'version': data.get('version', ''),
'license_type': license_type,
'license_key': data.get('license_key', ''),
'seats': data.get('seats', ''),
'account': data.get('account', ''),
'cost': data.get('cost', ''),
'start_date': data.get('start_date', '').strip(),
'expire_date': data.get('expire_date', '').strip(),
'responsible_person': data.get('responsible_person', ''),
'department': data.get('department', ''),
'status': status,
'remark': data.get('remark', ''),
}
if sw_asset:
# 更新已有记录
for field, value in common_fields.items():
setattr(sw_asset, field, value)
sw_asset.save()
SoftwareChangeLog.objects.create(
software_asset=sw_asset,
asset_number=sw_asset.asset_number,
action='import',
description=f'通过Excel导入更新(ID:{sw_asset.id})',
operator=operator,
)
else:
# 创建新记录
create_kwargs = dict(common_fields)
create_kwargs['created_by'] = operator
if import_id and import_id.isdigit():
create_kwargs['id'] = int(import_id)
sw_asset = SoftwareAsset.objects.create(**create_kwargs)
SoftwareChangeLog.objects.create(
software_asset=sw_asset,
asset_number=sw_asset.asset_number,
action='import',
description='通过Excel导入创建',
operator=operator,
)
results['success'] += 1
except Exception as e:
results['errors'].append(f'第{row_idx}行: {str(e)}')
return results
+63 -1
View File
@@ -1,5 +1,6 @@
from django import forms from django import forms
from .models import Asset, Category from django.contrib.auth.password_validation import password_validators_help_text_html, validate_password
from .models import Asset, Category, SoftwareAsset, SoftwareCategory
class AssetForm(forms.ModelForm): class AssetForm(forms.ModelForm):
@@ -33,3 +34,64 @@ class CategoryForm(forms.ModelForm):
class Meta: class Meta:
model = Category model = Category
fields = ['name', 'description'] fields = ['name', 'description']
class SoftwareCategoryForm(forms.ModelForm):
class Meta:
model = SoftwareCategory
fields = ['name', 'description']
class SoftwareAssetForm(forms.ModelForm):
class Meta:
model = SoftwareAsset
fields = [
'asset_number', 'name', 'category',
'vendor', 'version', 'license_type', 'license_key', 'seats',
'account', 'cost', 'start_date', 'expire_date',
'responsible_person', 'department', 'status', 'remark',
]
widgets = {
'start_date': forms.DateInput(attrs={'type': 'date'}),
'expire_date': forms.DateInput(attrs={'type': 'date'}),
'remark': forms.Textarea(attrs={'rows': 3}),
'status': forms.Select(attrs={'class': 'form-select'}),
'category': forms.Select(attrs={'class': 'form-select'}),
'license_type': forms.Select(attrs={'class': 'form-select'}),
}
class AdminPasswordResetForm(forms.Form):
"""管理员重置指定用户密码的表单"""
new_password1 = forms.CharField(
label='新密码',
widget=forms.PasswordInput(attrs={'class': 'form-control', 'autocomplete': 'new-password'}),
help_text=password_validators_help_text_html(),
)
new_password2 = forms.CharField(
label='确认新密码',
widget=forms.PasswordInput(attrs={'class': 'form-control', 'autocomplete': 'new-password'}),
)
def __init__(self, *args, target_user=None, **kwargs):
self.target_user = target_user
super().__init__(*args, **kwargs)
def clean(self):
cleaned_data = super().clean()
password1 = cleaned_data.get('new_password1')
password2 = cleaned_data.get('new_password2')
if password1 and password2 and password1 != password2:
raise forms.ValidationError('两次输入的密码不一致')
if password1 and self.target_user is not None:
validate_password(password1, self.target_user)
return cleaned_data
def save(self):
self.target_user.set_password(self.cleaned_data['new_password1'])
self.target_user.save(update_fields=['password'])
return self.target_user
@@ -0,0 +1,113 @@
# Generated by Django 5.2.13 on 2026-10-15 11:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('assetapp', '0008_alter_asset_location'),
]
operations = [
migrations.AlterField(
model_name='asset',
name='asset_value',
field=models.CharField(blank=True, default='', max_length=50, verbose_name='资产面值'),
),
migrations.AlterField(
model_name='asset',
name='bmc_address',
field=models.CharField(blank=True, default='', max_length=200, verbose_name='BMC地址'),
),
migrations.AlterField(
model_name='asset',
name='brand',
field=models.CharField(blank=True, default='', max_length=200, verbose_name='品牌'),
),
migrations.AlterField(
model_name='asset',
name='business_type',
field=models.CharField(blank=True, default='', max_length=200, verbose_name='业务类型'),
),
migrations.AlterField(
model_name='asset',
name='cabinet',
field=models.CharField(blank=True, default='', max_length=200, verbose_name='机柜'),
),
migrations.AlterField(
model_name='asset',
name='cabinet_position',
field=models.CharField(blank=True, default='', help_text='U位', max_length=200, verbose_name='机柜位置'),
),
migrations.AlterField(
model_name='asset',
name='department',
field=models.CharField(blank=True, default='', max_length=200, verbose_name='使用部门'),
),
migrations.AlterField(
model_name='asset',
name='gpu_count',
field=models.CharField(blank=True, default='', max_length=50, verbose_name='卡数'),
),
migrations.AlterField(
model_name='asset',
name='gpu_type',
field=models.CharField(blank=True, default='', max_length=200, verbose_name='显卡类型'),
),
migrations.AlterField(
model_name='asset',
name='has_gpu',
field=models.CharField(blank=True, default='', max_length=50, verbose_name='是否带卡'),
),
migrations.AlterField(
model_name='asset',
name='ip_address',
field=models.CharField(blank=True, default='', max_length=200, verbose_name='IP地址'),
),
migrations.AlterField(
model_name='asset',
name='model',
field=models.CharField(blank=True, default='', max_length=200, verbose_name='型号'),
),
migrations.AlterField(
model_name='asset',
name='purchase_date',
field=models.CharField(blank=True, default='', max_length=50, verbose_name='采购日期'),
),
migrations.AlterField(
model_name='asset',
name='remark',
field=models.CharField(blank=True, default='', max_length=500, verbose_name='备注'),
),
migrations.AlterField(
model_name='asset',
name='responsible_person',
field=models.CharField(blank=True, default='', max_length=200, verbose_name='负责人'),
),
migrations.AlterField(
model_name='asset',
name='serial_number',
field=models.CharField(blank=True, db_index=True, default='', max_length=200, verbose_name='序列号'),
),
migrations.AlterField(
model_name='asset',
name='status',
field=models.CharField(choices=[('in_use', '在用'), ('idle', '闲置'), ('maintenance', '维修中'), ('scrapped', '已报废')], default='in_use', max_length=50, verbose_name='状态'),
),
migrations.AlterField(
model_name='asset',
name='supplier',
field=models.CharField(blank=True, default='', max_length=200, verbose_name='供应商'),
),
migrations.AlterField(
model_name='asset',
name='user',
field=models.CharField(blank=True, default='', max_length=200, verbose_name='维护人'),
),
migrations.AlterField(
model_name='asset',
name='warranty_expire',
field=models.CharField(blank=True, default='', max_length=50, verbose_name='质保到期'),
),
]
@@ -0,0 +1,80 @@
# Generated by Django 5.2.13 on 2026-11-11 09:12
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('assetapp', '0009_alter_asset_asset_value_alter_asset_bmc_address_and_more'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='SoftwareCategory',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50, unique=True, verbose_name='分类名称')),
('description', models.CharField(blank=True, default='', max_length=200, verbose_name='描述')),
('created_at', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')),
],
options={
'verbose_name': '软件分类',
'verbose_name_plural': '软件分类',
'ordering': ['name'],
},
),
migrations.CreateModel(
name='SoftwareAsset',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('asset_number', models.CharField(db_index=True, max_length=50, verbose_name='资产编号')),
('name', models.CharField(max_length=100, verbose_name='软件名称')),
('vendor', models.CharField(blank=True, default='', max_length=200, verbose_name='供应商')),
('version', models.CharField(blank=True, default='', max_length=100, verbose_name='版本')),
('license_type', models.CharField(choices=[('permanent', '永久授权'), ('subscription', '订阅'), ('open_source', '开源免费'), ('pay_as_you_go', '按需付费')], default='subscription', max_length=50, verbose_name='许可类型')),
('license_key', models.CharField(blank=True, default='', max_length=500, verbose_name='许可密钥/激活码')),
('seats', models.CharField(blank=True, default='', max_length=50, verbose_name='授权数量')),
('account', models.CharField(blank=True, default='', max_length=200, verbose_name='账号')),
('cost', models.CharField(blank=True, default='', max_length=50, verbose_name='费用(元)')),
('start_date', models.CharField(blank=True, default='', max_length=50, verbose_name='启用日期')),
('expire_date', models.CharField(blank=True, default='', max_length=50, verbose_name='到期日期')),
('responsible_person', models.CharField(blank=True, default='', max_length=200, verbose_name='负责人')),
('department', models.CharField(blank=True, default='', max_length=200, verbose_name='使用部门')),
('status', models.CharField(choices=[('in_use', '在用'), ('idle', '闲置'), ('expired', '已过期'), ('cancelled', '已注销')], default='in_use', max_length=50, verbose_name='状态')),
('remark', models.CharField(blank=True, default='', max_length=500, verbose_name='备注')),
('created_at', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')),
('updated_at', models.DateTimeField(auto_now=True, verbose_name='更新时间')),
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL, verbose_name='创建人')),
('category', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='software_assets', to='assetapp.softwarecategory', verbose_name='软件分类')),
],
options={
'verbose_name': '软件资产',
'verbose_name_plural': '软件资产',
'ordering': ['id'],
},
),
migrations.CreateModel(
name='SoftwareChangeLog',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('asset_number', models.CharField(db_index=True, max_length=50, verbose_name='资产编号')),
('action', models.CharField(choices=[('create', '创建'), ('update', '更新'), ('delete', '删除'), ('import', '导入'), ('export', '导出'), ('status_change', '状态变更')], max_length=20, verbose_name='操作类型')),
('field_name', models.CharField(blank=True, default='', max_length=50, verbose_name='变更字段')),
('old_value', models.TextField(blank=True, default='', verbose_name='旧值')),
('new_value', models.TextField(blank=True, default='', verbose_name='新值')),
('description', models.TextField(blank=True, default='', verbose_name='描述')),
('created_at', models.DateTimeField(auto_now_add=True, verbose_name='操作时间')),
('operator', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL, verbose_name='操作人')),
('software_asset', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='change_logs', to='assetapp.softwareasset', verbose_name='软件资产')),
],
options={
'verbose_name': '软件资产变更记录',
'verbose_name_plural': '软件资产变更记录',
'ordering': ['-created_at'],
},
),
]
+173 -40
View File
@@ -21,6 +21,41 @@ class Category(models.Model):
class Asset(models.Model): class Asset(models.Model):
"""硬件资产""" """硬件资产"""
# 基本信息
asset_number = models.CharField('资产编号', max_length=50, db_index=True)
name = models.CharField('设备名称', max_length=100)
category = models.ForeignKey(Category, on_delete=models.PROTECT, verbose_name='设备分类', related_name='assets')
# 硬件信息
brand = models.CharField('品牌', max_length=200, blank=True, default='')
model = models.CharField('型号', max_length=200, blank=True, default='')
asset_value = models.CharField('资产面值', max_length=50, blank=True, default='')
serial_number = models.CharField('序列号', max_length=200, blank=True, default='', db_index=True)
# 位置信息
location = models.CharField('机房', max_length=200, blank=True, default='', help_text='楼层/房间/区域')
cabinet = models.CharField('机柜', max_length=200, blank=True, default='')
cabinet_position = models.CharField('机柜位置', max_length=200, blank=True, default='', help_text='U位')
# 网络信息
bmc_address = models.CharField('BMC地址', max_length=200, blank=True, default='')
ip_address = models.CharField('IP地址', max_length=200, blank=True, default='')
# 显卡信息
has_gpu = models.CharField('是否带卡', max_length=50, blank=True, default='')
gpu_type = models.CharField('显卡类型', max_length=200, blank=True, default='')
gpu_count = models.CharField('卡数', max_length=50, blank=True, default='')
# 采购与质保
purchase_date = models.CharField('采购日期', max_length=50, blank=True, default='')
warranty_expire = models.CharField('质保到期', max_length=50, blank=True, default='')
supplier = models.CharField('供应商', max_length=200, blank=True, default='')
# 管理信息
responsible_person = models.CharField('负责人', max_length=200, blank=True, default='')
department = models.CharField('使用部门', max_length=200, blank=True, default='')
user = models.CharField('维护人', max_length=200, blank=True, default='')
business_type = models.CharField('业务类型', max_length=200, blank=True, default='')
STATUS_CHOICES = [ STATUS_CHOICES = [
('in_use', '在用'), ('in_use', '在用'),
('idle', '闲置'), ('idle', '闲置'),
@@ -28,43 +63,8 @@ class Asset(models.Model):
('scrapped', '已报废'), ('scrapped', '已报废'),
] ]
# 基本信息 status = models.CharField('状态', max_length=50, choices=STATUS_CHOICES, default='in_use')
asset_number = models.CharField('资产编号', max_length=50, db_index=True) remark = models.CharField('备注', max_length=500, blank=True, default='')
name = models.CharField('设备名称', max_length=100)
category = models.ForeignKey(Category, on_delete=models.PROTECT, verbose_name='设备分类', related_name='assets')
# 硬件信息
brand = models.CharField('品牌', max_length=50, blank=True, default='')
model = models.CharField('型号', max_length=100, blank=True, default='')
asset_value = models.DecimalField('资产面值', max_digits=12, decimal_places=2, blank=True, null=True)
serial_number = models.CharField('序列号', max_length=100, blank=True, default='', db_index=True)
# 位置信息
location = models.CharField('机房', max_length=200, blank=True, default='', help_text='楼层/房间/区域')
cabinet = models.CharField('机柜', max_length=50, blank=True, default='')
cabinet_position = models.CharField('机柜位置', max_length=50, blank=True, default='', help_text='U位')
# 网络信息
bmc_address = models.GenericIPAddressField('BMC地址', blank=True, null=True)
ip_address = models.GenericIPAddressField('IP地址', blank=True, null=True)
# 显卡信息
has_gpu = models.CharField('是否带卡', max_length=20, blank=True, default='')
gpu_type = models.CharField('显卡类型', max_length=100, blank=True, default='')
gpu_count = models.IntegerField('卡数', blank=True, null=True)
# 采购与质保
purchase_date = models.DateField('采购日期', blank=True, null=True)
warranty_expire = models.DateField('质保到期', blank=True, null=True)
supplier = models.CharField('供应商', max_length=100, blank=True, default='')
# 管理信息
responsible_person = models.CharField('负责人', max_length=50, blank=True, default='')
department = models.CharField('使用部门', max_length=100, blank=True, default='')
user = models.CharField('维护人', max_length=50, blank=True, default='')
business_type = models.CharField('业务类型', max_length=100, blank=True, default='')
status = models.CharField('状态', max_length=20, choices=STATUS_CHOICES, default='in_use')
remark = models.TextField('备注', blank=True, default='')
# 系统字段 # 系统字段
created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='创建人') created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='创建人')
@@ -82,14 +82,23 @@ class Asset(models.Model):
@property @property
def is_expired(self): def is_expired(self):
if self.warranty_expire: if self.warranty_expire:
return self.warranty_expire < date.today() try:
from datetime import datetime
expire_date = datetime.strptime(self.warranty_expire, '%Y-%m-%d').date()
return expire_date < date.today()
except (ValueError, TypeError):
return False
return False return False
@property @property
def is_expiring_soon(self): def is_expiring_soon(self):
if self.warranty_expire: if self.warranty_expire:
from datetime import timedelta try:
return date.today() <= self.warranty_expire <= date.today() + timedelta(days=30) from datetime import datetime, timedelta
expire_date = datetime.strptime(self.warranty_expire, '%Y-%m-%d').date()
return date.today() <= expire_date <= date.today() + timedelta(days=30)
except (ValueError, TypeError):
return False
return False return False
@@ -123,3 +132,127 @@ class AssetChangeLog(models.Model):
def __str__(self): def __str__(self):
return f'{self.asset_number} - {self.get_action_display()}' return f'{self.asset_number} - {self.get_action_display()}'
class SoftwareCategory(models.Model):
"""软件分类(软资产)"""
name = models.CharField('分类名称', max_length=50, unique=True)
description = models.CharField('描述', max_length=200, blank=True, default='')
created_at = models.DateTimeField('创建时间', auto_now_add=True)
class Meta:
verbose_name = '软件分类'
verbose_name_plural = verbose_name
ordering = ['name']
def __str__(self):
return self.name
class SoftwareAsset(models.Model):
"""软件资产(软资产)"""
# 基本信息
asset_number = models.CharField('资产编号', max_length=50, db_index=True)
name = models.CharField('软件名称', max_length=100)
category = models.ForeignKey(SoftwareCategory, on_delete=models.PROTECT, verbose_name='软件分类', related_name='software_assets')
# 许可信息
vendor = models.CharField('供应商', max_length=200, blank=True, default='')
version = models.CharField('版本', max_length=100, blank=True, default='')
LICENSE_TYPE_CHOICES = [
('permanent', '永久授权'),
('subscription', '订阅'),
('open_source', '开源免费'),
('pay_as_you_go', '按需付费'),
]
license_type = models.CharField('许可类型', max_length=50, choices=LICENSE_TYPE_CHOICES, default='subscription')
license_key = models.CharField('许可密钥/激活码', max_length=500, blank=True, default='')
seats = models.CharField('授权数量', max_length=50, blank=True, default='')
# 账号信息
account = models.CharField('账号', max_length=200, blank=True, default='')
# 费用与日期
cost = models.CharField('费用(元)', max_length=50, blank=True, default='')
start_date = models.CharField('启用日期', max_length=50, blank=True, default='')
expire_date = models.CharField('到期日期', max_length=50, blank=True, default='')
# 管理信息
responsible_person = models.CharField('负责人', max_length=200, blank=True, default='')
department = models.CharField('使用部门', max_length=200, blank=True, default='')
STATUS_CHOICES = [
('in_use', '在用'),
('idle', '闲置'),
('expired', '已过期'),
('cancelled', '已注销'),
]
status = models.CharField('状态', max_length=50, choices=STATUS_CHOICES, default='in_use')
remark = models.CharField('备注', max_length=500, blank=True, default='')
# 系统字段
created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='创建人')
created_at = models.DateTimeField('创建时间', auto_now_add=True)
updated_at = models.DateTimeField('更新时间', auto_now=True)
class Meta:
verbose_name = '软件资产'
verbose_name_plural = verbose_name
ordering = ['id']
def __str__(self):
return f'{self.asset_number} - {self.name}'
@property
def is_expired(self):
if self.expire_date:
try:
from datetime import datetime
expire = datetime.strptime(self.expire_date, '%Y-%m-%d').date()
return expire < date.today()
except (ValueError, TypeError):
return False
return False
@property
def is_expiring_soon(self):
if self.expire_date:
try:
from datetime import datetime, timedelta
expire = datetime.strptime(self.expire_date, '%Y-%m-%d').date()
return date.today() <= expire <= date.today() + timedelta(days=30)
except (ValueError, TypeError):
return False
return False
class SoftwareChangeLog(models.Model):
"""软件资产变更记录"""
ACTION_CHOICES = [
('create', '创建'),
('update', '更新'),
('delete', '删除'),
('import', '导入'),
('export', '导出'),
('status_change', '状态变更'),
]
software_asset = models.ForeignKey(SoftwareAsset, on_delete=models.SET_NULL, null=True, blank=True,
verbose_name='软件资产', related_name='change_logs')
asset_number = models.CharField('资产编号', max_length=50, db_index=True)
action = models.CharField('操作类型', max_length=20, choices=ACTION_CHOICES)
field_name = models.CharField('变更字段', max_length=50, blank=True, default='')
old_value = models.TextField('旧值', blank=True, default='')
new_value = models.TextField('新值', blank=True, default='')
description = models.TextField('描述', blank=True, default='')
operator = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='操作人')
created_at = models.DateTimeField('操作时间', auto_now_add=True)
class Meta:
verbose_name = '软件资产变更记录'
verbose_name_plural = verbose_name
ordering = ['-created_at']
def __str__(self):
return f'{self.asset_number} - {self.get_action_display()}'
+21
View File
@@ -29,4 +29,25 @@ urlpatterns = [
path('categories/create/', views.category_create, name='category_create'), path('categories/create/', views.category_create, name='category_create'),
path('categories/<int:pk>/edit/', views.category_update, name='category_update'), path('categories/<int:pk>/edit/', views.category_update, name='category_update'),
path('categories/<int:pk>/delete/', views.category_delete, name='category_delete'), path('categories/<int:pk>/delete/', views.category_delete, name='category_delete'),
# 软件资产(软资产)
path('software/', views.software_list, name='software_list'),
path('software/create/', views.software_create, name='software_create'),
path('software/<int:pk>/', views.software_detail, name='software_detail'),
path('software/<int:pk>/edit/', views.software_update, name='software_update'),
path('software/<int:pk>/delete/', views.software_delete, name='software_delete'),
path('software/export/', views.software_export, name='software_export'),
path('software/import/', views.software_import, name='software_import'),
path('software/import/template/', views.download_software_template, name='download_software_template'),
path('software/changelog/', views.software_change_log_list, name='software_changelog'),
# 软件分类管理
path('software/categories/', views.software_category_list, name='software_category_list'),
path('software/categories/create/', views.software_category_create, name='software_category_create'),
path('software/categories/<int:pk>/edit/', views.software_category_update, name='software_category_update'),
path('software/categories/<int:pk>/delete/', views.software_category_delete, name='software_category_delete'),
# 用户管理(仅超级管理员)
path('users/', views.user_list, name='user_list'),
path('users/<int:pk>/password/', views.admin_password_reset, name='admin_password_reset'),
] ]
+457 -5
View File
@@ -1,6 +1,7 @@
from django.shortcuts import render, redirect, get_object_or_404 from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required from django.contrib.auth.decorators import login_required, user_passes_test
from django.contrib.auth import authenticate, login, logout from django.contrib.auth import authenticate, login, logout, update_session_auth_hash
from django.contrib.auth.models import User
from django.contrib import messages from django.contrib import messages
from django.http import HttpResponse, JsonResponse from django.http import HttpResponse, JsonResponse
from django.db.models import Count, Q from django.db.models import Count, Q
@@ -10,11 +11,14 @@ from openpyxl import load_workbook
from io import BytesIO from io import BytesIO
from datetime import date, timedelta from datetime import date, timedelta
from .models import Asset, Category, AssetChangeLog from .models import Asset, Category, AssetChangeLog, SoftwareAsset, SoftwareCategory, SoftwareChangeLog
from .forms import AssetForm, AssetImportForm, CategoryForm from .forms import (AssetForm, AssetImportForm, CategoryForm, AdminPasswordResetForm,
SoftwareAssetForm, SoftwareCategoryForm)
from .excel_utils import ( from .excel_utils import (
export_assets_to_excel, generate_import_template, export_assets_to_excel, generate_import_template,
import_assets_from_excel, STATUS_MAP, import_assets_from_excel, STATUS_MAP,
export_software_assets_to_excel, generate_software_import_template,
import_software_from_excel, SOFTWARE_STATUS_MAP,
) )
@@ -70,6 +74,25 @@ def dashboard(request):
# 最近变更 # 最近变更
recent_changes = AssetChangeLog.objects.select_related('operator')[:10] recent_changes = AssetChangeLog.objects.select_related('operator')[:10]
# 软件资产统计(软资产)
total_software = SoftwareAsset.objects.count()
software_status_stats = SoftwareAsset.objects.values('status').annotate(count=Count('id'))
software_status_data = {item['status']: item['count'] for item in software_status_stats}
software_category_stats = SoftwareAsset.objects.values('category__name').annotate(
count=Count('id')).order_by('-count')
software_license_stats = SoftwareAsset.objects.values('license_type').annotate(count=Count('id'))
software_license_data = {item['license_type']: item['count'] for item in software_license_stats}
sw_expiring_soon = SoftwareAsset.objects.filter(
expire_date__lte=today + timedelta(days=30),
expire_date__gte=today,
status='in_use',
).count()
sw_expired = SoftwareAsset.objects.filter(
expire_date__lt=today,
status='in_use',
).count()
recent_software_changes = SoftwareChangeLog.objects.select_related('operator')[:10]
context = { context = {
'total_assets': total_assets, 'total_assets': total_assets,
'status_data': status_data, 'status_data': status_data,
@@ -78,6 +101,14 @@ def dashboard(request):
'expiring_soon': expiring_soon, 'expiring_soon': expiring_soon,
'expired': expired, 'expired': expired,
'recent_changes': recent_changes, 'recent_changes': recent_changes,
'total_software': total_software,
'software_status_data': software_status_data,
'software_category_stats': software_category_stats,
'sw_expiring_soon': sw_expiring_soon,
'sw_expired': sw_expired,
'recent_software_changes': recent_software_changes,
'software_status_map': SOFTWARE_STATUS_MAP,
'software_license_data': software_license_data,
} }
return render(request, 'assetapp/dashboard.html', context) return render(request, 'assetapp/dashboard.html', context)
@@ -285,7 +316,34 @@ def asset_export(request):
if status: if status:
queryset = queryset.filter(status=status) queryset = queryset.filter(status=status)
wb = export_assets_to_excel(queryset) # 按资产编号导出(支持逗号/空格/换行分隔多个编号,精确匹配)
asset_numbers_raw = request.GET.get('asset_numbers', '').strip()
missing_numbers = []
ordered_assets = None
if asset_numbers_raw:
numbers = [n.strip() for n in asset_numbers_raw.replace(',', ',').replace('、', ',').replace('\n', ',').replace(' ', ',').split(',') if n.strip()]
# 去重,保持顺序
seen = set()
numbers = [n for n in numbers if not (n in seen or seen.add(n))]
if numbers:
queryset = queryset.filter(asset_number__in=numbers)
# 检查哪些编号不存在
found = set(queryset.values_list('asset_number', flat=True))
missing_numbers = [n for n in numbers if n not in found]
# 按用户输入的编号顺序导出(而非默认ID顺序)
rank = {n: i for i, n in enumerate(numbers)}
ordered_assets = sorted(queryset, key=lambda a: rank.get(a.asset_number, len(rank)))
if missing_numbers:
messages.warning(
request,
f'以下 {len(missing_numbers)} 个资产编号未找到: {", ".join(missing_numbers)}'
)
if asset_numbers_raw:
wb = export_assets_to_excel(ordered_assets)
else:
wb = export_assets_to_excel(queryset)
output = BytesIO() output = BytesIO()
wb.save(output) wb.save(output)
@@ -437,3 +495,397 @@ def category_delete(request, pk):
return redirect('category_list') return redirect('category_list')
return render(request, 'assetapp/category_confirm_delete.html', {'category': category}) return render(request, 'assetapp/category_confirm_delete.html', {'category': category})
# ─── 用户管理(仅超级管理员) ───────────────────────
superuser_required = user_passes_test(lambda u: u.is_authenticated and u.is_superuser)
@superuser_required
def user_list(request):
users = User.objects.order_by('id')
keyword = request.GET.get('search', '').strip()
if keyword:
users = users.filter(
Q(username__icontains=keyword) |
Q(first_name__icontains=keyword) |
Q(email__icontains=keyword)
)
is_active = request.GET.get('is_active')
if is_active in ('1', '0'):
users = users.filter(is_active=(is_active == '1'))
paginator = Paginator(users, 20)
page_obj = paginator.get_page(request.GET.get('page', 1))
context = {
'page_obj': page_obj,
'search': keyword,
'current_is_active': is_active,
}
return render(request, 'assetapp/user_list.html', context)
@superuser_required
def admin_password_reset(request, pk):
target_user = get_object_or_404(User, pk=pk)
if request.method == 'POST':
form = AdminPasswordResetForm(request.POST, target_user=target_user)
if form.is_valid():
form.save()
# 如果管理员重置的是自己的密码,保持当前登录会话不失效
if request.user.pk == target_user.pk:
update_session_auth_hash(request, target_user)
messages.success(request, f'用户 "{target_user.username}" 的密码已重置')
return redirect('user_list')
else:
form = AdminPasswordResetForm(target_user=target_user)
context = {'form': form, 'target_user': target_user}
return render(request, 'assetapp/user_password_reset.html', context)
# ─── 软件资产(软资产)管理 ─────────────────────────
SOFTWARE_LICENSE_TYPE_LABELS = {
'permanent': '永久授权', 'subscription': '订阅',
'open_source': '开源免费', 'pay_as_you_go': '按需付费',
}
@login_required
def software_list(request):
queryset = SoftwareAsset.objects.select_related('category')
# 搜索
search = request.GET.get('search', '').strip()
if search:
queryset = queryset.filter(
Q(asset_number__icontains=search) |
Q(name__icontains=search) |
Q(vendor__icontains=search) |
Q(version__icontains=search) |
Q(license_key__icontains=search) |
Q(account__icontains=search) |
Q(responsible_person__icontains=search) |
Q(department__icontains=search)
)
# 筛选
category_id = request.GET.get('category')
if category_id:
queryset = queryset.filter(category_id=category_id)
status = request.GET.get('status')
if status:
queryset = queryset.filter(status=status)
license_type = request.GET.get('license_type')
if license_type:
queryset = queryset.filter(license_type=license_type)
department = request.GET.get('department')
if department:
queryset = queryset.filter(department__icontains=department)
# 排序
sort = request.GET.get('sort', 'id')
valid_sorts = ['id', '-id', 'asset_number', '-asset_number', 'name', '-name',
'expire_date', '-expire_date', 'created_at', '-created_at']
if sort not in valid_sorts:
sort = 'id'
queryset = queryset.order_by(sort)
# 分页
paginator = Paginator(queryset, settings.ASSETS_PER_PAGE)
page_obj = paginator.get_page(request.GET.get('page', 1))
categories = SoftwareCategory.objects.all()
departments = sorted(set(
SoftwareAsset.objects.values_list('department', flat=True)
.exclude(department='')
.exclude(department=None)
))
# 导出链接附带当前筛选
export_params = []
if search:
export_params.append(f'search={search}')
if category_id:
export_params.append(f'category={category_id}')
if status:
export_params.append(f'status={status}')
query_string = '?' + '&'.join(export_params) if export_params else ''
context = {
'page_obj': page_obj,
'search': search,
'categories': categories,
'current_category': category_id,
'current_status': status,
'current_license_type': license_type,
'current_department': department,
'departments': departments,
'license_type_map': SOFTWARE_LICENSE_TYPE_LABELS,
'status_map': SOFTWARE_STATUS_MAP,
'sort': sort,
'query_string': query_string,
}
return render(request, 'assetapp/software_list.html', context)
@login_required
def software_detail(request, pk):
sw_asset = get_object_or_404(
SoftwareAsset.objects.select_related('category', 'created_by'), pk=pk)
change_logs = sw_asset.change_logs.select_related('operator')[:20]
context = {
'sw_asset': sw_asset,
'change_logs': change_logs,
'status_map': SOFTWARE_STATUS_MAP,
'license_type_map': SOFTWARE_LICENSE_TYPE_LABELS,
}
return render(request, 'assetapp/software_detail.html', context)
@login_required
def software_create(request):
if request.method == 'POST':
form = SoftwareAssetForm(request.POST)
if form.is_valid():
sw_asset = form.save(commit=False)
sw_asset.created_by = request.user
sw_asset.save()
SoftwareChangeLog.objects.create(
software_asset=sw_asset,
asset_number=sw_asset.asset_number,
action='create',
description='创建软件资产',
operator=request.user,
)
messages.success(request, f'软件资产 {sw_asset.asset_number} 创建成功!')
return redirect('software_detail', pk=sw_asset.pk)
else:
form = SoftwareAssetForm()
context = {'form': form, 'action': 'create'}
return render(request, 'assetapp/software_form.html', context)
@login_required
def software_update(request, pk):
sw_asset = get_object_or_404(SoftwareAsset, pk=pk)
if request.method == 'POST':
form = SoftwareAssetForm(request.POST, instance=sw_asset)
if form.is_valid():
# 记录变更
for field in form.changed_data:
SoftwareChangeLog.objects.create(
software_asset=sw_asset,
asset_number=sw_asset.asset_number,
action='update',
field_name=field,
old_value=str(form.initial.get(field, '')),
new_value=str(form.cleaned_data.get(field, '')),
operator=request.user,
)
sw_asset = form.save()
if form.changed_data:
messages.success(request, f'已更新 {len(form.changed_data)} 个字段')
return redirect('software_detail', pk=sw_asset.pk)
else:
form = SoftwareAssetForm(instance=sw_asset)
context = {'form': form, 'action': 'update', 'sw_asset': sw_asset}
return render(request, 'assetapp/software_form.html', context)
@login_required
def software_delete(request, pk):
sw_asset = get_object_or_404(SoftwareAsset, pk=pk)
if request.method == 'POST':
SoftwareChangeLog.objects.create(
asset_number=sw_asset.asset_number,
action='delete',
description=f'删除软件资产: {sw_asset.name}',
operator=request.user,
)
sw_asset.delete()
messages.success(request, f'软件资产 {sw_asset.asset_number} 已删除')
return redirect('software_list')
context = {'sw_asset': sw_asset}
return render(request, 'assetapp/software_confirm_delete.html', context)
@login_required
def software_export(request):
queryset = SoftwareAsset.objects.select_related('category')
category_id = request.GET.get('category')
if category_id:
queryset = queryset.filter(category_id=category_id)
status = request.GET.get('status')
if status:
queryset = queryset.filter(status=status)
wb = export_software_assets_to_excel(queryset)
output = BytesIO()
wb.save(output)
output.seek(0)
SoftwareChangeLog.objects.create(
asset_number='-',
action='export',
description=f'导出 {queryset.count()} 条软件资产记录',
operator=request.user,
)
today_str = date.today().strftime('%Y%m%d')
response = HttpResponse(
output.read(),
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
)
response['Content-Disposition'] = f'attachment; filename=软件资产_{today_str}.xlsx'
return response
@login_required
def software_import(request):
if request.method == 'POST':
form = AssetImportForm(request.POST, request.FILES)
if form.is_valid():
try:
wb = load_workbook(request.FILES['excel_file'])
ws = wb.active
category_map = {c.name: c for c in SoftwareCategory.objects.all()}
results = import_software_from_excel(ws, category_map, operator=request.user)
if results['success'] > 0:
messages.success(request, f"成功导入 {results['success']} 条软件资产")
if results['skipped'] > 0:
messages.warning(request, f"跳过 {results['skipped']} 条")
if results['errors']:
for error in results['errors'][:10]:
messages.error(request, error)
if len(results['errors']) > 10:
messages.error(request, f"...还有 {len(results['errors']) - 10} 条错误")
except Exception as e:
messages.error(request, f'导入失败: {str(e)}')
return redirect('software_list')
else:
form = AssetImportForm()
return render(request, 'assetapp/software_import.html', {'form': form})
@login_required
def download_software_template(request):
wb = generate_software_import_template()
output = BytesIO()
wb.save(output)
output.seek(0)
response = HttpResponse(
output.read(),
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
)
response['Content-Disposition'] = 'attachment; filename=软件资产导入模板.xlsx'
return response
@login_required
def software_change_log_list(request):
logs = SoftwareChangeLog.objects.select_related('operator', 'software_asset')
asset_number = request.GET.get('asset_number', '').strip()
if asset_number:
logs = logs.filter(asset_number__icontains=asset_number)
action = request.GET.get('action')
if action:
logs = logs.filter(action=action)
paginator = Paginator(logs, 30)
page_obj = paginator.get_page(request.GET.get('page', 1))
context = {
'page_obj': page_obj,
'asset_number': asset_number,
'current_action': action,
}
return render(request, 'assetapp/software_changelog.html', context)
# ─── 软件分类管理 ──────────────────────────────────
@login_required
def software_category_list(request):
categories = SoftwareCategory.objects.annotate(
sw_count=Count('software_assets')).order_by('name')
return render(request, 'assetapp/software_category_list.html', {'categories': categories})
@login_required
def software_category_create(request):
if request.method == 'POST':
form = SoftwareCategoryForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, f'软件分类 "{form.instance.name}" 创建成功')
return redirect('software_category_list')
else:
form = SoftwareCategoryForm()
return render(request, 'assetapp/software_category_form.html', {'form': form, 'action': 'create'})
@login_required
def software_category_update(request, pk):
category = get_object_or_404(SoftwareCategory, pk=pk)
if request.method == 'POST':
form = SoftwareCategoryForm(request.POST, instance=category)
if form.is_valid():
form.save()
messages.success(request, f'软件分类 "{category.name}" 已更新')
return redirect('software_category_list')
else:
form = SoftwareCategoryForm(instance=category)
return render(request, 'assetapp/software_category_form.html',
{'form': form, 'action': 'update', 'category': category})
@login_required
def software_category_delete(request, pk):
category = get_object_or_404(SoftwareCategory, pk=pk)
sw_count = category.software_assets.count()
if sw_count > 0:
messages.error(request, f'软件分类 "{category.name}" 下还有 {sw_count} 个软件资产,无法删除')
return redirect('software_category_list')
if request.method == 'POST':
category.delete()
messages.success(request, f'软件分类 "{category.name}" 已删除')
return redirect('software_category_list')
return render(request, 'assetapp/software_category_confirm_delete.html', {'category': category})
+9
View File
@@ -76,6 +76,15 @@ LOGIN_URL = '/login/'
LOGIN_REDIRECT_URL = '/' LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/login/' LOGOUT_REDIRECT_URL = '/login/'
# Password validation
AUTH_PASSWORD_VALIDATORS = [
{'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'},
{'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
'OPTIONS': {'min_length': 8}},
{'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'},
{'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'},
]
# Static files # Static files
STATIC_URL = '/static/' STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / 'static'] STATICFILES_DIRS = [BASE_DIR / 'static']
+6 -2
View File
@@ -37,14 +37,18 @@
{{ form.category }} {{ form.category }}
</div> </div>
<div class="row"> <div class="row">
<div class="col-md-6 mb-3"> <div class="col-md-4 mb-3">
<label class="form-label text-muted">{{ form.brand.label }}</label> <label class="form-label text-muted">{{ form.brand.label }}</label>
{{ form.brand }} {{ form.brand }}
</div> </div>
<div class="col-md-6 mb-3"> <div class="col-md-4 mb-3">
<label class="form-label text-muted">{{ form.model.label }}</label> <label class="form-label text-muted">{{ form.model.label }}</label>
{{ form.model }} {{ form.model }}
</div> </div>
<div class="col-md-4 mb-3">
<label class="form-label text-muted">{{ form.asset_value.label }}</label>
{{ form.asset_value }}
</div>
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label class="form-label text-muted">{{ form.serial_number.label }}</label> <label class="form-label text-muted">{{ form.serial_number.label }}</label>
+36
View File
@@ -6,6 +6,15 @@
<div class="d-flex justify-content-between align-items-center mb-4"> <div class="d-flex justify-content-between align-items-center mb-4">
<h4 class="mb-0"><i class="bi bi-list-ul me-2"></i>资产列表</h4> <h4 class="mb-0"><i class="bi bi-list-ul me-2"></i>资产列表</h4>
<div> <div>
<!-- 按资产编号导出 -->
<div class="btn-group me-2" role="group">
<input type="text" id="exportNumbers" class="form-control form-control-sm"
style="width: 220px;" placeholder="输入资产编号,逗号分隔"
aria-label="按资产编号导出">
<button type="button" id="exportByNumbersBtn" class="btn btn-outline-success btn-sm">
<i class="bi bi-file-earmark-spreadsheet me-1"></i>按编号导出
</button>
</div>
<a href="{% url 'asset_export' %}" class="btn btn-outline-success btn-sm me-2"> <a href="{% url 'asset_export' %}" class="btn btn-outline-success btn-sm me-2">
<i class="bi bi-download me-1"></i>导出Excel <i class="bi bi-download me-1"></i>导出Excel
</a> </a>
@@ -175,4 +184,31 @@
<div class="text-light opacity-75 small mt-2"> <div class="text-light opacity-75 small mt-2">
共 {{ page_obj.paginator.count }} 条记录,第 {{ page_obj.number }}/{{ page_obj.paginator.num_pages }} 页 共 {{ page_obj.paginator.count }} 条记录,第 {{ page_obj.number }}/{{ page_obj.paginator.num_pages }} 页
</div> </div>
<script>
(function () {
var input = document.getElementById('exportNumbers');
var btn = document.getElementById('exportByNumbersBtn');
var exportUrl = '{% url "asset_export" %}';
function doExport() {
var raw = (input.value || '').trim();
if (!raw) {
alert('请先输入资产编号,多个编号用逗号分隔');
input.focus();
return;
}
// 编号作为 query 参数传递,浏览器下载文件
window.location.href = exportUrl + '?asset_numbers=' + encodeURIComponent(raw);
}
btn.addEventListener('click', doExport);
input.addEventListener('keydown', function (e) {
if (e.key === 'Enter') {
e.preventDefault();
doExport();
}
});
})();
</script>
{% endblock %} {% endblock %}
+35 -10
View File
@@ -28,30 +28,55 @@
<i class="bi bi-speedometer2 me-1"></i>仪表盘 <i class="bi bi-speedometer2 me-1"></i>仪表盘
</a> </a>
</li> </li>
<li class="nav-item"> <li class="nav-item dropdown">
<a class="nav-link {% if 'assets' in request.path and 'import' not in request.path %}active{% endif %}" href="{% url 'asset_list' %}"> <a class="nav-link dropdown-toggle {% if 'asset' in request.resolver_match.url_name or 'software' in request.resolver_match.url_name and 'category' not in request.resolver_match.url_name %}active{% endif %}"
<i class="bi bi-list-ul me-1"></i>资产列表 href="#" role="button" data-bs-toggle="dropdown">
<i class="bi bi-boxes me-1"></i>资产管理
</a> </a>
<ul class="dropdown-menu dropdown-menu-dark">
<li><a class="dropdown-item" href="{% url 'asset_list' %}"><i class="bi bi-hdd-rack me-2"></i>硬件资产</a></li>
<li><a class="dropdown-item" href="{% url 'software_list' %}"><i class="bi bi-window-stack me-2"></i>软件资产</a></li>
</ul>
</li> </li>
<li class="nav-item"> <li class="nav-item dropdown">
<a class="nav-link {% if request.resolver_match.url_name == 'category_list' %}active{% endif %}" href="{% url 'category_list' %}"> <a class="nav-link dropdown-toggle {% if 'category' in request.resolver_match.url_name %}active{% endif %}"
href="#" role="button" data-bs-toggle="dropdown">
<i class="bi bi-tags me-1"></i>分类管理 <i class="bi bi-tags me-1"></i>分类管理
</a> </a>
<ul class="dropdown-menu dropdown-menu-dark">
<li><a class="dropdown-item" href="{% url 'category_list' %}"><i class="bi bi-hdd-rack me-2"></i>设备分类</a></li>
<li><a class="dropdown-item" href="{% url 'software_category_list' %}"><i class="bi bi-bookmarks me-2"></i>软件分类</a></li>
</ul>
</li> </li>
<li class="nav-item"> <li class="nav-item dropdown">
<a class="nav-link {% if request.resolver_match.url_name == 'change_log_list' %}active{% endif %}" href="{% url 'change_log_list' %}"> <a class="nav-link dropdown-toggle {% if 'changelog' in request.resolver_match.url_name %}active{% endif %}"
href="#" role="button" data-bs-toggle="dropdown">
<i class="bi bi-clock-history me-1"></i>变更记录 <i class="bi bi-clock-history me-1"></i>变更记录
</a> </a>
<ul class="dropdown-menu dropdown-menu-dark">
<li><a class="dropdown-item" href="{% url 'change_log_list' %}"><i class="bi bi-hdd-rack me-2"></i>硬件变更</a></li>
<li><a class="dropdown-item" href="{% url 'software_changelog' %}"><i class="bi bi-window-stack me-2"></i>软件变更</a></li>
</ul>
</li> </li>
{% if user.is_superuser %}
<li class="nav-item">
<a class="nav-link {% if request.resolver_match.url_name == 'user_list' %}active{% endif %}" href="{% url 'user_list' %}">
<i class="bi bi-people me-1"></i>用户管理
</a>
</li>
{% endif %}
<li class="nav-item dropdown"> <li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown"> <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
<i class="bi bi-file-earmark-spreadsheet me-1"></i>导入导出 <i class="bi bi-file-earmark-spreadsheet me-1"></i>导入导出
</a> </a>
<ul class="dropdown-menu dropdown-menu-dark"> <ul class="dropdown-menu dropdown-menu-dark">
<li><a class="dropdown-item" href="{% url 'asset_import' %}"><i class="bi bi-upload me-2"></i>导入Excel</a></li> <li><a class="dropdown-item" href="{% url 'asset_import' %}"><i class="bi bi-upload me-2"></i>导入硬件Excel</a></li>
<li><a class="dropdown-item" href="{% url 'asset_export' %}"><i class="bi bi-download me-2"></i>导出Excel</a></li> <li><a class="dropdown-item" href="{% url 'asset_export' %}"><i class="bi bi-download me-2"></i>导出硬件Excel</a></li>
<li><a class="dropdown-item" href="{% url 'download_template' %}"><i class="bi bi-file-earmark-arrow-down me-2"></i>硬件导入模板</a></li>
<li><hr class="dropdown-divider"></li> <li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item" href="{% url 'download_template' %}"><i class="bi bi-file-earmark-arrow-down me-2"></i>下载模板</a></li> <li><a class="dropdown-item" href="{% url 'software_import' %}"><i class="bi bi-upload me-2"></i>导入软件Excel</a></li>
<li><a class="dropdown-item" href="{% url 'software_export' %}"><i class="bi bi-download me-2"></i>导出软件Excel</a></li>
<li><a class="dropdown-item" href="{% url 'download_software_template' %}"><i class="bi bi-file-earmark-arrow-down me-2"></i>软件导入模板</a></li>
</ul> </ul>
</li> </li>
</ul> </ul>
+219 -52
View File
@@ -6,12 +6,18 @@
{% block content %} {% block content %}
<div class="d-flex justify-content-between align-items-center mb-4"> <div class="d-flex justify-content-between align-items-center mb-4">
<h4 class="mb-0"><i class="bi bi-speedometer2 me-2"></i>仪表盘</h4> <h4 class="mb-0"><i class="bi bi-speedometer2 me-2"></i>仪表盘</h4>
<a href="{% url 'asset_create' %}" class="btn btn-primary"> <div>
<i class="bi bi-plus-circle me-1"></i>新增资产 <a href="{% url 'software_create' %}" class="btn btn-outline-info me-2">
</a> <i class="bi bi-window-stack me-1"></i>新增软件资产
</a>
<a href="{% url 'asset_create' %}" class="btn btn-primary">
<i class="bi bi-plus-circle me-1"></i>新增资产
</a>
</div>
</div> </div>
<!-- 统计卡片 --> <!-- 硬件统计卡片 -->
<h6 class="text-muted mb-2"><i class="bi bi-hdd-rack me-1"></i>硬件资产</h6>
<div class="row g-3 mb-4"> <div class="row g-3 mb-4">
<div class="col-md-3"> <div class="col-md-3">
<div class="stat-card stat-total"> <div class="stat-card stat-total">
@@ -51,12 +57,53 @@
</div> </div>
</div> </div>
<!-- 软件资产统计卡片 -->
<h6 class="text-muted mb-2"><i class="bi bi-window-stack me-1"></i>软件资产</h6>
<div class="row g-3 mb-4">
<div class="col-md-3">
<div class="stat-card stat-total">
<div class="stat-icon"><i class="bi bi-window-stack"></i></div>
<div class="stat-info">
<div class="stat-value">{{ total_software }}</div>
<div class="stat-label">软件总数</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="stat-card stat-in-use">
<div class="stat-icon"><i class="bi bi-check-circle"></i></div>
<div class="stat-info">
<div class="stat-value">{{ software_status_data.in_use|default:0 }}</div>
<div class="stat-label">在用</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="stat-card stat-warning">
<div class="stat-icon"><i class="bi bi-exclamation-triangle"></i></div>
<div class="stat-info">
<div class="stat-value">{{ sw_expiring_soon }}</div>
<div class="stat-label">即将到期(30天)</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="stat-card stat-danger">
<div class="stat-icon"><i class="bi bi-shield-exclamation"></i></div>
<div class="stat-info">
<div class="stat-value">{{ sw_expired }}</div>
<div class="stat-label">已过期</div>
</div>
</div>
</div>
</div>
<div class="row g-3"> <div class="row g-3">
<!-- 分类统计 --> <!-- 分类统计 -->
<div class="col-md-6"> <div class="col-md-3">
<div class="card card-dark"> <div class="card card-dark h-100">
<div class="card-header"> <div class="card-header">
<i class="bi bi-pie-chart me-2"></i>分类统计 <i class="bi bi-pie-chart me-2"></i>硬件分类统计
</div> </div>
<div class="card-body"> <div class="card-body">
{% if category_stats %} {% if category_stats %}
@@ -64,7 +111,7 @@
<div class="d-flex justify-content-between align-items-center py-2 border-bottom border-secondary"> <div class="d-flex justify-content-between align-items-center py-2 border-bottom border-secondary">
<span class="text-light">{{ item.category__name }}</span> <span class="text-light">{{ item.category__name }}</span>
<div class="d-flex align-items-center"> <div class="d-flex align-items-center">
<div class="progress me-2" style="width: 120px; height: 8px;"> <div class="progress me-2" style="width: 80px; height: 8px;">
{% widthratio item.count total_assets 100 as pct %} {% widthratio item.count total_assets 100 as pct %}
<div class="progress-bar bg-primary" style="width: {{ pct }}%"></div> <div class="progress-bar bg-primary" style="width: {{ pct }}%"></div>
</div> </div>
@@ -79,16 +126,43 @@
</div> </div>
</div> </div>
<!-- 软件分类统计 -->
<div class="col-md-3">
<div class="card card-dark h-100">
<div class="card-header">
<i class="bi bi-bookmarks me-2"></i>软件分类统计
</div>
<div class="card-body">
{% if software_category_stats %}
{% for item in software_category_stats %}
<div class="d-flex justify-content-between align-items-center py-2 border-bottom border-secondary">
<span class="text-light">{{ item.category__name }}</span>
<div class="d-flex align-items-center">
<div class="progress me-2" style="width: 80px; height: 8px;">
{% widthratio item.count total_software 100 as pct %}
<div class="progress-bar bg-info" style="width: {{ pct }}%"></div>
</div>
<span class="badge bg-info">{{ item.count }}</span>
</div>
</div>
{% endfor %}
{% else %}
<p class="text-muted text-center my-4">暂无数据</p>
{% endif %}
</div>
</div>
</div>
<!-- 状态分布 --> <!-- 状态分布 -->
<div class="col-md-6"> <div class="col-md-3">
<div class="card card-dark"> <div class="card card-dark h-100">
<div class="card-header"> <div class="card-header">
<i class="bi bi-bar-chart me-2"></i>状态分布 <i class="bi bi-bar-chart me-2"></i>状态分布
</div> </div>
<div class="card-body"> <div class="card-body">
{% for key, label in status_map.items %} {% for key, label in status_map.items %}
<div class="d-flex justify-content-between align-items-center py-2 border-bottom border-secondary"> <div class="d-flex justify-content-between align-items-center py-2 border-bottom border-secondary">
<span class="text-light">{{ label }}</span> <span class="text-light"><i class="bi bi-hdd-rack me-1 text-muted small"></i>{{ label }}</span>
<span class="badge <span class="badge
{% if key == 'in_use' %}bg-success {% if key == 'in_use' %}bg-success
{% elif key == 'idle' %}bg-warning text-dark {% elif key == 'idle' %}bg-warning text-dark
@@ -98,53 +172,146 @@
</span> </span>
</div> </div>
{% endfor %} {% endfor %}
{% for key, label in software_status_map.items %}
<div class="d-flex justify-content-between align-items-center py-2 border-bottom border-secondary">
<span class="text-light"><i class="bi bi-window-stack me-1 text-muted small"></i>{{ label }}</span>
<span class="badge
{% if key == 'in_use' %}bg-success
{% elif key == 'idle' %}bg-warning text-dark
{% elif key == 'expired' %}bg-danger
{% else %}bg-secondary{% endif %}">
{{ software_status_data|get_item:key|default:0 }}
</span>
</div>
{% endfor %}
</div>
</div>
</div>
<!-- 软件许可类型分布 -->
<div class="col-md-3">
<div class="card card-dark h-100">
<div class="card-header">
<i class="bi bi-key me-2"></i>许可类型分布
</div>
<div class="card-body">
<div class="d-flex justify-content-between align-items-center py-2 border-bottom border-secondary">
<span class="text-light">永久授权</span>
<span class="badge bg-primary">{{ software_license_data.permanent|default:0 }}</span>
</div>
<div class="d-flex justify-content-between align-items-center py-2 border-bottom border-secondary">
<span class="text-light">订阅</span>
<span class="badge bg-info">{{ software_license_data.subscription|default:0 }}</span>
</div>
<div class="d-flex justify-content-between align-items-center py-2 border-bottom border-secondary">
<span class="text-light">开源免费</span>
<span class="badge bg-secondary">{{ software_license_data.open_source|default:0 }}</span>
</div>
<div class="d-flex justify-content-between align-items-center py-2 border-bottom border-secondary">
<span class="text-light">按需付费</span>
<span class="badge bg-warning text-dark">{{ software_license_data.pay_as_you_go|default:0 }}</span>
</div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<!-- 最近变更 --> <!-- 最近变更(硬件+软件合并展示) -->
<div class="card card-dark mt-3"> <div class="row g-3 mt-0">
<div class="card-header d-flex justify-content-between align-items-center"> <div class="col-lg-6">
<span><i class="bi bi-clock-history me-2"></i>最近变更</span> <div class="card card-dark h-100">
<a href="{% url 'change_log_list' %}" class="btn btn-sm btn-outline-light">查看全部</a> <div class="card-header d-flex justify-content-between align-items-center">
<span><i class="bi bi-hdd-rack me-2"></i>硬件最近变更</span>
<a href="{% url 'change_log_list' %}" class="btn btn-sm btn-outline-light">查看全部</a>
</div>
<div class="card-body p-0">
<div class="table-responsive">
<table class="table table-dark table-hover mb-0">
<thead>
<tr>
<th>时间</th>
<th>资产编号</th>
<th>操作</th>
<th>描述</th>
<th>操作人</th>
</tr>
</thead>
<tbody>
{% for log in recent_changes %}
<tr>
<td>{{ log.created_at|date:"m-d H:i" }}</td>
<td><a href="{% url 'asset_list' %}?search={{ log.asset_number }}" class="text-info">{{ log.asset_number }}</a></td>
<td>
<span class="badge
{% if log.action == 'create' %}bg-success
{% elif log.action == 'update' %}bg-primary
{% elif log.action == 'delete' %}bg-danger
{% elif log.action == 'import' %}bg-info
{% elif log.action == 'export' %}bg-secondary
{% else %}bg-warning{% endif %}">
{{ log.get_action_display }}
</span>
</td>
<td>{{ log.description|default:"-" }}</td>
<td>{{ log.operator|default:"-" }}</td>
</tr>
{% empty %}
<tr><td colspan="5" class="text-center text-light opacity-75 py-3">暂无变更记录</td></tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
</div> </div>
<div class="card-body p-0"> <div class="col-lg-6">
<div class="table-responsive"> <div class="card card-dark h-100">
<table class="table table-dark table-hover mb-0"> <div class="card-header d-flex justify-content-between align-items-center">
<thead> <span><i class="bi bi-window-stack me-2"></i>软件最近变更</span>
<tr> <a href="{% url 'software_changelog' %}" class="btn btn-sm btn-outline-light">查看全部</a>
<th>时间</th> </div>
<th>资产编号</th> <div class="card-body p-0">
<th>操作</th> <div class="table-responsive">
<th>描述</th> <table class="table table-dark table-hover mb-0">
<th>操作人</th> <thead>
</tr> <tr>
</thead> <th>时间</th>
<tbody> <th>资产编号</th>
{% for log in recent_changes %} <th>操作</th>
<tr> <th>描述</th>
<td>{{ log.created_at|date:"m-d H:i" }}</td> <th>操作人</th>
<td><a href="{% url 'asset_list' %}?search={{ log.asset_number }}" class="text-info">{{ log.asset_number }}</a></td> </tr>
<td> </thead>
<span class="badge <tbody>
{% if log.action == 'create' %}bg-success {% for log in recent_software_changes %}
{% elif log.action == 'update' %}bg-primary <tr>
{% elif log.action == 'delete' %}bg-danger <td>{{ log.created_at|date:"m-d H:i" }}</td>
{% elif log.action == 'import' %}bg-info <td>
{% elif log.action == 'export' %}bg-secondary {% if log.software_asset %}
{% else %}bg-warning{% endif %}"> <a href="{% url 'software_detail' log.software_asset.pk %}" class="text-info">{{ log.asset_number }}</a>
{{ log.get_action_display }} {% else %}{{ log.asset_number }}{% endif %}
</span> </td>
</td> <td>
<td>{{ log.description|default:"-" }}</td> <span class="badge
<td>{{ log.operator|default:"-" }}</td> {% if log.action == 'create' %}bg-success
</tr> {% elif log.action == 'update' %}bg-primary
{% empty %} {% elif log.action == 'delete' %}bg-danger
<tr><td colspan="5" class="text-center text-light opacity-75 py-3">暂无变更记录</td></tr> {% elif log.action == 'import' %}bg-info
{% endfor %} {% elif log.action == 'export' %}bg-secondary
</tbody> {% else %}bg-warning{% endif %}">
</table> {{ log.get_action_display }}
</span>
</td>
<td>{{ log.description|default:"-" }}</td>
<td>{{ log.operator|default:"-" }}</td>
</tr>
{% empty %}
<tr><td colspan="5" class="text-center text-light opacity-75 py-3">暂无变更记录</td></tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div> </div>
</div> </div>
</div> </div>
@@ -0,0 +1,32 @@
{% extends "assetapp/base.html" %}
{% block title %}删除软件分类{% endblock %}
{% block content %}
<div class="d-flex align-items-center mb-4">
<a href="{% url 'software_category_list' %}" class="btn btn-outline-secondary btn-sm me-3">
<i class="bi bi-arrow-left"></i> 返回
</a>
<h4 class="mb-0"><i class="bi bi-trash me-2"></i>删除软件分类</h4>
</div>
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card card-dark border-danger">
<div class="card-body">
<div class="alert alert-danger">
<i class="bi bi-exclamation-triangle me-2"></i>
确定要删除软件分类 <strong>{{ category.name }}</strong> 吗?
</div>
<form method="post">
{% csrf_token %}
<button type="submit" class="btn btn-danger">
<i class="bi bi-trash me-1"></i>确认删除
</button>
<a href="{% url 'software_category_list' %}" class="btn btn-outline-secondary ms-2">取消</a>
</form>
</div>
</div>
</div>
</div>
{% endblock %}
@@ -0,0 +1,40 @@
{% extends "assetapp/base.html" %}
{% block title %}{% if action == 'create' %}新增软件分类{% else %}编辑软件分类{% endif %}{% endblock %}
{% block content %}
<div class="d-flex align-items-center mb-4">
<a href="{% url 'software_category_list' %}" class="btn btn-outline-secondary btn-sm me-3">
<i class="bi bi-arrow-left"></i> 返回
</a>
<h4 class="mb-0">
<i class="bi bi-{% if action == 'create' %}plus-circle{% else %}pencil{% endif %} me-2"></i>
{% if action == 'create' %}新增软件分类{% else %}编辑软件分类 - {{ category.name }}{% endif %}
</h4>
</div>
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card card-dark">
<div class="card-body">
<form method="post">
{% csrf_token %}
<div class="mb-3">
<label class="form-label text-muted">分类名称 <span class="text-danger">*</span></label>
{{ form.name }}
{% if form.name.errors %}<div class="text-danger small mt-1">{{ form.name.errors.0 }}</div>{% endif %}
</div>
<div class="mb-3">
<label class="form-label text-muted">描述</label>
{{ form.description }}
</div>
<button type="submit" class="btn btn-primary">
<i class="bi bi-check-circle me-1"></i>{% if action == 'create' %}创建{% else %}保存{% endif %}
</button>
<a href="{% url 'software_category_list' %}" class="btn btn-outline-secondary ms-2">取消</a>
</form>
</div>
</div>
</div>
</div>
{% endblock %}
@@ -0,0 +1,52 @@
{% extends "assetapp/base.html" %}
{% block title %}软件分类管理{% endblock %}
{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
<h4 class="mb-0"><i class="bi bi-bookmarks me-2"></i>软件分类管理</h4>
<a href="{% url 'software_category_create' %}" class="btn btn-primary btn-sm">
<i class="bi bi-plus-circle me-1"></i>新增软件分类
</a>
</div>
<div class="card card-dark">
<div class="card-body p-0">
<div class="table-responsive">
<table class="table table-dark table-hover mb-0">
<thead>
<tr>
<th>ID</th>
<th>分类名称</th>
<th>描述</th>
<th>软件资产数量</th>
<th>创建时间</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for category in categories %}
<tr>
<td>{{ category.id }}</td>
<td><strong>{{ category.name }}</strong></td>
<td>{{ category.description|default:"-" }}</td>
<td><span class="badge bg-primary">{{ category.sw_count }}</span></td>
<td>{{ category.created_at|date:"Y-m-d H:i" }}</td>
<td>
<a href="{% url 'software_category_update' category.pk %}" class="btn btn-outline-warning btn-xs" title="编辑">
<i class="bi bi-pencil"></i>
</a>
<a href="{% url 'software_category_delete' category.pk %}" class="btn btn-outline-danger btn-xs" title="删除">
<i class="bi bi-trash"></i>
</a>
</td>
</tr>
{% empty %}
<tr><td colspan="6" class="text-center text-muted py-4">暂无软件分类</td></tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
{% endblock %}
+112
View File
@@ -0,0 +1,112 @@
{% extends "assetapp/base.html" %}
{% block title %}软件资产变更记录{% endblock %}
{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
<h4 class="mb-0"><i class="bi bi-clock-history me-2"></i>软件资产变更记录</h4>
</div>
<div class="card card-dark mb-3">
<div class="card-body py-3">
<form method="get" class="row g-2 align-items-center">
<div class="col-md-4">
<div class="input-group input-group-sm">
<span class="input-group-text"><i class="bi bi-search"></i></span>
<input type="text" name="asset_number" value="{{ asset_number }}" class="form-control"
placeholder="按资产编号搜索">
</div>
</div>
<div class="col-md-3">
<select name="action" class="form-select form-select-sm">
<option value="">全部操作</option>
<option value="create" {% if current_action == 'create' %}selected{% endif %}>创建</option>
<option value="update" {% if current_action == 'update' %}selected{% endif %}>更新</option>
<option value="delete" {% if current_action == 'delete' %}selected{% endif %}>删除</option>
<option value="import" {% if current_action == 'import' %}selected{% endif %}>导入</option>
<option value="export" {% if current_action == 'export' %}selected{% endif %}>导出</option>
<option value="status_change" {% if current_action == 'status_change' %}selected{% endif %}>状态变更</option>
</select>
</div>
<div class="col-md-2">
<button type="submit" class="btn btn-primary btn-sm w-100">
<i class="bi bi-funnel me-1"></i>筛选
</button>
</div>
</form>
</div>
</div>
<div class="card card-dark">
<div class="card-body p-0">
<div class="table-responsive">
<table class="table table-dark table-hover mb-0">
<thead>
<tr>
<th>时间</th>
<th>资产编号</th>
<th>操作</th>
<th>变更字段</th>
<th>旧值</th>
<th>新值</th>
<th>描述</th>
<th>操作人</th>
</tr>
</thead>
<tbody>
{% for log in page_obj %}
<tr>
<td>{{ log.created_at|date:"m-d H:i" }}</td>
<td>
{% if log.software_asset %}
<a href="{% url 'software_detail' log.software_asset.pk %}" class="text-info">{{ log.asset_number }}</a>
{% else %}
{{ log.asset_number }}
{% endif %}
</td>
<td>
<span class="badge
{% if log.action == 'create' %}bg-success
{% elif log.action == 'update' %}bg-primary
{% elif log.action == 'delete' %}bg-danger
{% elif log.action == 'import' %}bg-info
{% elif log.action == 'export' %}bg-secondary
{% else %}bg-warning{% endif %}">
{{ log.get_action_display }}
</span>
</td>
<td>{{ log.field_name|default:"-" }}</td>
<td class="text-wrap" style="max-width:150px;">{{ log.old_value|default:"-"|truncatechars:30 }}</td>
<td class="text-wrap" style="max-width:150px;">{{ log.new_value|default:"-"|truncatechars:30 }}</td>
<td>{{ log.description|default:"-" }}</td>
<td>{{ log.operator|default:"-" }}</td>
</tr>
{% empty %}
<tr><td colspan="8" class="text-center text-muted py-4">暂无变更记录</td></tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
{% if page_obj.paginator.num_pages > 1 %}
<nav class="mt-3">
<ul class="pagination pagination-sm justify-content-center">
{% if page_obj.has_previous %}
<li class="page-item">
<a class="page-link" href="?page={{ page_obj.previous_page_number }}&asset_number={{ asset_number }}&action={{ current_action }}">上一页</a>
</li>
{% endif %}
<li class="page-item active">
<span class="page-link">{{ page_obj.number }} / {{ page_obj.paginator.num_pages }}</span>
</li>
{% if page_obj.has_next %}
<li class="page-item">
<a class="page-link" href="?page={{ page_obj.next_page_number }}&asset_number={{ asset_number }}&action={{ current_action }}">下一页</a>
</li>
{% endif %}
</ul>
</nav>
{% endif %}
{% endblock %}
@@ -0,0 +1,33 @@
{% extends "assetapp/base.html" %}
{% block title %}删除软件资产{% endblock %}
{% block content %}
<div class="d-flex align-items-center mb-4">
<a href="{% url 'software_list' %}" class="btn btn-outline-secondary btn-sm me-3">
<i class="bi bi-arrow-left"></i> 返回
</a>
<h4 class="mb-0"><i class="bi bi-trash me-2"></i>删除软件资产</h4>
</div>
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card card-dark border-danger">
<div class="card-body">
<div class="alert alert-danger">
<i class="bi bi-exclamation-triangle me-2"></i>
确定要删除软件资产 <strong>{{ sw_asset.asset_number }} - {{ sw_asset.name }}</strong> 吗?
此操作不可恢复!
</div>
<form method="post">
{% csrf_token %}
<button type="submit" class="btn btn-danger">
<i class="bi bi-trash me-1"></i>确认删除
</button>
<a href="{% url 'software_list' %}" class="btn btn-outline-secondary ms-2">取消</a>
</form>
</div>
</div>
</div>
</div>
{% endblock %}
+137
View File
@@ -0,0 +1,137 @@
{% extends "assetapp/base.html" %}
{% load asset_tags %}
{% block title %}{{ sw_asset.name }} - 软件资产详情{% endblock %}
{% block content %}
<div class="d-flex align-items-center mb-4">
<a href="{% url 'software_list' %}" class="btn btn-outline-secondary btn-sm me-3">
<i class="bi bi-arrow-left"></i> 返回
</a>
<h4 class="mb-0"><i class="bi bi-window-stack me-2"></i>{{ sw_asset.asset_number }} - {{ sw_asset.name }}</h4>
<div class="ms-auto">
<a href="{% url 'software_update' sw_asset.pk %}" class="btn btn-warning btn-sm me-2">
<i class="bi bi-pencil me-1"></i>编辑
</a>
<a href="{% url 'software_delete' sw_asset.pk %}" class="btn btn-outline-danger btn-sm">
<i class="bi bi-trash me-1"></i>删除
</a>
</div>
</div>
<div class="row g-3">
<div class="col-lg-8">
<div class="card card-dark mb-3">
<div class="card-header"><i class="bi bi-info-circle me-2"></i>基本信息</div>
<div class="card-body">
<div class="row">
<div class="col-md-6 mb-2"><span class="text-muted">资产编号:</span>{{ sw_asset.asset_number }}</div>
<div class="col-md-6 mb-2"><span class="text-muted">软件名称:</span>{{ sw_asset.name }}</div>
<div class="col-md-6 mb-2"><span class="text-muted">软件分类:</span>{{ sw_asset.category.name }}</div>
<div class="col-md-6 mb-2"><span class="text-muted">供应商:</span>{{ sw_asset.vendor|default:"-" }}</div>
<div class="col-md-6 mb-2"><span class="text-muted">版本:</span>{{ sw_asset.version|default:"-" }}</div>
<div class="col-md-6 mb-2"><span class="text-muted">账号:</span>{{ sw_asset.account|default:"-" }}</div>
</div>
</div>
</div>
<div class="card card-dark mb-3">
<div class="card-header"><i class="bi bi-key me-2"></i>许可信息</div>
<div class="card-body">
<div class="row">
<div class="col-md-6 mb-2">
<span class="text-muted">许可类型:</span>
{{ license_type_map|get_item:sw_asset.license_type }}
</div>
<div class="col-md-6 mb-2"><span class="text-muted">授权数量:</span>{{ sw_asset.seats|default:"-" }}</div>
<div class="col-12 mb-2"><span class="text-muted">许可密钥/激活码:</span><code>{{ sw_asset.license_key|default:"-" }}</code></div>
</div>
</div>
</div>
<div class="card card-dark mb-3">
<div class="card-header"><i class="bi bi-cash-coin me-2"></i>费用与有效期</div>
<div class="card-body">
<div class="row">
<div class="col-md-3 mb-2"><span class="text-muted">费用:</span>{{ sw_asset.cost|default:"-" }}{% if sw_asset.cost %} 元{% endif %}</div>
<div class="col-md-3 mb-2"><span class="text-muted">启用日期:</span>{{ sw_asset.start_date|default:"-" }}</div>
<div class="col-md-3 mb-2">
<span class="text-muted">到期日期:</span>{{ sw_asset.expire_date|default:"-" }}
{% if sw_asset.is_expired %}<span class="badge bg-danger ms-1">已到期</span>
{% elif sw_asset.is_expiring_soon %}<span class="badge bg-warning text-dark ms-1">即将到期</span>{% endif %}
</div>
<div class="col-md-3 mb-2">
<span class="text-muted">状态:</span>
<span class="badge
{% if sw_asset.status == 'in_use' %}bg-success
{% elif sw_asset.status == 'idle' %}bg-warning text-dark
{% elif sw_asset.status == 'expired' %}bg-danger
{% else %}bg-secondary{% endif %}">
{{ status_map|get_item:sw_asset.status }}
</span>
</div>
</div>
</div>
</div>
<div class="card card-dark mb-3">
<div class="card-header"><i class="bi bi-person-badge me-2"></i>管理信息</div>
<div class="card-body">
<div class="row">
<div class="col-md-6 mb-2"><span class="text-muted">负责人:</span>{{ sw_asset.responsible_person|default:"-" }}</div>
<div class="col-md-6 mb-2"><span class="text-muted">使用部门:</span>{{ sw_asset.department|default:"-" }}</div>
<div class="col-12 mb-2"><span class="text-muted">备注:</span>{{ sw_asset.remark|default:"-" }}</div>
</div>
</div>
</div>
</div>
<div class="col-lg-4">
<div class="card card-dark">
<div class="card-header"><i class="bi bi-clock-history me-2"></i>变更记录</div>
<div class="card-body p-0">
<div class="table-responsive" style="max-height: 500px;">
<table class="table table-dark table-hover mb-0">
<tbody>
{% for log in change_logs %}
<tr>
<td class="py-2">
<div class="small text-muted">{{ log.created_at|date:"Y-m-d H:i" }}</div>
<span class="badge
{% if log.action == 'create' %}bg-success
{% elif log.action == 'update' %}bg-primary
{% elif log.action == 'delete' %}bg-danger
{% elif log.action == 'import' %}bg-info
{% else %}bg-secondary{% endif %}">
{{ log.get_action_display }}
</span>
{% if log.field_name %}
<span class="small">{{ log.field_name }}: {{ log.old_value }} → {{ log.new_value }}</span>
{% endif %}
{% if log.description %}
<div class="small text-muted">{{ log.description }}</div>
{% endif %}
<div class="small text-muted">操作人: {{ log.operator|default:"-" }}</div>
</td>
</tr>
{% empty %}
<tr><td class="text-center text-muted py-4">暂无变更记录</td></tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
<div class="card card-dark mt-3">
<div class="card-body">
<div class="small text-muted">
<div><i class="bi bi-person me-1"></i>创建人: {{ sw_asset.created_by|default:"-" }}</div>
<div><i class="bi bi-calendar-plus me-1"></i>创建时间: {{ sw_asset.created_at|date:"Y-m-d H:i" }}</div>
<div><i class="bi bi-arrow-repeat me-1"></i>更新时间: {{ sw_asset.updated_at|date:"Y-m-d H:i" }}</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
+116
View File
@@ -0,0 +1,116 @@
{% extends "assetapp/base.html" %}
{% block title %}{% if action == 'create' %}新增软件资产{% else %}编辑软件资产{% endif %}{% endblock %}
{% block content %}
<div class="d-flex align-items-center mb-4">
<a href="{% if action == 'update' %}{% url 'software_detail' sw_asset.pk %}{% else %}{% url 'software_list' %}{% endif %}"
class="btn btn-outline-secondary btn-sm me-3">
<i class="bi bi-arrow-left"></i> 返回
</a>
<h4 class="mb-0">
<i class="bi bi-{% if action == 'create' %}plus-circle{% else %}pencil{% endif %} me-2"></i>
{% if action == 'create' %}新增软件资产{% else %}编辑软件资产 - {{ sw_asset.name }}{% endif %}
</h4>
</div>
<div class="row justify-content-center">
<div class="col-lg-8">
<div class="card card-dark">
<div class="card-body">
<form method="post">
{% csrf_token %}
<h6 class="text-info mb-3"><i class="bi bi-info-circle me-1"></i>基本信息</h6>
<div class="row">
<div class="col-md-4 mb-3">
<label class="form-label text-muted">资产编号 <span class="text-danger">*</span></label>
{{ form.asset_number }}
{% if form.asset_number.errors %}<div class="text-danger small mt-1">{{ form.asset_number.errors.0 }}</div>{% endif %}
</div>
<div class="col-md-4 mb-3">
<label class="form-label text-muted">软件名称 <span class="text-danger">*</span></label>
{{ form.name }}
{% if form.name.errors %}<div class="text-danger small mt-1">{{ form.name.errors.0 }}</div>{% endif %}
</div>
<div class="col-md-4 mb-3">
<label class="form-label text-muted">软件分类</label>
{{ form.category }}
</div>
<div class="col-md-6 mb-3">
<label class="form-label text-muted">供应商</label>
{{ form.vendor }}
</div>
<div class="col-md-6 mb-3">
<label class="form-label text-muted">版本</label>
{{ form.version }}
</div>
</div>
<h6 class="text-info mb-3 mt-4"><i class="bi bi-key me-1"></i>许可信息</h6>
<div class="row">
<div class="col-md-3 mb-3">
<label class="form-label text-muted">许可类型</label>
{{ form.license_type }}
</div>
<div class="col-md-3 mb-3">
<label class="form-label text-muted">授权数量</label>
{{ form.seats }}
</div>
<div class="col-md-6 mb-3">
<label class="form-label text-muted">账号</label>
{{ form.account }}
</div>
<div class="col-12 mb-3">
<label class="form-label text-muted">许可密钥/激活码</label>
{{ form.license_key }}
</div>
</div>
<h6 class="text-info mb-3 mt-4"><i class="bi bi-cash-coin me-1"></i>费用与有效期</h6>
<div class="row">
<div class="col-md-4 mb-3">
<label class="form-label text-muted">费用(元)</label>
{{ form.cost }}
</div>
<div class="col-md-4 mb-3">
<label class="form-label text-muted">启用日期</label>
{{ form.start_date }}
</div>
<div class="col-md-4 mb-3">
<label class="form-label text-muted">到期日期</label>
{{ form.expire_date }}
</div>
</div>
<h6 class="text-info mb-3 mt-4"><i class="bi bi-person-badge me-1"></i>管理信息</h6>
<div class="row">
<div class="col-md-4 mb-3">
<label class="form-label text-muted">负责人</label>
{{ form.responsible_person }}
</div>
<div class="col-md-4 mb-3">
<label class="form-label text-muted">使用部门</label>
{{ form.department }}
</div>
<div class="col-md-4 mb-3">
<label class="form-label text-muted">状态</label>
{{ form.status }}
</div>
<div class="col-12 mb-3">
<label class="form-label text-muted">备注</label>
{{ form.remark }}
</div>
</div>
<button type="submit" class="btn btn-primary">
<i class="bi bi-check-circle me-1"></i>{% if action == 'create' %}创建{% else %}保存{% endif %}
</button>
<a href="{% if action == 'update' %}{% url 'software_detail' sw_asset.pk %}{% else %}{% url 'software_list' %}{% endif %}"
class="btn btn-outline-secondary ms-2">取消</a>
</form>
</div>
</div>
</div>
</div>
{% endblock %}
+71
View File
@@ -0,0 +1,71 @@
{% extends "assetapp/base.html" %}
{% block title %}导入软件资产{% endblock %}
{% block content %}
<div class="d-flex align-items-center mb-4">
<a href="{% url 'software_list' %}" class="btn btn-outline-secondary btn-sm me-3">
<i class="bi bi-arrow-left"></i> 返回
</a>
<h4 class="mb-0"><i class="bi bi-upload me-2"></i>导入软件资产</h4>
</div>
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card card-dark">
<div class="card-header"><i class="bi bi-file-earmark-spreadsheet me-2"></i>上传文件</div>
<div class="card-body">
<div class="alert alert-info">
<i class="bi bi-info-circle me-2"></i>
<strong>使用说明:</strong>
<ol class="mb-0 mt-2">
<li>先 <a href="{% url 'download_software_template' %}" class="text-info">下载软件资产导入模板</a></li>
<li>按模板格式填写软件资产数据</li>
<li>上传填写好的Excel文件(.xlsx)</li>
<li>提供ID列且该ID已存在时更新原记录,否则创建新记录</li>
<li>软件分类不存在时会自动创建</li>
</ol>
</div>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="mb-3">
<label class="form-label">选择Excel文件</label>
<div class="file-upload-wrapper">
<input type="file" name="excel_file" id="id_excel_file" accept=".xlsx,.xls" class="d-none" onchange="updateFileName(this)">
<button type="button" class="btn btn-outline-info" onclick="document.getElementById('id_excel_file').click()">
<i class="bi bi-folder2-open me-1"></i>浏览文件
</button>
<span id="file-name" class="ms-3 file-name-text">未选择文件</span>
</div>
{% if form.excel_file.errors %}
<div class="text-danger small mt-1">{{ form.excel_file.errors.0 }}</div>
{% endif %}
</div>
<div class="d-flex">
<button type="submit" class="btn btn-primary me-2">
<i class="bi bi-upload me-1"></i>开始导入
</button>
<a href="{% url 'download_software_template' %}" class="btn btn-outline-info">
<i class="bi bi-file-earmark-arrow-down me-1"></i>下载模板
</a>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
function updateFileName(input) {
var nameSpan = document.getElementById('file-name');
if (input.files && input.files.length > 0) {
nameSpan.textContent = input.files[0].name;
nameSpan.style.color = '#4A9EFF';
} else {
nameSpan.textContent = '未选择文件';
nameSpan.style.color = '#8b949e';
}
}
</script>
{% endblock %}
+166
View File
@@ -0,0 +1,166 @@
{% extends "assetapp/base.html" %}
{% load asset_tags %}
{% block title %}软件资产{% endblock %}
{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
<h4 class="mb-0"><i class="bi bi-window-stack me-2"></i>软件资产</h4>
<div>
<a href="{% url 'software_import' %}" class="btn btn-outline-info btn-sm me-2">
<i class="bi bi-upload me-1"></i>导入
</a>
<a href="{% url 'software_export' %}{{ query_string|default:'' }}" class="btn btn-outline-info btn-sm me-2">
<i class="bi bi-download me-1"></i>导出
</a>
<a href="{% url 'software_create' %}" class="btn btn-primary btn-sm">
<i class="bi bi-plus-circle me-1"></i>新增软件资产
</a>
</div>
</div>
<!-- 搜索与筛选 -->
<div class="card card-dark mb-3">
<div class="card-body py-3">
<form method="get" class="row g-2 align-items-center">
<div class="col-md-4">
<div class="input-group input-group-sm">
<span class="input-group-text"><i class="bi bi-search"></i></span>
<input type="text" name="search" value="{{ search }}" class="form-control"
placeholder="搜索编号 / 名称 / 供应商 / 版本 / 账号 / 负责人">
</div>
</div>
<div class="col-md-2">
<select name="category" class="form-select form-select-sm">
<option value="">全部分类</option>
{% for c in categories %}
<option value="{{ c.id }}" {% if current_category == c.id|stringformat:"s" %}selected{% endif %}>{{ c.name }}</option>
{% endfor %}
</select>
</div>
<div class="col-md-2">
<select name="status" class="form-select form-select-sm">
<option value="">全部状态</option>
{% for key, label in status_map.items %}
<option value="{{ key }}" {% if current_status == key %}selected{% endif %}>{{ label }}</option>
{% endfor %}
</select>
</div>
<div class="col-md-2">
<select name="license_type" class="form-select form-select-sm">
<option value="">全部许可类型</option>
{% for key, label in license_type_map.items %}
<option value="{{ key }}" {% if current_license_type == key %}selected{% endif %}>{{ label }}</option>
{% endfor %}
</select>
</div>
<div class="col-md-2">
<button type="submit" class="btn btn-primary btn-sm w-100">
<i class="bi bi-funnel me-1"></i>筛选
</button>
</div>
</form>
</div>
</div>
<div class="card card-dark">
<div class="card-body p-0">
<div class="table-responsive">
<table class="table table-dark table-hover mb-0 align-middle">
<thead>
<tr>
<th><a href="?sort={% if sort == 'id' %}-{% else %}id{% endif %}&search={{ search }}">ID</a></th>
<th><a href="?sort={% if sort == 'asset_number' %}-asset_number{% else %}asset_number{% endif %}&search={{ search }}">资产编号</a></th>
<th><a href="?sort={% if sort == 'name' %}-name{% else %}name{% endif %}&search={{ search }}">软件名称</a></th>
<th>软件分类</th>
<th>供应商</th>
<th>版本</th>
<th>许可类型</th>
<th>授权数量</th>
<th>账号</th>
<th>负责人</th>
<th>使用部门</th>
<th><a href="?sort={% if sort == 'expire_date' %}-expire_date{% else %}expire_date{% endif %}&search={{ search }}">到期日期</a></th>
<th>状态</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for sw in page_obj %}
<tr>
<td>{{ sw.id }}</td>
<td><strong>{{ sw.asset_number }}</strong></td>
<td>
<a href="{% url 'software_detail' sw.pk %}" class="text-info text-decoration-none">{{ sw.name }}</a>
</td>
<td>{{ sw.category.name }}</td>
<td>{{ sw.vendor|default:"-" }}</td>
<td>{{ sw.version|default:"-" }}</td>
<td>
<span class="badge
{% if sw.license_type == 'permanent' %}bg-primary
{% elif sw.license_type == 'subscription' %}bg-info
{% elif sw.license_type == 'open_source' %}bg-secondary
{% else %}bg-warning text-dark{% endif %}">
{{ license_type_map|get_item:sw.license_type }}
</span>
</td>
<td>{{ sw.seats|default:"-" }}</td>
<td>{{ sw.account|default:"-" }}</td>
<td>{{ sw.responsible_person|default:"-" }}</td>
<td>{{ sw.department|default:"-" }}</td>
<td>
{{ sw.expire_date|default:"-" }}
{% if sw.is_expired %}<span class="badge bg-danger ms-1">已到期</span>
{% elif sw.is_expiring_soon %}<span class="badge bg-warning text-dark ms-1">即将到期</span>{% endif %}
</td>
<td>
<span class="badge
{% if sw.status == 'in_use' %}bg-success
{% elif sw.status == 'idle' %}bg-warning text-dark
{% elif sw.status == 'expired' %}bg-danger
{% else %}bg-secondary{% endif %}">
{{ status_map|get_item:sw.status }}
</span>
</td>
<td class="text-nowrap">
<a href="{% url 'software_detail' sw.pk %}" class="btn btn-outline-info btn-xs" title="详情">
<i class="bi bi-eye"></i>
</a>
<a href="{% url 'software_update' sw.pk %}" class="btn btn-outline-warning btn-xs" title="编辑">
<i class="bi bi-pencil"></i>
</a>
<a href="{% url 'software_delete' sw.pk %}" class="btn btn-outline-danger btn-xs" title="删除">
<i class="bi bi-trash"></i>
</a>
</td>
</tr>
{% empty %}
<tr><td colspan="14" class="text-center text-muted py-4">暂无软件资产</td></tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
{% if page_obj.paginator.num_pages > 1 %}
<nav class="mt-3">
<ul class="pagination pagination-sm justify-content-center">
{% if page_obj.has_previous %}
<li class="page-item">
<a class="page-link" href="?page={{ page_obj.previous_page_number }}&search={{ search }}&category={{ current_category }}&status={{ current_status }}&license_type={{ current_license_type }}">上一页</a>
</li>
{% endif %}
<li class="page-item active">
<span class="page-link">{{ page_obj.number }} / {{ page_obj.paginator.num_pages }}</span>
</li>
{% if page_obj.has_next %}
<li class="page-item">
<a class="page-link" href="?page={{ page_obj.next_page_number }}&search={{ search }}&category={{ current_category }}&status={{ current_status }}&license_type={{ current_license_type }}">下一页</a>
</li>
{% endif %}
</ul>
</nav>
{% endif %}
{% endblock %}
+113
View File
@@ -0,0 +1,113 @@
{% extends "assetapp/base.html" %}
{% block title %}用户管理{% endblock %}
{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
<h4 class="mb-0"><i class="bi bi-people me-2"></i>用户管理</h4>
</div>
<div class="card card-dark mb-3">
<div class="card-body py-3">
<form method="get" class="row g-2 align-items-center">
<div class="col-md-4">
<div class="input-group input-group-sm">
<span class="input-group-text"><i class="bi bi-search"></i></span>
<input type="text" name="search" value="{{ search }}" class="form-control"
placeholder="搜索用户名 / 姓名 / 邮箱">
</div>
</div>
<div class="col-md-3">
<select name="is_active" class="form-select form-select-sm">
<option value="">全部状态</option>
<option value="1" {% if current_is_active == '1' %}selected{% endif %}>正常</option>
<option value="0" {% if current_is_active == '0' %}selected{% endif %}>已禁用</option>
</select>
</div>
<div class="col-md-2">
<button type="submit" class="btn btn-primary btn-sm w-100">
<i class="bi bi-funnel me-1"></i>筛选
</button>
</div>
</form>
</div>
</div>
<div class="card card-dark">
<div class="card-body p-0">
<div class="table-responsive">
<table class="table table-dark table-hover mb-0 align-middle">
<thead>
<tr>
<th>ID</th>
<th>用户名</th>
<th>姓名</th>
<th>邮箱</th>
<th>角色</th>
<th>状态</th>
<th>最后登录</th>
<th>加入时间</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for u in page_obj %}
<tr>
<td>{{ u.id }}</td>
<td><strong>{{ u.username }}</strong></td>
<td>{{ u.first_name|default:"-" }}</td>
<td>{{ u.email|default:"-" }}</td>
<td>
{% if u.is_superuser %}
<span class="badge bg-danger">超级管理员</span>
{% elif u.is_staff %}
<span class="badge bg-info">管理员</span>
{% else %}
<span class="badge bg-secondary">普通用户</span>
{% endif %}
</td>
<td>
{% if u.is_active %}
<span class="badge bg-success">正常</span>
{% else %}
<span class="badge bg-secondary">已禁用</span>
{% endif %}
</td>
<td>{{ u.last_login|date:"Y-m-d H:i"|default:"-" }}</td>
<td>{{ u.date_joined|date:"Y-m-d" }}</td>
<td>
<a href="{% url 'admin_password_reset' u.pk %}"
class="btn btn-outline-warning btn-xs" title="重置密码">
<i class="bi bi-key"></i> 重置密码
</a>
</td>
</tr>
{% empty %}
<tr><td colspan="9" class="text-center text-muted py-4">暂无用户</td></tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
{% if page_obj.paginator.num_pages > 1 %}
<nav class="mt-3">
<ul class="pagination pagination-sm justify-content-center">
{% if page_obj.has_previous %}
<li class="page-item">
<a class="page-link" href="?page={{ page_obj.previous_page_number }}&search={{ search }}&is_active={{ current_is_active }}">上一页</a>
</li>
{% endif %}
<li class="page-item active">
<span class="page-link">{{ page_obj.number }} / {{ page_obj.paginator.num_pages }}</span>
</li>
{% if page_obj.has_next %}
<li class="page-item">
<a class="page-link" href="?page={{ page_obj.next_page_number }}&search={{ search }}&is_active={{ current_is_active }}">下一页</a>
</li>
{% endif %}
</ul>
</nav>
{% endif %}
{% endblock %}
@@ -0,0 +1,63 @@
{% extends "assetapp/base.html" %}
{% block title %}重置密码 - {{ target_user.username }}{% endblock %}
{% block content %}
<div class="d-flex align-items-center mb-4">
<a href="{% url 'user_list' %}" class="btn btn-outline-secondary btn-sm me-3">
<i class="bi bi-arrow-left"></i> 返回
</a>
<h4 class="mb-0">
<i class="bi bi-key me-2"></i>重置密码 - {{ target_user.username }}
</h4>
</div>
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card card-dark">
<div class="card-body">
<div class="alert alert-warning py-2 small">
<i class="bi bi-exclamation-triangle me-1"></i>
您正在为用户 <strong>{{ target_user.username }}</strong> 设置新密码,设置后该用户需使用新密码登录。
</div>
<form method="post">
{% csrf_token %}
{% if form.non_field_errors %}
<div class="alert alert-danger py-2 small">{{ form.non_field_errors }}</div>
{% endif %}
<div class="mb-3">
<label class="form-label text-muted" for="{{ form.new_password1.id_for_label }}">
新密码 <span class="text-danger">*</span>
</label>
{{ form.new_password1 }}
{% if form.new_password1.help_text %}
<div class="form-text text-muted">{{ form.new_password1.help_text|safe }}</div>
{% endif %}
{% if form.new_password1.errors %}
<div class="text-danger small mt-1">{{ form.new_password1.errors }}</div>
{% endif %}
</div>
<div class="mb-3">
<label class="form-label text-muted" for="{{ form.new_password2.id_for_label }}">
确认新密码 <span class="text-danger">*</span>
</label>
{{ form.new_password2 }}
{% if form.new_password2.errors %}
<div class="text-danger small mt-1">{{ form.new_password2.errors }}</div>
{% endif %}
</div>
<button type="submit" class="btn btn-warning">
<i class="bi bi-check-circle me-1"></i>确认重置
</button>
<a href="{% url 'user_list' %}" class="btn btn-outline-secondary ms-2">取消</a>
</form>
</div>
</div>
</div>
</div>
{% endblock %}