1
0
forked from erp-dev/erp

fix: added permission for plate_order and printing_order api

This commit is contained in:
2026-01-14 18:14:22 +08:00
parent fae667c965
commit cae0f8434e
17 changed files with 867 additions and 15 deletions

View File

@@ -0,0 +1,106 @@
"""
Printing API Mixins
提供客户可见性过滤等通用功能
"""
from django.db.models import Q
class CustomerVisibilityFilterMixin:
"""
基于客户可见性的查询过滤 Mixin
适用于关联了 Customer 的模型PlateOrder, PrintingOrder, PrintingJob
使用方式:
1. 在 ViewSet 中继承此 Mixin放在 LimitedModelViewSet 之前)
2. 设置 customer_field 指定关联 customer 的字段路径
3. 设置 view_all_permission 指定突破限制的权限名
可见性规则:
- superuser: 无限制
- 有 view_all_permission 权限: 无限制
- 订单.customer 为空: 全员可见(同 merchant
- 订单.customer 不为空: 按客户绑定关系判断
- customer.created_by == 当前员工 → 可见
- 当前员工 in customer.visible_employees → 可见
"""
# 子类需要指定:通过哪个字段关联到 customer
customer_field = 'customer' # PlateOrder/PrintingOrder 直接关联
# customer_field = 'printing_order__customer' # PrintingJob 间接关联
# 子类需要指定:突破限制的权限名(完整格式如 'printing.view_all_plateorders'
view_all_permission = None
def can_bypass_customer_visibility(self) -> bool:
"""
是否可以突破客户可见性限制
注意view_all_customers 权限不影响此判断
"""
user = self.request.user
if user.is_superuser:
return True
# 仅检查订单级别的专属权限
if self.view_all_permission and user.has_perm(self.view_all_permission):
return True
return False
def filter_by_customer_visibility(self, queryset):
"""
应用客户可见性过滤
Returns:
过滤后的 queryset
"""
if self.can_bypass_customer_visibility():
return queryset
user = self.request.user
emp = getattr(user, 'employee', None)
if emp is None:
return queryset.none()
# 可见的客户条件:
# 1. customer.created_by == 当前员工
# 2. 当前员工 in customer.visible_employees
visible_customer_filter = (
Q(**{f'{self.customer_field}__created_by': emp}) |
Q(**{f'{self.customer_field}__visible_employees': emp})
)
# customer 为空时全员可见(同 merchant 下)
no_customer_filter = Q(**{f'{self.customer_field}__isnull': True})
return queryset.filter(visible_customer_filter | no_customer_filter).distinct()
def filter_by_merchant(self, queryset):
"""
应用 merchant 隔离过滤
Returns:
过滤后的 queryset如果用户没有关联 merchant 则返回空
"""
user = self.request.user
if user.is_superuser:
return queryset
emp = getattr(user, 'employee', None)
if emp is None or emp.merchant is None:
return queryset.none()
return queryset.filter(merchant=emp.merchant)
def get_queryset(self):
"""
重写 get_queryset应用 merchant 隔离和客户可见性过滤
"""
queryset = super().get_queryset()
# 1. merchant 隔离(必须)
queryset = self.filter_by_merchant(queryset)
# 2. 客户可见性过滤
queryset = self.filter_by_customer_visibility(queryset)
return queryset

View File

