factory/apps/hrm/serializers.py

229 lines
8.5 KiB
Python
Executable File

from apps.hrm.errors import PHONE_F_WRONG
from rest_framework.serializers import ModelSerializer
from rest_framework import serializers
from apps.utils.serializers import CustomModelSerializer
from apps.utils.constants import EXCLUDE_FIELDS, EXCLUDE_FIELDS_BASE
from apps.utils.tools import rannum
from apps.hrm.models import Certificate, ClockRecord, Employee, NotWorkRemark
from apps.system.serializers import DeptSimpleSerializer, UserSimpleSerializer
from django.db import transaction
from apps.third.clients import dhClient
from apps.third.tapis import dhapis
import re
from datetime import datetime
from django.conf import settings
class EmployeeBaseSerializer(CustomModelSerializer):
def save(self, **kwargs):
if self.validated_data.get('user', None):
user = self.validated_data['user']
self.validated_data['name'] = user.name
self.validated_data['belong_dept'] = user.belong_dept
return super().save(**kwargs)
def phone_check(phone):
re_phone = r'^1[358]\d{9}$|^147\d{8}$|^176\d{8}$'
if not re.match(re_phone, phone):
raise serializers.ValidationError(**PHONE_F_WRONG)
return phone
class EmployeeCreateUpdateSerializer(EmployeeBaseSerializer):
phone = serializers.CharField(label="手机号", validators=[phone_check])
class Meta:
model = Employee
exclude = EXCLUDE_FIELDS + ['is_atwork', 'last_check_time',
'not_work_remark', 'third_info', 'type']
extra_kwargs = {
'phone': {'required': True},
'number': {'required': True},
'photo': {'required': True},
'id_number': {'required': True},
}
@transaction.atomic
def create(self, validated_data):
instance = super().create(validated_data)
if settings.DAHUA_ENABLED and dhClient:
# 创建人员
_, res = dhClient.request(**dhapis['person_gen_id'])
personId = res['id']
departmentId = 1
if instance.belong_dept:
try:
departmentId = instance.belong_dept.third_info['dh_id']
except Exception:
pass
json_data = {
"service": "ehs",
"id": personId,
"name": instance.name,
"code": instance.number,
"paperType": 111,
"paperNumber": instance.id_number,
"paperAddress": "default",
"departmentId": departmentId,
"phone": instance.phone,
"email": instance.email,
"sex": 1 if instance.gender == '' else 2
}
_, res = dhClient.request(**dhapis['person_img_upload'], file_path_rela=instance.photo)
dh_photo = res["fileUrl"]
json_data.update(
{
"biosignatureTypeList": [3],
"personBiosignatures": [{
"type": 3,
"index": 1,
"path": dh_photo
}]
}
)
_, res = dhClient.request(**dhapis['person_add'], json=json_data)
# 开人脸卡
_, res = dhClient.request(**dhapis['card_gen_id'])
cardId = res['id']
cardNumber = instance.id[:8] + rannum(2)
now = datetime.now()
startDate = now.strftime("%Y-%m-%d %H:%M:%S")
endDate = (datetime(year=now.year+50,
month=now.month, day=1)).strftime("%Y-%m-%d %H:%M:%S")
json_data = {
"id": cardId,
"cardNumber": cardNumber,
"category": 0,
"cardType": 0,
"personId": personId,
"departmentId": departmentId,
"startDate": startDate,
"endDate": endDate
}
_, res = dhClient.request(**dhapis['card_add'], json=json_data)
instance.third_info = {'dh_id': personId,
'dh_photo': dh_photo, 'dh_face_card': res['id']}
instance.save()
return instance
@transaction.atomic
def update(self, instance, validated_data):
old_photo = instance.photo
instance = super().update(instance, validated_data)
departmentId = 1
if instance.belong_dept:
try:
departmentId = instance.belong_dept.third_info['dh_id']
except Exception:
pass
if settings.DAHUA_ENABLED and dhClient:
third_info = instance.third_info
dh_id = instance.third_info['dh_id']
dh_photo = third_info['dh_photo']
json_data = {
"service": "ehs",
"id": dh_id,
"name": instance.name,
"code": instance.number,
"paperType": 111,
"paperNumber": instance.id_number,
"paperAddress": "default",
"departmentId": departmentId,
"phone": instance.phone,
"email": instance.email,
"sex": 1 if instance.gender == '' else 2,
"biosignatureTypeList": [3],
"personBiosignatures": [{
"type": 3,
"index": 1,
"path": third_info['dh_photo']
}]
}
if instance.photo != old_photo:
_, res = dhClient.request(**dhapis['person_img_upload'], file_path_rela=instance.photo)
dh_photo = res["fileUrl"]
json_data.update(
{
"biosignatureTypeList": [3],
"personBiosignatures": [{
"type": 3,
"index": 1,
"path": dh_photo
}]
}
)
third_info['dh_photo'] = dh_photo
dhClient.request(**dhapis['person_update'], json=json_data)
# 开人脸卡
if instance.job_state in [Employee.JOB_ON]:
if not third_info.get('dh_face_card', None):
_, res = dhClient.request(**dhapis['card_gen_id'])
cardId = res['id']
cardNumber = instance.id[3:8] + rannum(5)
now = datetime.now()
startDate = now.strftime("%Y-%m-%d %H:%M:%S")
endDate = (datetime(year=now.year+50,
month=now.month, day=1)).strftime("%Y-%m-%d %H:%M:%S")
json_data = {
"id": cardId,
"cardNumber": cardNumber,
"category": 0,
"cardType": 0,
"personId": third_info['dh_id'],
"departmentId": departmentId,
"startDate": startDate,
"endDate": endDate
}
_, res = dhClient.request(**dhapis['card_add'], json=json_data)
third_info['dh_face_card'] = cardNumber
instance.save()
return instance
class ChannelAuthoritySerializer(serializers.Serializer):
pks = serializers.ListField(child=serializers.CharField(max_length=20), label="员工ID列表")
channels = serializers.ListField(child=serializers.CharField(max_length=20), label="门通道ID列表")
class EmployeeSerializer(EmployeeBaseSerializer):
belong_dept_ = DeptSimpleSerializer(source='belong_dept', read_only=True)
class Meta:
model = Employee
fields = '__all__'
read_only_fields = ['is_atwork', 'last_check_time', 'not_work_remark']
class EmployeeNotWorkRemarkSerializer(ModelSerializer):
class Meta:
model = Employee
fields = ['not_work_remark']
class ClockRecordListSerializer(serializers.ModelSerializer):
create_by_ = UserSimpleSerializer(source='create_by', read_only=True)
class Meta:
model = ClockRecord
fields = '__all__'
class NotWorkRemarkListSerializer(serializers.ModelSerializer):
class Meta:
model = NotWorkRemark
fields = '__all__'
class CertificateCreateUpdateSerializer(CustomModelSerializer):
class Meta:
model = Certificate
exclude = EXCLUDE_FIELDS
class CertificateSerializer(CustomModelSerializer):
class Meta:
model = Certificate
fields = '__all__'