修正员工基础信息编辑

This commit is contained in:
2026-07-01 14:24:46 +08:00
parent 9939bfb317
commit fc368a866f
11 changed files with 578 additions and 76 deletions
@@ -110,6 +110,21 @@ public class NailArtistInfoDTO {
*/
private String avatar;
/**
* 登录手机号
*/
private String phone;
/**
* 联系电话
*/
private String contactPhone;
/**
* 微信号
*/
private String wechatId;
/**
* 排班模式摘要
*/
@@ -197,16 +197,11 @@ public class NailArtistInfoServiceImpl extends ServiceImpl<NailArtistInfoMapper,
* @return NailArtistInfoDTO result consumed by the caller or returned to the frontend
*/
public NailArtistInfoDTO saveOrUpdateNailArtistInfo(NailArtistInfoDTO dto) {
NailArtistInfoDO entity = new NailArtistInfoDO();
BeanUtils.copyProperties(dto, entity);
NailArtistInfoDO existing = getOne(new LambdaQueryWrapper<NailArtistInfoDO>()
.eq(NailArtistInfoDO::getUserId, dto.getUserId())
.eq(NailArtistInfoDO::getIsDelete, 0)
.last("LIMIT 1"));
if (existing != null) {
entity.setId(existing.getId());
}
NailArtistInfoDO entity = existing == null ? buildNewArtistInfoEntity(dto) : mergeArtistInfoEntity(existing, dto);
if (entity.getStatus() == null) {
entity.setStatus(1);
}
@@ -232,6 +227,46 @@ public class NailArtistInfoServiceImpl extends ServiceImpl<NailArtistInfoMapper,
return convertToDTO(entity);
}
private NailArtistInfoDO buildNewArtistInfoEntity(NailArtistInfoDTO dto) {
NailArtistInfoDO entity = new NailArtistInfoDO();
BeanUtils.copyProperties(dto, entity);
return entity;
}
private NailArtistInfoDO mergeArtistInfoEntity(NailArtistInfoDO entity, NailArtistInfoDTO dto) {
if (dto.getIdentity() != null) {
entity.setIdentity(dto.getIdentity());
}
if (dto.getExperience() != null) {
entity.setExperience(dto.getExperience());
}
if (dto.getSkills() != null) {
entity.setSkills(dto.getSkills());
}
if (dto.getRating() != null) {
entity.setRating(dto.getRating());
}
if (dto.getStatus() != null) {
entity.setStatus(dto.getStatus());
}
if (dto.getColor() != null) {
entity.setColor(dto.getColor());
}
if (dto.getParticipateProduction() != null) {
entity.setParticipateProduction(dto.getParticipateProduction());
}
if (dto.getWorkStartTime() != null) {
entity.setWorkStartTime(dto.getWorkStartTime());
}
if (dto.getWorkEndTime() != null) {
entity.setWorkEndTime(dto.getWorkEndTime());
}
if (dto.getPortfolio() != null) {
entity.setPortfolio(dto.getPortfolio());
}
return entity;
}
private void syncArtistNickname(NailArtistInfoDTO dto) {
if (dto.getUserId() == null || !StringUtils.hasText(dto.getNickname())) {
return;
@@ -429,6 +464,9 @@ public class NailArtistInfoServiceImpl extends ServiceImpl<NailArtistInfoMapper,
dto.setNickname(user.getNickname());
dto.setSignature(user.getSignature());
dto.setAvatar(resolveAccessibleAvatar(user.getAvatar()));
dto.setPhone(user.getPhone());
dto.setContactPhone(user.getContactPhone());
dto.setWechatId(user.getWechatId());
dto.setUserType(user.getType());
dto.setUserTypeName(resolveUserTypeName(user.getType()));
if (dto.getParticipateProduction() == null) {
@@ -457,6 +495,9 @@ public class NailArtistInfoServiceImpl extends ServiceImpl<NailArtistInfoMapper,
dto.setNickname(user.getNickname());
dto.setSignature(user.getSignature());
dto.setAvatar(resolveAccessibleAvatar(user.getAvatar()));
dto.setPhone(user.getPhone());
dto.setContactPhone(user.getContactPhone());
dto.setWechatId(user.getWechatId());
dto.setUserType(user.getType());
dto.setUserTypeName(resolveUserTypeName(user.getType()));
dto.setIdentity("美甲师");
@@ -35,6 +35,7 @@ import com.xiaowang.jayucloud.core.modules.user.service.UserService;
import com.xiaowang.jayucloud.core.modules.user.vo.UserVO;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
@@ -182,10 +183,34 @@ public class AdminManagerController {
public Result<NailArtistInfoDTO> saveEmployee(HttpServletRequest request,
@RequestBody NailArtistInfoDTO dto) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
if (dto.getUserId() == null) {
throw new RuntimeException("员工用户ID不能为空");
}
if (!adminScopeHelper.isPlatformAdmin(currentUser)) {
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, dto.getUserId(), "无权编辑其他店铺员工");
}
return Result.success(nailArtistInfoService.saveOrUpdateNailArtistInfo(dto));
syncEmployeeUserBasics(dto);
return Result.success(nailArtistInfoService.saveOrUpdateNailArtistInfo(buildEmployeeArtistSaveDTO(dto)));
}
@PostMapping("/employees/{userId}/reset-password")
@RequirePermission("user:reset_password")
@OperationGuard(action = "manager-employee-reset-password", ttlSeconds = 10, message = "密码重置处理中,请勿重复点击")
public Result<Boolean> resetEmployeePassword(HttpServletRequest request,
@PathVariable Long userId) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
if (!adminScopeHelper.isPlatformAdmin(currentUser)) {
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权重置其他店铺员工密码");
}
UserVO targetUser = userService.getUserById(userId);
if (targetUser == null) {
throw new RuntimeException("目标员工不存在");
}
adminScopeHelper.ensureAssignableUserType(currentUser, targetUser.getType());
if (!Integer.valueOf(3).equals(targetUser.getType())) {
throw new RuntimeException("只能重置员工密码");
}
return Result.success(userService.resetManagedEmployeePassword(userId, currentUser.getId()));
}
@PostMapping("/employees/users")
@@ -318,4 +343,62 @@ public class AdminManagerController {
adminScopeHelper.requireShopContext(currentUser);
return Result.success(shopService.saveScheduleException(dto));
}
private void syncEmployeeUserBasics(NailArtistInfoDTO dto) {
if (!hasEmployeeUserBasicChanges(dto)) {
return;
}
UserDTO userDTO = new UserDTO();
if (dto.getNickname() != null) {
if (!StringUtils.hasText(dto.getNickname())) {
throw new RuntimeException("员工昵称不能为空");
}
userDTO.setNickname(dto.getNickname().trim());
}
if (dto.getAvatar() != null) {
userDTO.setAvatar(dto.getAvatar().trim());
}
if (dto.getPhone() != null) {
if (!StringUtils.hasText(dto.getPhone())) {
throw new RuntimeException("登录手机号不能为空");
}
userDTO.setPhone(dto.getPhone().trim());
}
if (dto.getContactPhone() != null) {
userDTO.setContactPhone(trimProvided(dto.getContactPhone()));
}
if (dto.getWechatId() != null) {
userDTO.setWechatId(trimProvided(dto.getWechatId()));
}
boolean updated = userService.updateUser(dto.getUserId(), userDTO);
if (!updated) {
throw new RuntimeException("员工账号不存在,无法保存基础信息");
}
}
private boolean hasEmployeeUserBasicChanges(NailArtistInfoDTO dto) {
return dto.getNickname() != null
|| dto.getAvatar() != null
|| dto.getPhone() != null
|| dto.getContactPhone() != null
|| dto.getWechatId() != null;
}
private NailArtistInfoDTO buildEmployeeArtistSaveDTO(NailArtistInfoDTO dto) {
NailArtistInfoDTO artistDTO = new NailArtistInfoDTO();
artistDTO.setId(dto.getId());
artistDTO.setUserId(dto.getUserId());
artistDTO.setIdentity(trimProvided(dto.getIdentity()));
artistDTO.setExperience(dto.getExperience());
artistDTO.setSkills(trimProvided(dto.getSkills()));
artistDTO.setRating(dto.getRating());
artistDTO.setStatus(dto.getStatus());
artistDTO.setColor(trimProvided(dto.getColor()));
artistDTO.setPortfolio(trimProvided(dto.getPortfolio()));
return artistDTO;
}
private String trimProvided(String value) {
return value == null ? null : value.trim();
}
}
@@ -252,6 +252,15 @@ public interface UserService extends IService<UserDO> {
*/
boolean resetPassword(Long targetUserId, Long currentUserId);
/**
* 重置店务员工密码
*
* @param targetUserId 目标员工用户ID
* @param currentUserId 当前操作用户ID
* @return 重置是否成功
*/
boolean resetManagedEmployeePassword(Long targetUserId, Long currentUserId);
/**
* Run business method `resetPasswordByPhone`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
@@ -1836,6 +1836,32 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
}
return updated;
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean resetManagedEmployeePassword(Long targetUserId, Long currentUserId) {
UserDO targetUser = userMapper.selectById(targetUserId);
if (targetUser == null || Integer.valueOf(1).equals(targetUser.getIsDelete())) {
throw new RuntimeException("目标员工不存在");
}
UserDO currentUser = userMapper.selectById(currentUserId);
if (currentUser == null || Integer.valueOf(1).equals(currentUser.getIsDelete())) {
throw new RuntimeException("当前用户不存在");
}
if (!Integer.valueOf(2).equals(currentUser.getType()) && !Integer.valueOf(4).equals(currentUser.getType())) {
throw new RuntimeException("当前账号无权重置员工密码");
}
if (!Integer.valueOf(3).equals(targetUser.getType())) {
throw new RuntimeException("只能重置员工密码");
}
targetUser.setPassword(passwordEncoder.encode(resolveAdminDefaultPassword()));
targetUser.setUpdateTime(LocalDateTime.now());
boolean updated = userMapper.updateById(targetUser) > 0;
if (updated) {
userSessionService.revokeAllUserSessions(targetUserId);
}
return updated;
}
@Override
/**
@@ -94,10 +94,47 @@ class NailArtistInfoServiceImplTest {
ReflectionTestUtils.setField(service, "artistScheduleMapper", artistScheduleMapper);
ReflectionTestUtils.setField(service, "appointmentReservationMapper", appointmentReservationMapper);
when(userShopBindingSupport.listShopOptionsByUserId(any(), anyBoolean(), anyBoolean())).thenReturn(List.of());
when(objectStorageUrlSupport.toAccessibleUrl(any(String.class)))
.thenAnswer(invocation -> invocation.getArgument(0, String.class));
when(objectStorageUrlSupport.toAccessibleUrl(any(ObjectStorageFileVO.class)))
.thenAnswer(invocation -> invocation.getArgument(0, ObjectStorageFileVO.class).getFileUrl());
}
@Test
void getByUserIdReturnsUserContactFields() {
NailArtistInfoDO artistInfo = new NailArtistInfoDO();
artistInfo.setId(11L);
artistInfo.setUserId(7L);
artistInfo.setIdentity("高级美甲师");
artistInfo.setStatus(1);
artistInfo.setIsDelete(0);
when(nailArtistInfoMapper.selectOne(any())).thenReturn(artistInfo);
UserDO user = new UserDO();
user.setId(7L);
user.setNickname("Mina");
user.setAvatar("https://img.test/mina.jpg");
user.setPhone("13800138000");
user.setContactPhone("13900139000");
user.setWechatId("wx_mina");
user.setType(3);
user.setShopId(9L);
user.setIsDelete(0);
when(userMapper.selectById(7L)).thenReturn(user);
ShopDO shop = new ShopDO();
shop.setId(9L);
shop.setShopName("测试门店");
when(shopMapper.selectById(9L)).thenReturn(shop);
NailArtistInfoDTO dto = service.getByUserId(7L);
assertThat(dto.getPhone()).isEqualTo("13800138000");
assertThat(dto.getContactPhone()).isEqualTo("13900139000");
assertThat(dto.getWechatId()).isEqualTo("wx_mina");
assertThat(dto.getAvatar()).isEqualTo("https://img.test/mina.jpg");
assertThat(dto.getShopName()).isEqualTo("测试门店");
}
@Test
void saveOrUpdateNailArtistInfoSyncsNicknameToUser() {
NailArtistInfoDO existing = new NailArtistInfoDO();
@@ -36,7 +36,11 @@ import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -165,6 +169,112 @@ class AdminManagerControllerTest {
));
}
@Test
void saveEmployeeShouldSyncUserBasicsAndArtistInfo() {
MockHttpServletRequest request = new MockHttpServletRequest();
UserDO manager = new UserDO();
manager.setType(2);
NailArtistInfoDTO dto = new NailArtistInfoDTO();
dto.setId(11L);
dto.setUserId(7L);
dto.setNickname(" 新员工 ");
dto.setAvatar(" https://img.test/a.jpg ");
dto.setPhone(" 13800138000 ");
dto.setContactPhone(" 13900139000 ");
dto.setWechatId(" wx_mina ");
dto.setIdentity("高级美甲师");
dto.setStatus(1);
dto.setParticipateProduction(0);
NailArtistInfoDTO saved = new NailArtistInfoDTO();
saved.setUserId(7L);
when(adminScopeHelper.getCurrentUser(request)).thenReturn(manager);
when(adminScopeHelper.isPlatformAdmin(manager)).thenReturn(false);
when(userService.updateUser(any(), any(UserDTO.class))).thenReturn(true);
when(nailArtistInfoService.saveOrUpdateNailArtistInfo(any())).thenReturn(saved);
Result<NailArtistInfoDTO> result = controller.saveEmployee(request, dto);
assertThat(result.getData()).isSameAs(saved);
verify(adminScopeHelper).ensureUserAccessibleInCurrentShop(manager, 7L, "无权编辑其他店铺员工");
verify(userService).updateUser(argThat(userId -> Long.valueOf(7L).equals(userId)), argThat(userDTO ->
"新员工".equals(userDTO.getNickname())
&& "https://img.test/a.jpg".equals(userDTO.getAvatar())
&& "13800138000".equals(userDTO.getPhone())
&& "13900139000".equals(userDTO.getContactPhone())
&& "wx_mina".equals(userDTO.getWechatId())
));
verify(nailArtistInfoService).saveOrUpdateNailArtistInfo(argThat(artistDTO ->
Long.valueOf(11L).equals(artistDTO.getId())
&& Long.valueOf(7L).equals(artistDTO.getUserId())
&& "高级美甲师".equals(artistDTO.getIdentity())
&& Integer.valueOf(1).equals(artistDTO.getStatus())
&& artistDTO.getNickname() == null
&& artistDTO.getPhone() == null
&& artistDTO.getParticipateProduction() == null
&& artistDTO.getWorkStartTime() == null
&& artistDTO.getWorkEndTime() == null
));
}
@Test
void saveEmployeeShouldStopWhenUserOutOfScope() {
MockHttpServletRequest request = new MockHttpServletRequest();
UserDO manager = new UserDO();
NailArtistInfoDTO dto = new NailArtistInfoDTO();
dto.setUserId(7L);
when(adminScopeHelper.getCurrentUser(request)).thenReturn(manager);
when(adminScopeHelper.isPlatformAdmin(manager)).thenReturn(false);
doThrow(new RuntimeException("无权编辑其他店铺员工"))
.when(adminScopeHelper).ensureUserAccessibleInCurrentShop(manager, 7L, "无权编辑其他店铺员工");
assertThatThrownBy(() -> controller.saveEmployee(request, dto))
.isInstanceOf(RuntimeException.class)
.hasMessage("无权编辑其他店铺员工");
verify(userService, never()).updateUser(any(), any(UserDTO.class));
verify(nailArtistInfoService, never()).saveOrUpdateNailArtistInfo(any());
}
@Test
void resetEmployeePasswordShouldUseManagerScope() {
MockHttpServletRequest request = new MockHttpServletRequest();
UserDO manager = new UserDO();
manager.setId(5L);
manager.setType(2);
UserVO targetUser = new UserVO();
targetUser.setId(7L);
targetUser.setType(3);
when(adminScopeHelper.getCurrentUser(request)).thenReturn(manager);
when(adminScopeHelper.isPlatformAdmin(manager)).thenReturn(false);
when(userService.getUserById(7L)).thenReturn(targetUser);
when(userService.resetManagedEmployeePassword(7L, 5L)).thenReturn(true);
Result<Boolean> result = controller.resetEmployeePassword(request, 7L);
assertThat(result.getData()).isTrue();
verify(adminScopeHelper).ensureUserAccessibleInCurrentShop(manager, 7L, "无权重置其他店铺员工密码");
verify(adminScopeHelper).ensureAssignableUserType(manager, 3);
verify(userService).resetManagedEmployeePassword(7L, 5L);
}
@Test
void resetEmployeePasswordShouldRejectNonEmployee() {
MockHttpServletRequest request = new MockHttpServletRequest();
UserDO manager = new UserDO();
manager.setId(5L);
manager.setType(2);
UserVO targetUser = new UserVO();
targetUser.setId(7L);
targetUser.setType(0);
when(adminScopeHelper.getCurrentUser(request)).thenReturn(manager);
when(adminScopeHelper.isPlatformAdmin(manager)).thenReturn(false);
when(userService.getUserById(7L)).thenReturn(targetUser);
assertThatThrownBy(() -> controller.resetEmployeePassword(request, 7L))
.isInstanceOf(RuntimeException.class)
.hasMessage("只能重置员工密码");
verify(userService, never()).resetManagedEmployeePassword(any(), any());
}
@Test
void saveScheduleShouldResolveShopScopeBeforeSaving() {
MockHttpServletRequest request = new MockHttpServletRequest();
@@ -19,6 +19,9 @@ export const managerEmployeesApi = {
save(data: Partial<Artist>): Promise<Artist> {
return adminApi.post('/manager/employees', data)
},
resetPassword(userId: IdType): Promise<boolean> {
return adminApi.post(`/manager/employees/${userId}/reset-password`)
},
createUser(data: EmployeeCreateRequest): Promise<IdType> {
return adminApi.post('/manager/employees/users', data)
},
+2
View File
@@ -6,6 +6,8 @@ export interface Artist {
name: string
nickname?: string
phone?: string
contactPhone?: string
wechatId?: string
color?: string
shortName?: string
avatar?: string
@@ -121,7 +121,7 @@ const save = async (): Promise<void> => {
try {
const color = selected.value
const saved = await managerEmployeesApi.save({
...employee.value,
id: employee.value.id,
userId: employee.value.userId || employeeId.value,
color
})
+244 -68
View File
@@ -9,7 +9,7 @@
</div>
<div class="employee-hero__body">
<h2>{{ employee.name || employee.nickname || '未命名员工' }}</h2>
<p>{{ employee.phone || '未填写手机号' }}</p>
<p>{{ employee.phone || '未填写登录手机号' }}</p>
</div>
<button class="edit-btn" type="button" @click="openEdit">
<Pencil :size="15" aria-hidden="true" />
@@ -21,8 +21,9 @@
<div class="field"><label>员工编号</label><div class="field-value">{{ employee.userId || employee.id }}</div></div>
<div class="field"><label>身份/级别</label><div class="field-value">{{ employee.identity || employee.level || '美甲师' }}</div></div>
<div class="field"><label>状态</label><div class="field-value">{{ employee.status === 0 ? '休息中' : '可预约' }}</div></div>
<div class="field"><label>参与生产</label><div class="field-value">{{ employee.participateProduction === 0 ? '不参与' : '参与' }}</div></div>
<div class="field"><label>上班时间</label><div class="field-value">{{ workTimeText }}</div></div>
<div class="field"><label>登录手机号</label><div class="field-value">{{ employee.phone || '未填写' }}</div></div>
<div class="field"><label>联系电话</label><div class="field-value">{{ employee.contactPhone || '未填写' }}</div></div>
<div class="field"><label>微信号</label><div class="field-value">{{ employee.wechatId || '未填写' }}</div></div>
<div class="field"><label>预约颜色</label><div class="field-value color-line"><span class="color-dot" :style="{ backgroundColor: employee.color || '#b8b0a6' }"></span>{{ employee.color || '未设置' }}</div></div>
</section>
@@ -38,12 +39,33 @@
<BaseModal
:model-value="editModalVisible"
title="编辑员工"
:close-disabled="saving"
:close-disabled="closeDisabled"
:has-unsaved-changes="editFormChanged"
@update:model-value="updateEditModalVisible"
>
<div class="modal-form">
<div class="field"><label class="required">姓名</label><input v-model.trim="editForm.nickname" placeholder="请输入姓名" /></div>
<div class="avatar-field">
<div class="avatar-preview" :style="{ backgroundColor: employee?.color || '#e5eee9' }">
<img v-if="editForm.avatar" :src="editForm.avatar" alt="" />
<span v-else>{{ (editForm.nickname || '员').slice(0, 1) }}</span>
</div>
<div class="avatar-actions">
<label class="secondary-btn avatar-upload" :class="{ 'is-disabled': avatarUploading }">
<Upload :size="15" aria-hidden="true" />
<span>{{ avatarUploading ? '上传中' : '上传头像' }}</span>
<input type="file" accept="image/*" :disabled="avatarUploading" @change="uploadAvatar" />
</label>
<button class="secondary-btn" type="button" :disabled="avatarUploading || !editForm.avatar" @click="clearAvatar">
<Trash2 :size="15" aria-hidden="true" />
<span>清除</span>
</button>
</div>
</div>
<div class="field"><label class="required">昵称</label><input v-model.trim="editForm.nickname" placeholder="请输入昵称" /></div>
<div class="field"><label class="required">登录手机号</label><input v-model.trim="editForm.phone" inputmode="tel" placeholder="请输入登录手机号" /></div>
<div class="field"><label>联系电话</label><input v-model.trim="editForm.contactPhone" inputmode="tel" placeholder="请输入联系电话" /></div>
<div class="field"><label class="required">微信号</label><input v-model.trim="editForm.wechatId" placeholder="请输入微信号" /></div>
<div class="field"><label>身份/级别</label><input v-model.trim="editForm.identity" placeholder="例如:高级美甲师" /></div>
<div class="field">
<label>状态</label>
@@ -52,16 +74,30 @@
<option :value="0">休息中</option>
</select>
</div>
<div class="field">
<label>参与生产</label>
<select v-model.number="editForm.participateProduction">
<option :value="1">参与</option>
<option :value="0">不参与</option>
</select>
<div class="reset-panel">
<div>
<strong>重置登录密码</strong>
<p>重置后员工可使用系统默认密码登录。</p>
</div>
<button class="secondary-btn reset-btn" type="button" :disabled="resettingPassword" @click="requestResetPassword">
<KeyRound :size="15" aria-hidden="true" />
<span>重置密码</span>
</button>
</div>
<div class="field"><label>上班开始</label><input v-model="editForm.workStartTime" type="time" /></div>
<div class="field"><label>上班结束</label><input v-model="editForm.workEndTime" type="time" /></div>
<button class="primary-btn" type="button" :disabled="saving" @click="saveEdit">{{ saving ? '保存中...' : '保存员工' }}</button>
<div v-if="resetConfirmVisible" class="reset-confirm">
<p>确定要把该员工密码重置为系统默认密码吗?</p>
<div class="reset-confirm__actions">
<button class="secondary-btn" type="button" :disabled="resettingPassword" @click="resetConfirmVisible = false">取消</button>
<button class="danger-btn" type="button" :disabled="resettingPassword" @click="confirmResetPassword">
{{ resettingPassword ? '重置中...' : '确认重置' }}
</button>
</div>
</div>
<button class="primary-btn" type="button" :disabled="saving || avatarUploading" @click="saveEdit">
{{ saving ? '保存中...' : '保存员工' }}
</button>
</div>
</BaseModal>
</MobileShell>
@@ -70,11 +106,12 @@
<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Pencil } from 'lucide-vue-next'
import { KeyRound, Pencil, Trash2, Upload } from 'lucide-vue-next'
import BaseModal from '@/components/BaseModal.vue'
import EmptyState from '@/components/EmptyState.vue'
import LoadingState from '@/components/LoadingState.vue'
import MobileShell from '@/components/MobileShell.vue'
import { fileApi } from '@/api/file'
import { managerEmployeesApi } from '@/api/managerEmployees'
import { useSessionStore } from '@/stores/session'
import { useToastStore } from '@/stores/toast'
@@ -82,15 +119,17 @@ import type { Artist } from '@/types/manager'
import { readFormModalDraft, removeFormModalDraft, writeFormModalDraft } from '@/utils/form-modal-draft'
interface EditEmployeeForm {
avatar: string
nickname: string
phone: string
contactPhone: string
wechatId: string
identity: string
status: number
participateProduction: number
workStartTime: string
workEndTime: string
}
const EDIT_EMPLOYEE_DRAFT_NAME_PREFIX = 'employee-edit'
const phonePattern = /^1[3-9]\d{9}$/
const route = useRoute()
const router = useRouter()
@@ -98,6 +137,9 @@ const session = useSessionStore()
const toast = useToastStore()
const loading = ref(false)
const saving = ref(false)
const avatarUploading = ref(false)
const resettingPassword = ref(false)
const resetConfirmVisible = ref(false)
const employee = ref<Artist | null>(null)
const editModalVisible = ref(false)
const employeeId = computed(() => String(route.params.id))
@@ -109,80 +151,74 @@ const menus = computed(() => [
{ title: '员工作品/订单', path: `/employees/${employeeId.value}/orders` }
])
const buildEmptyEditForm = (): EditEmployeeForm => ({
avatar: '',
nickname: '',
phone: '',
contactPhone: '',
wechatId: '',
identity: '',
status: 1,
participateProduction: 1,
workStartTime: '',
workEndTime: ''
status: 1
})
const editForm = reactive<EditEmployeeForm>(buildEmptyEditForm())
const originalEditForm = ref<EditEmployeeForm>(buildEmptyEditForm())
const workTimeText = computed(() => {
if (!employee.value?.workStartTime || !employee.value?.workEndTime) {
return '未设置'
}
return `${normalizeTimeText(employee.value.workStartTime)}-${normalizeTimeText(employee.value.workEndTime)}`
})
const editFormChanged = computed(() => !sameEditForm(editForm, originalEditForm.value))
function normalizeTimeText(value: string | null | undefined): string {
if (!value) {
return ''
}
return value.slice(0, 5)
}
const closeDisabled = computed(() => saving.value || avatarUploading.value || resettingPassword.value)
function buildEditFormFromEmployee(value: Artist): EditEmployeeForm {
return {
avatar: value.avatar || '',
nickname: value.nickname || value.name || '',
phone: value.phone || '',
contactPhone: value.contactPhone || '',
wechatId: value.wechatId || '',
identity: value.identity || value.level || '',
status: value.status === 0 ? 0 : 1,
participateProduction: value.participateProduction === 0 ? 0 : 1,
workStartTime: normalizeTimeText(value.workStartTime),
workEndTime: normalizeTimeText(value.workEndTime)
status: value.status === 0 ? 0 : 1
}
}
function sameEditForm(left: EditEmployeeForm, right: EditEmployeeForm): boolean {
return left.nickname === right.nickname
return left.avatar === right.avatar
&& left.nickname === right.nickname
&& left.phone === right.phone
&& left.contactPhone === right.contactPhone
&& left.wechatId === right.wechatId
&& left.identity === right.identity
&& left.status === right.status
&& left.participateProduction === right.participateProduction
&& left.workStartTime === right.workStartTime
&& left.workEndTime === right.workEndTime
}
function snapshotEditForm(): EditEmployeeForm {
return {
avatar: editForm.avatar,
nickname: editForm.nickname,
phone: editForm.phone,
contactPhone: editForm.contactPhone,
wechatId: editForm.wechatId,
identity: editForm.identity,
status: editForm.status,
participateProduction: editForm.participateProduction,
workStartTime: editForm.workStartTime,
workEndTime: editForm.workEndTime
status: editForm.status
}
}
function normalizeEditForm(form: EditEmployeeForm): EditEmployeeForm {
return {
avatar: String(form.avatar || ''),
nickname: String(form.nickname || ''),
phone: String(form.phone || ''),
contactPhone: String(form.contactPhone || ''),
wechatId: String(form.wechatId || ''),
identity: String(form.identity || ''),
status: Number(form.status) === 0 ? 0 : 1,
participateProduction: Number(form.participateProduction) === 0 ? 0 : 1,
workStartTime: normalizeTimeText(String(form.workStartTime || '')),
workEndTime: normalizeTimeText(String(form.workEndTime || ''))
status: Number(form.status) === 0 ? 0 : 1
}
}
function applyEditForm(form: EditEmployeeForm): void {
const normalizedForm = normalizeEditForm(form)
editForm.avatar = normalizedForm.avatar
editForm.nickname = normalizedForm.nickname
editForm.phone = normalizedForm.phone
editForm.contactPhone = normalizedForm.contactPhone
editForm.wechatId = normalizedForm.wechatId
editForm.identity = normalizedForm.identity
editForm.status = normalizedForm.status
editForm.participateProduction = normalizedForm.participateProduction
editForm.workStartTime = normalizedForm.workStartTime
editForm.workEndTime = normalizedForm.workEndTime
}
function resetEditForm(): void {
@@ -219,6 +255,7 @@ function clearEditDraft(): void {
function updateEditModalVisible(value: boolean): void {
editModalVisible.value = value
if (!value) {
resetConfirmVisible.value = false
clearEditDraft()
resetEditForm()
}
@@ -229,36 +266,62 @@ function openEdit(): void {
return
}
clearEditDraft()
resetConfirmVisible.value = false
const form = buildEditFormFromEmployee(employee.value)
applyEditForm(form)
originalEditForm.value = snapshotEditForm()
editModalVisible.value = true
}
function errorMessage(error: { message?: string } | null): string {
return error?.message ? error.message : '员工信息保存失败,请稍后重试'
function errorMessage(error: { message?: string } | null, fallback: string): string {
return error?.message ? error.message : fallback
}
const loadEmployee = async (): Promise<void> => {
loading.value = true
try {
employee.value = await managerEmployeesApi.detail(employeeId.value)
} catch (error) {
toast.error(errorMessage(error as { message?: string } | null, '员工详情加载失败,请稍后重试'))
employee.value = null
} finally {
loading.value = false
}
}
const uploadAvatar = async (event: Event): Promise<void> => {
const target = event.target as HTMLInputElement
const file = target.files?.[0]
target.value = ''
if (!file) {
return
}
avatarUploading.value = true
try {
editForm.avatar = await fileApi.uploadProfileImage(file)
toast.success('头像已上传')
} catch (error) {
toast.error(errorMessage(error as { message?: string } | null, '头像上传失败,请稍后重试'))
} finally {
avatarUploading.value = false
}
}
const clearAvatar = (): void => {
editForm.avatar = ''
}
const validateEditForm = (): boolean => {
if (!editForm.nickname.trim()) {
toast.error('请输入员工姓名')
toast.error('请输入员工昵称')
return false
}
if (Boolean(editForm.workStartTime) !== Boolean(editForm.workEndTime)) {
toast.error('请同时填写上班开始和结束时间')
if (!phonePattern.test(editForm.phone.trim())) {
toast.error('请输入正确的登录手机号')
return false
}
if (editForm.workStartTime && editForm.workEndTime && editForm.workStartTime >= editForm.workEndTime) {
toast.error('上班结束时间必须晚于开始时间')
if (!editForm.wechatId.trim()) {
toast.error('请输入微信号')
return false
}
return true
@@ -271,25 +334,46 @@ const saveEdit = async (): Promise<void> => {
saving.value = true
try {
await managerEmployeesApi.save({
...employee.value,
id: employee.value.id,
userId: employee.value.userId || employeeId.value,
avatar: editForm.avatar.trim(),
nickname: editForm.nickname.trim(),
phone: editForm.phone.trim(),
contactPhone: editForm.contactPhone.trim(),
wechatId: editForm.wechatId.trim(),
identity: editForm.identity.trim(),
status: editForm.status,
participateProduction: editForm.participateProduction,
workStartTime: editForm.workStartTime || null,
workEndTime: editForm.workEndTime || null
status: editForm.status
})
toast.success('员工信息已保存')
updateEditModalVisible(false)
await loadEmployee()
} catch (error) {
toast.error(errorMessage(error as { message?: string } | null))
toast.error(errorMessage(error as { message?: string } | null, '员工信息保存失败,请稍后重试'))
} finally {
saving.value = false
}
}
const requestResetPassword = (): void => {
resetConfirmVisible.value = true
}
const confirmResetPassword = async (): Promise<void> => {
if (!employee.value) {
return
}
resettingPassword.value = true
try {
await managerEmployeesApi.resetPassword(employee.value.userId || employeeId.value)
resetConfirmVisible.value = false
toast.success('密码已重置为系统默认密码')
} catch (error) {
toast.error(errorMessage(error as { message?: string } | null, '密码重置失败,请稍后重试'))
} finally {
resettingPassword.value = false
}
}
onMounted(async () => {
await loadEmployee()
restoreEditDraft()
@@ -324,7 +408,8 @@ watch(editModalVisible, syncEditDraft)
flex: 1;
}
.employee-avatar img {
.employee-avatar img,
.avatar-preview img {
width: 100%;
height: 100%;
object-fit: cover;
@@ -392,4 +477,95 @@ watch(editModalVisible, syncEditDraft)
gap: 12px;
padding: 14px;
}
.avatar-field {
display: flex;
align-items: center;
gap: 14px;
padding: 6px 0 10px;
}
.avatar-preview {
display: grid;
place-items: center;
width: 64px;
height: 64px;
overflow: hidden;
border-radius: 22px;
color: var(--accent);
font-size: 24px;
font-weight: 900;
}
.avatar-actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.avatar-actions .secondary-btn,
.reset-btn {
gap: 6px;
min-height: 36px;
padding: 0 12px;
}
.avatar-upload {
cursor: pointer;
}
.avatar-upload input {
display: none;
}
.avatar-upload.is-disabled {
cursor: not-allowed;
opacity: 0.65;
}
.reset-panel {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 12px;
border: 1px solid var(--border);
border-radius: 8px;
background: rgba(255, 255, 255, 0.7);
}
.reset-panel strong,
.reset-panel p,
.reset-confirm p {
margin: 0;
}
.reset-panel strong {
display: block;
color: var(--ink);
font-size: 14px;
}
.reset-panel p,
.reset-confirm p {
margin-top: 4px;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
.reset-confirm {
display: grid;
gap: 10px;
padding: 12px;
border: 1px solid rgba(191, 73, 73, 0.22);
border-radius: 8px;
background: rgba(191, 73, 73, 0.08);
}
.reset-confirm__actions {
display: flex;
justify-content: flex-end;
gap: 8px;
}
</style>