@@ -46,12 +46,13 @@ class PrintingOrderAPITestCase(TestCase):
status=basic_models.EmployeeStatusEnum.ACTIVE
)
# 创建客户
# 创建客户(设置 created_by 以便客户可见性过滤)
self.customer = basic_models.Customer.objects.create(
merchant=self.merchant,
name='测试客户',
mobile='13900139000',
area='测试地区'
area='测试地区',
created_by=self.employee
)
# 创建流程
@@ -72,7 +73,9 @@ class PrintingOrderAPITestCase(TestCase):
view_perm = Permission.objects.get(codename='view_printingorder')
add_perm = Permission.objects.get(codename='add_printingorder')
change_perm = Permission.objects.get(codename='change_printingorder')
self.user.user_permissions.add(view_perm, add_perm, change_perm)
# 添加 view_all 权限以便测试 API 功能(权限过滤逻辑在专门的测试类中验证)
view_all_perm = Permission.objects.get(codename='view_all_printingorders')
self.user.user_permissions.add(view_perm, add_perm, change_perm, view_all_perm)
def test_create_printing_order(self):
"""测试创建印染订单"""
@@ -113,11 +116,13 @@ class PrintingOrderAPITestCase(TestCase):
"""测试获取订单列表"""
# 创建测试订单
printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric='布料1',
width='150cm'
)
printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric='布料2',
width='160cm'
@@ -131,6 +136,7 @@ class PrintingOrderAPITestCase(TestCase):
def test_retrieve_printing_order(self):
"""测试获取订单详情"""
order = printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric='测试布料',
width='150cm',
@@ -148,6 +154,7 @@ class PrintingOrderAPITestCase(TestCase):
def test_update_printing_order(self):
"""测试更新订单"""
order = printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric='旧布料',
width='150cm'
@@ -176,6 +183,7 @@ class PrintingOrderAPITestCase(TestCase):
def test_partial_update_printing_order(self):
"""测试部分更新订单"""
order = printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric='原布料',
width='150cm',
@@ -206,6 +214,7 @@ class PrintingOrderAPITestCase(TestCase):
self.user.user_permissions.add(delete_perm)
order = printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric='测试布料',
width='150cm'
@@ -227,6 +236,7 @@ class PrintingOrderAPITestCase(TestCase):
self.user.user_permissions.add(invalidate_perm)
order = printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric='测试布料',
width='150cm',
@@ -243,6 +253,7 @@ class PrintingOrderAPITestCase(TestCase):
def test_invalidate_without_permission(self):
"""测试没有权限时作废订单失败"""
order = printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric='测试布料',
width='150cm'
@@ -259,6 +270,7 @@ class PrintingOrderAPITestCase(TestCase):
self.user.user_permissions.add(activate_perm)
order = printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric='测试布料',
width='150cm',
@@ -275,6 +287,7 @@ class PrintingOrderAPITestCase(TestCase):
def test_activate_without_permission(self):
"""测试没有权限时恢复订单失败"""
order = printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric='测试布料',
width='150cm',
@@ -288,6 +301,7 @@ class PrintingOrderAPITestCase(TestCase):
def test_mark_fabric_received(self):
"""测试标记布料已收"""
order = printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric='测试布料',
width='150cm',
@@ -304,6 +318,7 @@ class PrintingOrderAPITestCase(TestCase):
def test_mark_fabric_received_already_received(self):
"""测试重复标记布料已收"""
order = printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric='测试布料',
width='150cm',
@@ -319,15 +334,18 @@ class PrintingOrderAPITestCase(TestCase):
customer2 = basic_models.Customer.objects.create(
merchant=self.merchant,
name='客户2',
mobile='13900139001'
mobile='13900139001',
created_by=self.employee
)
printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric='布料1',
width='150cm'
)
printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=customer2,
fabric='布料2',
width='160cm'
@@ -340,12 +358,14 @@ class PrintingOrderAPITestCase(TestCase):
def test_filter_by_urgent(self):
"""测试按紧急状态过滤"""
printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric='布料1',
width='150cm',
is_urgent=True
)
printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric='布料2',
width='160cm',
@@ -360,11 +380,13 @@ class PrintingOrderAPITestCase(TestCase):
def test_search_by_fabric(self):
"""测试按布料搜索"""
printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric='纯棉布料',
width='150cm'
)
printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric='涤纶布料',
width='160cm'
@@ -378,11 +400,13 @@ class PrintingOrderAPITestCase(TestCase):
def test_ordering(self):
"""测试排序"""
order1 = printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric='布料1',
width='150cm'
)
order2 = printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric='布料2',
width='160cm'
@@ -406,6 +430,7 @@ class PrintingOrderAPITestCase(TestCase):
from datetime import date
order = printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric='测试布料',
width='150cm'
@@ -452,6 +477,7 @@ class PrintingOrderAPITestCase(TestCase):
def test_order_progress_in_list(self):
"""测试订单列表包含进度字段"""
order = printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric='测试布料',
width='150cm',
@@ -466,6 +492,7 @@ class PrintingOrderAPITestCase(TestCase):
def test_update_process_when_no_jobs(self):
"""测试没有任务时可以修改流程"""
order = printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric='测试布料',
width='150cm',
@@ -491,6 +518,7 @@ class PrintingOrderAPITestCase(TestCase):
def test_cannot_update_process_when_job_started(self):
"""测试有已开始的任务时不能修改流程"""
order = printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric='测试布料',
width='150cm',
@@ -549,6 +577,7 @@ class PrintingOrderAPITestCase(TestCase):
"""测试订单列表包含 jobs_status_summary 字段PrintingJob 状态汇总)"""
# 创建订单
order = printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric='测试布料',
width='150cm',
@@ -622,6 +651,7 @@ class PrintingOrderAPITestCase(TestCase):
def test_jobs_status_summary_empty_when_no_jobs(self):
"""测试没有任务时 jobs_status_summary 为空列表"""
order = printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric='无任务订单',
width='150cm',
@@ -640,3 +670,174 @@ class PrintingOrderAPITestCase(TestCase):
summary = response.data['results'][0]['jobs_status_summary']
self.assertEqual(summary, [])
class CustomerVisibilityFilterTestCase(TestCase):
"""测试客户可见性过滤"""
def setUp(self):
from django.core.cache import cache
cache.clear()
self.client = APIClient()
# 创建商户
self.merchant = basic_models.Merchant.objects.create(
name='测试印花厂',
type=basic_models.MerchantTypeEnum.FACTORY
)
# 创建第二个商户(用于测试 merchant 隔离)
self.merchant2 = basic_models.Merchant.objects.create(
name='其他印花厂',
type=basic_models.MerchantTypeEnum.FACTORY
)
# 创建用户和员工
self.user = User.objects.create_user(
username='testuser',
password='testpass123',
email='test@example.com'
)
self.employee = basic_models.Employee.objects.create(
sys_user=self.user,
merchant=self.merchant,
name='测试员工',
mobile='13800138000',
status=basic_models.EmployeeStatusEnum.ACTIVE
)
# 创建第二个员工(同商户,用于测试客户可见性)
self.user2 = User.objects.create_user(
username='testuser2',
password='testpass123',
email='test2@example.com'
)
self.employee2 = basic_models.Employee.objects.create(
sys_user=self.user2,
merchant=self.merchant,
name='测试员工2',
mobile='13800138001',
status=basic_models.EmployeeStatusEnum.ACTIVE
)
# 创建客户employee 创建的employee 可见)
self.customer_by_emp1 = basic_models.Customer.objects.create(
merchant=self.merchant,
name='员工1的客户',
mobile='13900139000',
created_by=self.employee
)
# 创建客户employee2 创建的,默认 employee 不可见)
self.customer_by_emp2 = basic_models.Customer.objects.create(
merchant=self.merchant,
name='员工2的客户',
mobile='13900139001',
created_by=self.employee2
)
# 创建 employee 可见客户的订单
self.order_visible = printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer_by_emp1,
fabric='可见订单',
width='150cm'
)
# 创建 employee 不可见客户的订单
self.order_invisible = printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer_by_emp2,
fabric='不可见订单',
width='150cm'
)
# 创建其他商户的订单merchant 隔离测试)
self.customer_other_merchant = basic_models.Customer.objects.create(
merchant=self.merchant2,
name='其他商户客户',
mobile='13900139002'
)
self.order_other_merchant = printing_models.PrintingOrder.objects.create(
merchant=self.merchant2,
customer=self.customer_other_merchant,
fabric='其他商户订单',
width='150cm'
)
# 给用户添加基础权限(不含 view_all
view_perm = Permission.objects.get(codename='view_printingorder')
self.user.user_permissions.add(view_perm)
self.user2.user_permissions.add(view_perm)
self.client.force_authenticate(user=self.user)
def test_list_only_visible_orders(self):
"""测试普通员工只能看到可见客户的订单"""
response = self.client.get('/api/v1/printing-orders/')
self.assertEqual(response.status_code, status.HTTP_200_OK)
# 应该只能看到自己创建的客户的订单 = 1
self.assertEqual(response.data['count'], 1)
fabrics = [r['fabric'] for r in response.data['results']]
self.assertIn('可见订单', fabrics)
self.assertNotIn('不可见订单', fabrics)
self.assertNotIn('其他商户订单', fabrics)
def test_retrieve_visible_order(self):
"""测试可以获取可见订单详情"""
response = self.client.get(f'/api/v1/printing-orders/{self.order_visible.id}/')
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_retrieve_invisible_order_404(self):
"""测试无法获取不可见订单详情"""
response = self.client.get(f'/api/v1/printing-orders/{self.order_invisible.id}/')
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
def test_retrieve_other_merchant_order_404(self):
"""测试无法获取其他商户的订单"""
response = self.client.get(f'/api/v1/printing-orders/{self.order_other_merchant.id}/')
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
def test_customer_in_visible_employees_can_see(self):
"""测试被加入 visible_employees 后可以看到订单"""
# 将 employee 加入 customer_by_emp2 的可见员工列表
self.customer_by_emp2.visible_employees.add(self.employee)
response = self.client.get('/api/v1/printing-orders/')
self.assertEqual(response.status_code, status.HTTP_200_OK)
# 现在应该能看到 2 个订单(自己创建的 + 被加入可见列表的)
self.assertEqual(response.data['count'], 2)
fabrics = [r['fabric'] for r in response.data['results']]
self.assertIn('不可见订单', fabrics)
def test_view_all_permission_bypasses_filter(self):
"""测试 view_all 权限可以突破客户可见性限制"""
# 添加 view_all 权限
view_all_perm = Permission.objects.get(codename='view_all_printingorders')
self.user.user_permissions.add(view_all_perm)
response = self.client.get('/api/v1/printing-orders/')
self.assertEqual(response.status_code, status.HTTP_200_OK)
# 应该能看到本商户的所有订单2个但不能看到其他商户的
self.assertEqual(response.data['count'], 2)
fabrics = [r['fabric'] for r in response.data['results']]
self.assertIn('不可见订单', fabrics)
self.assertNotIn('其他商户订单', fabrics)
def test_superuser_sees_all(self):
"""测试超级用户可以看到所有订单"""
self.user.is_superuser = True
self.user.save()
response = self.client.get('/api/v1/printing-orders/')
self.assertEqual(response.status_code, status.HTTP_200_OK)
# 超级用户可以看到所有订单(包括其他商户)
self.assertEqual(response.data['count'], 3)

View File

@@ -28,6 +28,7 @@ from .serializers import (
PrintingJobDetailSerializer,
PrintingJobCreateUpdateSerializer,
)
from .mixins import CustomerVisibilityFilterMixin
class IsPrintingFactory(BasePermission):
@@ -96,7 +97,7 @@ class PrintingOrderFilterSet(django_filters.FilterSet):
@method_decorator(cache_page(20), name='list')
class PrintingOrderViewSet(LimitedModelViewSet):
class PrintingOrderViewSet(CustomerVisibilityFilterMixin, LimitedModelViewSet):
"""
印染订单 ViewSet
@@ -129,8 +130,14 @@ class PrintingOrderViewSet(LimitedModelViewSet):
格式: [{"state_name": "进度一", "state_id": 1, "count": 3}, ...]
- jobs_last_status_summary: 订单下所有印染任务按最后完成状态分组的数量汇总
格式: [{"state_name": "进度一", "count": 3}, ...]
权限控制:
- 默认按客户可见性过滤(员工只能看到自己负责的客户的订单)
- 拥有 printing.view_all_printingorders 权限可突破此限制
"""
queryset = models.PrintingOrder.objects.all()
customer_field = 'customer'
view_all_permission = 'printing.view_all_printingorders'
permission_classes = [DjangoModelPermissions]
filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
filterset_class = PrintingOrderFilterSet
@@ -286,7 +293,7 @@ class PrintingJobFilterSet(django_filters.FilterSet):
fields = ['printing_order', 'product']
class PrintingJobViewSet(LimitedModelViewSet):
class PrintingJobViewSet(CustomerVisibilityFilterMixin, LimitedModelViewSet):
"""
印染款式明细 ViewSet
@@ -318,8 +325,14 @@ class PrintingJobViewSet(LimitedModelViewSet):
- pieces_max: 最大件数
- search: 全文搜索(产品名称、单位、尺寸、备注)
- ordering: 排序字段
权限控制:
- 默认按客户可见性过滤(通过 printing_order.customer
- 拥有 printing.view_all_printingorders 权限可突破此限制
"""
queryset = models.PrintingJob.objects.all()
customer_field = 'printing_order__customer'
view_all_permission = 'printing.view_all_printingorders'
permission_classes = [DjangoModelPermissions, IsPrintingFactory]
filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
filterset_class = PrintingJobFilterSet
@@ -630,7 +643,7 @@ def _plate_order_last_modified(request, *args, **kwargs):
# @method_decorator(condition(last_modified_func=_plate_order_last_modified), name='list')
class PlateOrderViewSet(LimitedModelViewSet):
class PlateOrderViewSet(CustomerVisibilityFilterMixin, LimitedModelViewSet):
"""
开版订单 ViewSet
@@ -677,8 +690,14 @@ class PlateOrderViewSet(LimitedModelViewSet):
- created_date_to: 创建日期结束
- search: 全文搜索(设计编号、款式名称、客户名称、面料)
- ordering: 排序字段
权限控制:
- 默认按客户可见性过滤(员工只能看到自己负责的客户的订单)
- 拥有 printing.view_all_plateorders 权限可突破此限制
"""
queryset = models.PlateOrder.objects.all()
customer_field = 'customer'
view_all_permission = 'printing.view_all_plateorders'
permission_classes = [DjangoModelPermissions]
parser_classes = [MultiPartParser, FormParser, JSONParser] # 支持文件上传
filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]