完成JC-ArtList与JC-Salon端侧清理和统一命名
This commit is contained in:
-213
@@ -1,213 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.artist.service.impl;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleExceptionDTO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleDTO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleRuleDTO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleExceptionDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleRuleDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.ArtistScheduleExceptionMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.ArtistScheduleMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.ArtistScheduleRuleMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.planning.mapper.AppointmentReservationMapper;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalTime;
|
||||
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.eq;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class ArtistScheduleServiceImplTest {
|
||||
|
||||
@Mock
|
||||
private ArtistScheduleMapper scheduleMapper;
|
||||
@Mock
|
||||
private ArtistScheduleRuleMapper ruleMapper;
|
||||
@Mock
|
||||
private ArtistScheduleExceptionMapper exceptionMapper;
|
||||
@Mock
|
||||
private AppointmentReservationMapper reservationMapper;
|
||||
|
||||
private ArtistScheduleServiceImpl service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
service = new ArtistScheduleServiceImpl(scheduleMapper, ruleMapper, exceptionMapper, reservationMapper);
|
||||
when(ruleMapper.selectOne(any())).thenReturn(null);
|
||||
when(exceptionMapper.selectList(any())).thenReturn(List.of());
|
||||
when(scheduleMapper.selectDayScheduleForUpdate(eq(8L), eq(30L), any(LocalDate.class))).thenAnswer(invocation -> existingSchedule(invocation.getArgument(2)));
|
||||
when(reservationMapper.countActiveByArtistAndDateForUpdate(eq(8L), eq(30L), any(LocalDate.class))).thenReturn(0);
|
||||
when(reservationMapper.countActiveOutsideScheduleForUpdate(eq(8L), eq(30L), any(LocalDate.class), any(LocalTime.class), any(LocalTime.class))).thenReturn(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void saveDoubleRestRuleGeneratesWeekdaySchedulesAndWeekendRestRows() {
|
||||
service.saveRule(rule("DOUBLE_REST", List.of(1, 2, 3, 4, 5), LocalTime.of(9, 0), LocalTime.of(17, 0)));
|
||||
|
||||
ArgumentCaptor<Integer> statusCaptor = ArgumentCaptor.forClass(Integer.class);
|
||||
verify(scheduleMapper, org.mockito.Mockito.atLeastOnce()).updateGeneratedSchedule(any(), any(), any(), any(), any(), statusCaptor.capture(), any());
|
||||
assertThat(statusCaptor.getAllValues()).contains(1, 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void saveCustomRuleUsesSelectedWeekdaysOnly() {
|
||||
service.saveRule(rule("CUSTOM", List.of(2, 4), LocalTime.of(10, 0), LocalTime.of(20, 0)));
|
||||
|
||||
ArgumentCaptor<LocalDate> dateCaptor = ArgumentCaptor.forClass(LocalDate.class);
|
||||
ArgumentCaptor<Integer> statusCaptor = ArgumentCaptor.forClass(Integer.class);
|
||||
verify(scheduleMapper, org.mockito.Mockito.atLeastOnce()).selectDayScheduleForUpdate(eq(8L), eq(30L), dateCaptor.capture());
|
||||
verify(scheduleMapper, org.mockito.Mockito.atLeastOnce()).updateGeneratedSchedule(any(), any(), any(), any(), any(), statusCaptor.capture(), any());
|
||||
|
||||
List<LocalDate> dates = dateCaptor.getAllValues();
|
||||
List<Integer> statuses = statusCaptor.getAllValues();
|
||||
for (int index = 0; index < statuses.size(); index++) {
|
||||
DayOfWeek dayOfWeek = dates.get(index).getDayOfWeek();
|
||||
if (List.of(DayOfWeek.TUESDAY, DayOfWeek.THURSDAY).contains(dayOfWeek)) {
|
||||
assertThat(statuses.get(index)).isEqualTo(1);
|
||||
} else {
|
||||
assertThat(statuses.get(index)).isEqualTo(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void saveRestExceptionRejectsDateWithActiveReservation() {
|
||||
LocalDate date = LocalDate.now().plusDays(1L);
|
||||
when(ruleMapper.selectOne(any())).thenReturn(existingRule());
|
||||
when(exceptionMapper.selectOne(any())).thenReturn(null);
|
||||
when(reservationMapper.countActiveByArtistAndDateForUpdate(8L, 30L, date)).thenReturn(2);
|
||||
|
||||
assertThatThrownBy(() -> service.saveException(restException(date)))
|
||||
.isInstanceOf(RuntimeException.class)
|
||||
.hasMessageContaining(date.toString())
|
||||
.hasMessageContaining("2");
|
||||
|
||||
verify(exceptionMapper).insert(any(ArtistScheduleExceptionDO.class));
|
||||
verify(scheduleMapper, never()).updateGeneratedSchedule(any(), any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void saveExtraWorkExceptionGeneratesWorkingScheduleOnRestDay() {
|
||||
LocalDate sunday = next(DayOfWeek.SUNDAY);
|
||||
when(ruleMapper.selectOne(any())).thenReturn(existingRule());
|
||||
when(exceptionMapper.selectOne(any())).thenReturn(null);
|
||||
|
||||
service.saveException(extraWorkException(sunday));
|
||||
|
||||
verify(scheduleMapper).updateGeneratedSchedule(any(), eq(LocalTime.of(10, 0)), eq(LocalTime.of(18, 0)), eq(60), eq(1), eq(1), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void saveRuleUsesInternalCapacityAndSlotDefaults() {
|
||||
service.saveRule(rule("DOUBLE_REST", List.of(1, 2, 3, 4, 5), LocalTime.of(9, 0), LocalTime.of(17, 0)));
|
||||
|
||||
ArgumentCaptor<Integer> slotCaptor = ArgumentCaptor.forClass(Integer.class);
|
||||
ArgumentCaptor<Integer> capacityCaptor = ArgumentCaptor.forClass(Integer.class);
|
||||
verify(scheduleMapper, org.mockito.Mockito.atLeastOnce()).updateGeneratedSchedule(any(), any(), any(), slotCaptor.capture(), capacityCaptor.capture(), any(), any());
|
||||
assertThat(slotCaptor.getAllValues()).allMatch(value -> value == 60);
|
||||
assertThat(capacityCaptor.getAllValues()).allMatch(value -> value == 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void saveScheduleUpdatesExistingSlotInsteadOfDuplicatingGeneratedRow() {
|
||||
LocalDate date = LocalDate.now().plusDays(1L);
|
||||
ArtistScheduleDTO dto = new ArtistScheduleDTO();
|
||||
dto.setShopId(8L);
|
||||
dto.setArtistId(30L);
|
||||
dto.setWorkDate(date);
|
||||
dto.setStartTime(LocalTime.of(9, 0));
|
||||
dto.setEndTime(LocalTime.of(19, 0));
|
||||
dto.setSlotMinutes(30);
|
||||
dto.setCapacity(3);
|
||||
dto.setStatus(1);
|
||||
when(scheduleMapper.selectSlotScheduleForUpdate(8L, 30L, date, LocalTime.of(9, 0))).thenReturn(existingSchedule(date));
|
||||
|
||||
service.saveSchedule(dto);
|
||||
|
||||
verify(scheduleMapper, never()).insert(any(ArtistScheduleDO.class));
|
||||
verify(scheduleMapper).updateGeneratedSchedule(any(), eq(LocalTime.of(9, 0)), eq(LocalTime.of(19, 0)), eq(30), eq(3), eq(1), any());
|
||||
}
|
||||
|
||||
private ArtistScheduleRuleDTO rule(String presetType, List<Integer> workDays, LocalTime startTime, LocalTime endTime) {
|
||||
ArtistScheduleRuleDTO dto = new ArtistScheduleRuleDTO();
|
||||
dto.setShopId(8L);
|
||||
dto.setArtistId(30L);
|
||||
dto.setPresetType(presetType);
|
||||
dto.setWorkDays(workDays);
|
||||
dto.setStartTime(startTime);
|
||||
dto.setEndTime(endTime);
|
||||
return dto;
|
||||
}
|
||||
|
||||
private ArtistScheduleExceptionDTO restException(LocalDate date) {
|
||||
ArtistScheduleExceptionDTO dto = new ArtistScheduleExceptionDTO();
|
||||
dto.setShopId(8L);
|
||||
dto.setArtistId(30L);
|
||||
dto.setWorkDate(date);
|
||||
dto.setExceptionType("REST");
|
||||
return dto;
|
||||
}
|
||||
|
||||
private ArtistScheduleExceptionDTO extraWorkException(LocalDate date) {
|
||||
ArtistScheduleExceptionDTO dto = new ArtistScheduleExceptionDTO();
|
||||
dto.setShopId(8L);
|
||||
dto.setArtistId(30L);
|
||||
dto.setWorkDate(date);
|
||||
dto.setExceptionType("EXTRA_WORK");
|
||||
dto.setStartTime(LocalTime.of(10, 0));
|
||||
dto.setEndTime(LocalTime.of(18, 0));
|
||||
return dto;
|
||||
}
|
||||
|
||||
private ArtistScheduleRuleDO existingRule() {
|
||||
ArtistScheduleRuleDO rule = new ArtistScheduleRuleDO();
|
||||
rule.setId(1L);
|
||||
rule.setShopId(8L);
|
||||
rule.setArtistId(30L);
|
||||
rule.setPresetType("DOUBLE_REST");
|
||||
rule.setWorkDays("1,2,3,4,5");
|
||||
rule.setStartTime(LocalTime.of(9, 0));
|
||||
rule.setEndTime(LocalTime.of(17, 0));
|
||||
rule.setSlotMinutes(60);
|
||||
rule.setCapacity(1);
|
||||
rule.setStatus(1);
|
||||
rule.setIsDelete(0);
|
||||
return rule;
|
||||
}
|
||||
|
||||
private ArtistScheduleDO existingSchedule(LocalDate date) {
|
||||
ArtistScheduleDO schedule = new ArtistScheduleDO();
|
||||
schedule.setId(1000L + date.getDayOfYear());
|
||||
schedule.setShopId(8L);
|
||||
schedule.setArtistId(30L);
|
||||
schedule.setWorkDate(date);
|
||||
schedule.setStartTime(LocalTime.of(9, 0));
|
||||
schedule.setEndTime(LocalTime.of(17, 0));
|
||||
schedule.setSlotMinutes(60);
|
||||
schedule.setCapacity(1);
|
||||
schedule.setStatus(1);
|
||||
schedule.setIsDelete(0);
|
||||
return schedule;
|
||||
}
|
||||
|
||||
private LocalDate next(DayOfWeek dayOfWeek) {
|
||||
LocalDate cursor = LocalDate.now();
|
||||
while (cursor.getDayOfWeek() != dayOfWeek) {
|
||||
cursor = cursor.plusDays(1L);
|
||||
}
|
||||
return cursor;
|
||||
}
|
||||
}
|
||||
-292
@@ -1,292 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.artist.service.impl;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.entity.NailArtistInfoDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderArtistReviewDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderItemDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.entity.ProductDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.entity.ShopDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.NailArtistInfoMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.planning.mapper.AppointmentReservationMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.ArtistScheduleMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderArtistReviewMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderItemMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.mapper.ProductMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.ShopMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageFileService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.file.support.ObjectStorageUrlSupport;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.support.UserShopBindingSupport;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.NailArtistAvailabilityVO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.NailArtistProfileVO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.NailArtistReviewVO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.file.vo.ObjectStorageFileVO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.vo.ShopSimpleVO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class NailArtistInfoServiceImplTest {
|
||||
|
||||
@Mock
|
||||
private NailArtistInfoMapper nailArtistInfoMapper;
|
||||
@Mock
|
||||
private UserMapper userMapper;
|
||||
@Mock
|
||||
private ShopMapper shopMapper;
|
||||
@Mock
|
||||
private UserShopBindingSupport userShopBindingSupport;
|
||||
@Mock
|
||||
private ProductMapper productMapper;
|
||||
@Mock
|
||||
private OrderMapper orderMapper;
|
||||
@Mock
|
||||
private OrderItemMapper orderItemMapper;
|
||||
@Mock
|
||||
private OrderArtistReviewMapper orderArtistReviewMapper;
|
||||
@Mock
|
||||
private ObjectStorageFileService objectStorageFileService;
|
||||
@Mock
|
||||
private ObjectStorageUrlSupport objectStorageUrlSupport;
|
||||
@Mock
|
||||
private ArtistScheduleMapper artistScheduleMapper;
|
||||
@Mock
|
||||
private AppointmentReservationMapper appointmentReservationMapper;
|
||||
|
||||
private NailArtistInfoServiceImpl service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
service = new NailArtistInfoServiceImpl();
|
||||
ReflectionTestUtils.setField(service, "baseMapper", nailArtistInfoMapper);
|
||||
ReflectionTestUtils.setField(service, "userMapper", userMapper);
|
||||
ReflectionTestUtils.setField(service, "shopMapper", shopMapper);
|
||||
ReflectionTestUtils.setField(service, "userShopBindingSupport", userShopBindingSupport);
|
||||
ReflectionTestUtils.setField(service, "productMapper", productMapper);
|
||||
ReflectionTestUtils.setField(service, "orderMapper", orderMapper);
|
||||
ReflectionTestUtils.setField(service, "orderItemMapper", orderItemMapper);
|
||||
ReflectionTestUtils.setField(service, "orderArtistReviewMapper", orderArtistReviewMapper);
|
||||
ReflectionTestUtils.setField(service, "objectStorageFileService", objectStorageFileService);
|
||||
ReflectionTestUtils.setField(service, "objectStorageUrlSupport", objectStorageUrlSupport);
|
||||
ReflectionTestUtils.setField(service, "artistScheduleMapper", artistScheduleMapper);
|
||||
ReflectionTestUtils.setField(service, "appointmentReservationMapper", appointmentReservationMapper);
|
||||
when(userShopBindingSupport.listShopOptionsByUserId(any(), anyBoolean(), anyBoolean())).thenReturn(List.of());
|
||||
when(objectStorageUrlSupport.toAccessibleUrl(any(ObjectStorageFileVO.class)))
|
||||
.thenAnswer(invocation -> invocation.getArgument(0, ObjectStorageFileVO.class).getFileUrl());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getPublicProfileAggregatesArtistBasicsWorksReviewsAndAvailability() {
|
||||
NailArtistInfoDO artistInfo = new NailArtistInfoDO();
|
||||
artistInfo.setId(11L);
|
||||
artistInfo.setUserId(7L);
|
||||
artistInfo.setIdentity("Yumi senior artist");
|
||||
artistInfo.setExperience(5);
|
||||
artistInfo.setSkills("法式,猫眼");
|
||||
artistInfo.setRating(new BigDecimal("4.7"));
|
||||
artistInfo.setStatus(1);
|
||||
artistInfo.setPortfolio("31");
|
||||
artistInfo.setWorkStartTime(LocalTime.of(10, 0));
|
||||
artistInfo.setWorkEndTime(LocalTime.of(12, 0));
|
||||
artistInfo.setIsDelete(0);
|
||||
when(nailArtistInfoMapper.selectOne(any())).thenReturn(artistInfo);
|
||||
|
||||
UserDO artist = new UserDO();
|
||||
artist.setId(7L);
|
||||
artist.setNickname("Mina");
|
||||
artist.setAvatar("https://img.test/mina.jpg");
|
||||
artist.setSignature("Clean lines and soft colors");
|
||||
artist.setType(3);
|
||||
artist.setShopId(9L);
|
||||
artist.setIsDelete(0);
|
||||
when(userMapper.selectById(7L)).thenReturn(artist);
|
||||
|
||||
ShopDO shop = new ShopDO();
|
||||
shop.setId(9L);
|
||||
shop.setShopName("Yumi Test Shop");
|
||||
when(shopMapper.selectById(9L)).thenReturn(shop);
|
||||
when(userShopBindingSupport.listShopOptionsByUserId(7L, true, true)).thenReturn(List.of());
|
||||
|
||||
ProductDO product = new ProductDO();
|
||||
product.setId(31L);
|
||||
product.setShopId(9L);
|
||||
product.setTitle("Soft French");
|
||||
product.setPrice(new BigDecimal("168.00"));
|
||||
product.setImageFileIds("201");
|
||||
product.setTags("通勤;显白");
|
||||
product.setIsDelete(0);
|
||||
when(productMapper.selectBatchIds(any())).thenReturn(List.of(product));
|
||||
|
||||
ObjectStorageFileVO productImage = new ObjectStorageFileVO();
|
||||
productImage.setId(201L);
|
||||
productImage.setFileUrl("https://img.test/product.jpg");
|
||||
when(objectStorageFileService.getObjectStorageFileMapByIds(any())).thenReturn(Map.of(201L, productImage));
|
||||
|
||||
OrderDO completedOrder = new OrderDO();
|
||||
completedOrder.setId(41L);
|
||||
completedOrder.setStatus(2);
|
||||
completedOrder.setIsDelete(0);
|
||||
when(orderMapper.selectByArtistId(7L)).thenReturn(List.of(completedOrder));
|
||||
|
||||
OrderItemDO servedItem = new OrderItemDO();
|
||||
servedItem.setId(51L);
|
||||
servedItem.setOrderId(41L);
|
||||
servedItem.setArtistId(7L);
|
||||
servedItem.setProductId(31L);
|
||||
servedItem.setQuantity(2);
|
||||
servedItem.setIsDelete(0);
|
||||
when(orderItemMapper.selectByOrderId(41L)).thenReturn(List.of(servedItem));
|
||||
when(orderItemMapper.selectArtistCalendarItems(any(), any(), any())).thenReturn(List.of());
|
||||
|
||||
OrderArtistReviewDO submitted = new OrderArtistReviewDO();
|
||||
submitted.setId(61L);
|
||||
submitted.setArtistId(7L);
|
||||
submitted.setCustomerId(71L);
|
||||
submitted.setProductId(31L);
|
||||
submitted.setRatingScore(new BigDecimal("5.0"));
|
||||
submitted.setContent("Lines are precise");
|
||||
submitted.setStatus(1);
|
||||
submitted.setSubmittedAt(LocalDateTime.now().minusDays(1));
|
||||
submitted.setIsDelete(0);
|
||||
when(orderArtistReviewMapper.selectList(any())).thenReturn(List.of(submitted));
|
||||
when(orderArtistReviewMapper.selectAverageSubmittedRatingByArtistId(7L)).thenReturn(new BigDecimal("5.0"));
|
||||
|
||||
UserDO customer = new UserDO();
|
||||
customer.setId(71L);
|
||||
customer.setNickname("Ava");
|
||||
when(userMapper.selectBatchIds(List.of(71L))).thenReturn(List.of(customer));
|
||||
|
||||
NailArtistProfileVO profile = service.getPublicProfile(7L);
|
||||
|
||||
assertThat(profile.getArtistId()).isEqualTo(7L);
|
||||
assertThat(profile.getArtistName()).isEqualTo("Mina");
|
||||
assertThat(profile.getShopName()).isEqualTo("Yumi Test Shop");
|
||||
assertThat(profile.getStyleTags()).containsExactly("法式", "猫眼");
|
||||
assertThat(profile.getRating()).isEqualByComparingTo("5.0");
|
||||
assertThat(profile.getServiceCount()).isEqualTo(2L);
|
||||
assertThat(profile.getWorks()).hasSize(1);
|
||||
assertThat(profile.getWorks().get(0).getCoverImageUrl()).isEqualTo("https://img.test/product.jpg");
|
||||
assertThat(profile.getReviews()).hasSize(1);
|
||||
assertThat(profile.getReviews().get(0).getCustomerName()).isEqualTo("Ava");
|
||||
assertThat(profile.getAvailability()).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void listPublicReviewsReturnsSubmittedReviewsOnly() {
|
||||
OrderArtistReviewDO submitted = new OrderArtistReviewDO();
|
||||
submitted.setId(61L);
|
||||
submitted.setArtistId(7L);
|
||||
submitted.setCustomerId(71L);
|
||||
submitted.setRatingScore(new BigDecimal("4.5"));
|
||||
submitted.setContent("Gentle and detailed");
|
||||
submitted.setStatus(1);
|
||||
submitted.setSubmittedAt(LocalDateTime.now().minusHours(2));
|
||||
submitted.setIsDelete(0);
|
||||
when(orderArtistReviewMapper.selectList(any())).thenReturn(List.of(submitted));
|
||||
|
||||
UserDO customer = new UserDO();
|
||||
customer.setId(71L);
|
||||
customer.setNickname("Ava");
|
||||
when(userMapper.selectBatchIds(List.of(71L))).thenReturn(List.of(customer));
|
||||
|
||||
List<NailArtistReviewVO> reviews = service.listPublicReviews(7L);
|
||||
|
||||
assertThat(reviews).hasSize(1);
|
||||
assertThat(reviews.get(0).getRating()).isEqualByComparingTo("4.5");
|
||||
assertThat(reviews.get(0).getContent()).isEqualTo("Gentle and detailed");
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAvailabilitySkipsBookedSlots() {
|
||||
NailArtistInfoDO artistInfo = new NailArtistInfoDO();
|
||||
artistInfo.setUserId(7L);
|
||||
artistInfo.setStatus(1);
|
||||
artistInfo.setWorkStartTime(LocalTime.of(10, 0));
|
||||
artistInfo.setWorkEndTime(LocalTime.of(12, 0));
|
||||
artistInfo.setIsDelete(0);
|
||||
when(nailArtistInfoMapper.selectOne(any())).thenReturn(artistInfo);
|
||||
UserDO artist = new UserDO();
|
||||
artist.setId(7L);
|
||||
artist.setType(3);
|
||||
artist.setIsDelete(0);
|
||||
when(userMapper.selectById(7L)).thenReturn(artist);
|
||||
|
||||
OrderItemDO booked = new OrderItemDO();
|
||||
booked.setArtistId(7L);
|
||||
booked.setAppointmentTime(LocalDateTime.now().plusDays(1).withHour(10).withMinute(0).withSecond(0).withNano(0));
|
||||
when(orderItemMapper.selectArtistCalendarItems(any(), any(), any())).thenReturn(List.of(booked));
|
||||
|
||||
List<NailArtistAvailabilityVO> slots = service.getAvailability(7L);
|
||||
|
||||
assertThat(slots).isNotEmpty();
|
||||
assertThat(slots)
|
||||
.noneMatch(slot -> slot.getStartTime().toLocalDate().equals(booked.getAppointmentTime().toLocalDate())
|
||||
&& slot.getStartTime().toLocalTime().equals(LocalTime.of(10, 0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAvailabilityUsesScheduleCapacityWhenConfigured() {
|
||||
NailArtistInfoDO artistInfo = new NailArtistInfoDO();
|
||||
artistInfo.setUserId(7L);
|
||||
artistInfo.setStatus(1);
|
||||
artistInfo.setWorkStartTime(LocalTime.of(10, 0));
|
||||
artistInfo.setWorkEndTime(LocalTime.of(12, 0));
|
||||
artistInfo.setIsDelete(0);
|
||||
when(nailArtistInfoMapper.selectOne(any())).thenReturn(artistInfo);
|
||||
UserDO artist = new UserDO();
|
||||
artist.setId(7L);
|
||||
artist.setType(3);
|
||||
artist.setShopId(9L);
|
||||
artist.setIsDelete(0);
|
||||
when(userMapper.selectById(7L)).thenReturn(artist);
|
||||
|
||||
ShopDO shop = new ShopDO();
|
||||
shop.setId(9L);
|
||||
shop.setShopName("Yumi Test Shop");
|
||||
ShopSimpleVO shopOption = new ShopSimpleVO();
|
||||
shopOption.setId(9L);
|
||||
shopOption.setShopName("Yumi Test Shop");
|
||||
when(shopMapper.selectById(9L)).thenReturn(shop);
|
||||
when(userShopBindingSupport.listShopOptionsByUserId(7L, true, true)).thenReturn(List.of(shopOption));
|
||||
|
||||
LocalDate workDate = LocalDate.now().plusDays(1);
|
||||
ArtistScheduleDO schedule = new ArtistScheduleDO();
|
||||
schedule.setShopId(9L);
|
||||
schedule.setArtistId(7L);
|
||||
schedule.setWorkDate(workDate);
|
||||
schedule.setStartTime(LocalTime.of(10, 0));
|
||||
schedule.setEndTime(LocalTime.of(12, 0));
|
||||
schedule.setSlotMinutes(60);
|
||||
schedule.setCapacity(1);
|
||||
schedule.setStatus(1);
|
||||
schedule.setIsDelete(0);
|
||||
when(artistScheduleMapper.selectList(any())).thenReturn(List.of(schedule));
|
||||
when(appointmentReservationMapper.countOverlappingActive(any(), any(), any()))
|
||||
.thenReturn(1)
|
||||
.thenReturn(0);
|
||||
|
||||
List<NailArtistAvailabilityVO> slots = service.getAvailability(7L);
|
||||
|
||||
assertThat(slots).hasSize(1);
|
||||
assertThat(slots.get(0).getStartTime().toLocalDate()).isEqualTo(workDate);
|
||||
assertThat(slots.get(0).getStartTime().toLocalTime()).isEqualTo(LocalTime.of(11, 0));
|
||||
}
|
||||
}
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.file;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.modules.file.config.AliyunOssConfig;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class FileObjectStorageConfigurationTest {
|
||||
|
||||
@Test
|
||||
void aliyunOssConfigDoesNotHardCodeEnvironmentValues() {
|
||||
AliyunOssConfig config = new AliyunOssConfig();
|
||||
|
||||
assertThat(config.getBucketName()).isNull();
|
||||
assertThat(config.getSignedUrlExpireMinutes()).isNull();
|
||||
}
|
||||
}
|
||||
-96
@@ -1,96 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.file.controller.front;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.common.Result;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageFileService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.file.support.ObjectStorageUrlSupport;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.file.vo.ObjectStorageFileVO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.mapper.EffectDiagramMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.mapper.ProductMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.ShopMapper;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class FrontendFileControllerTest {
|
||||
|
||||
private ObjectStorageFileService objectStorageFileService;
|
||||
private ObjectStorageUrlSupport objectStorageUrlSupport;
|
||||
private ProductMapper productMapper;
|
||||
private ShopMapper shopMapper;
|
||||
private EffectDiagramMapper effectDiagramMapper;
|
||||
private FrontendFileController controller;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
objectStorageFileService = mock(ObjectStorageFileService.class);
|
||||
objectStorageUrlSupport = mock(ObjectStorageUrlSupport.class);
|
||||
productMapper = mock(ProductMapper.class);
|
||||
shopMapper = mock(ShopMapper.class);
|
||||
effectDiagramMapper = mock(EffectDiagramMapper.class);
|
||||
controller = new FrontendFileController(
|
||||
objectStorageFileService,
|
||||
objectStorageUrlSupport,
|
||||
productMapper,
|
||||
shopMapper,
|
||||
effectDiagramMapper
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSignedUrlRejectsAvailableFileWhenItIsNotPubliclyReferenced() throws Exception {
|
||||
ObjectStorageFileVO file = file();
|
||||
when(objectStorageFileService.getObjectStorageFileById(12L)).thenReturn(file);
|
||||
when(productMapper.countPublicImageReference(12L)).thenReturn(0L);
|
||||
when(shopMapper.countPublicImageReference(12L)).thenReturn(0L);
|
||||
when(effectDiagramMapper.countPublicImageReference(12L)).thenReturn(0L);
|
||||
|
||||
Result<String> result = controller.getSignedUrl(12L, 60);
|
||||
|
||||
assertThat(result.getCode()).isNotEqualTo(200);
|
||||
verify(objectStorageUrlSupport, never()).toAccessibleUrl(any(ObjectStorageFileVO.class), anyInt());
|
||||
verify(objectStorageUrlSupport, never()).getSignedUrlOrThrow(any(ObjectStorageFileVO.class), anyInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSignedUrlAllowsPublicProductImageReference() throws Exception {
|
||||
ObjectStorageFileVO file = file();
|
||||
file.setObjectName("public/a.png");
|
||||
when(objectStorageFileService.getObjectStorageFileById(12L)).thenReturn(file);
|
||||
when(productMapper.countPublicImageReference(12L)).thenReturn(1L);
|
||||
when(objectStorageUrlSupport.getSignedUrlOrThrow(file, 30)).thenReturn("https://signed.test/public/a.png");
|
||||
|
||||
Result<String> result = controller.getSignedUrl(12L, 30);
|
||||
|
||||
assertThat(result.getCode()).isEqualTo(200);
|
||||
assertThat(result.getData()).isEqualTo("https://signed.test/public/a.png");
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSignedUrlFallsBackToOriginalPublicExternalUrlWhenObjectNameCannotBeExtracted() throws Exception {
|
||||
ObjectStorageFileVO file = file();
|
||||
file.setFileUrl("https://acceptance.local/images/public-a.png");
|
||||
when(objectStorageFileService.getObjectStorageFileById(12L)).thenReturn(file);
|
||||
when(productMapper.countPublicImageReference(12L)).thenReturn(1L);
|
||||
|
||||
Result<String> result = controller.getSignedUrl(12L, 30);
|
||||
|
||||
assertThat(result.getCode()).isEqualTo(200);
|
||||
assertThat(result.getData()).isEqualTo("https://acceptance.local/images/public-a.png");
|
||||
verify(objectStorageUrlSupport, never()).getSignedUrlOrThrow(any(ObjectStorageFileVO.class), anyInt());
|
||||
}
|
||||
|
||||
private ObjectStorageFileVO file() {
|
||||
ObjectStorageFileVO file = new ObjectStorageFileVO();
|
||||
file.setId(12L);
|
||||
file.setStatus(1);
|
||||
file.setFileUrl("https://cdn.test/public/a.png");
|
||||
return file;
|
||||
}
|
||||
}
|
||||
-67
@@ -1,67 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.file.scheduler;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.Wrapper;
|
||||
import com.xiaowang.fingertipdesigner.core.config.ObjectStorageProperties;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.file.entity.ObjectStorageReplicaDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.file.mapper.ObjectStorageReplicaMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageBackupService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class ObjectStorageBackupRetrySchedulerTest {
|
||||
|
||||
private ObjectStorageReplicaMapper objectStorageReplicaMapper;
|
||||
private ObjectStorageBackupService objectStorageBackupService;
|
||||
private ObjectStorageBackupRetryScheduler scheduler;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
objectStorageReplicaMapper = mock(ObjectStorageReplicaMapper.class);
|
||||
objectStorageBackupService = mock(ObjectStorageBackupService.class);
|
||||
scheduler = new ObjectStorageBackupRetryScheduler(
|
||||
objectStorageReplicaMapper,
|
||||
objectStorageBackupService,
|
||||
objectStorageProperties()
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void retryPendingOrFailedBackupsScansRetryableFilesAndDispatchesBackup() {
|
||||
ObjectStorageReplicaDO pending = new ObjectStorageReplicaDO();
|
||||
pending.setFileId(1L);
|
||||
ObjectStorageReplicaDO failed = new ObjectStorageReplicaDO();
|
||||
failed.setFileId(2L);
|
||||
when(objectStorageReplicaMapper.selectList(any())).thenReturn(List.of(pending, failed));
|
||||
|
||||
scheduler.retryPendingOrFailedBackups();
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<Wrapper<ObjectStorageReplicaDO>> captor = ArgumentCaptor.forClass(Wrapper.class);
|
||||
verify(objectStorageReplicaMapper).selectList(captor.capture());
|
||||
assertThat(captor.getValue()).isNotNull();
|
||||
verify(objectStorageBackupService).backupFile(1L);
|
||||
verify(objectStorageBackupService).backupFile(2L);
|
||||
}
|
||||
|
||||
private ObjectStorageProperties objectStorageProperties() {
|
||||
ObjectStorageProperties properties = new ObjectStorageProperties();
|
||||
properties.setPrimaryProvider("QINIU_KODO");
|
||||
properties.setBackupProvider("ALIYUN_OSS");
|
||||
properties.setSignedUrlExpireMinutes(60);
|
||||
properties.setBackupQueueName("test.queue");
|
||||
properties.setBackupExchangeName("test.exchange");
|
||||
properties.setBackupRoutingKey("test.routing");
|
||||
properties.setBackupRetryBatchLimit(500);
|
||||
properties.setBackupRetryCron("0 0 2 * * ?");
|
||||
return properties;
|
||||
}
|
||||
}
|
||||
-88
@@ -1,88 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.file.service.impl;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.modules.file.entity.ObjectStorageFileDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.file.mapper.ObjectStorageFileMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageFileService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageOrchestrationService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class ObjectStorageBackupServiceImplTest {
|
||||
|
||||
private ObjectStorageFileMapper objectStorageFileMapper;
|
||||
private ObjectStorageOrchestrationService objectStorageOrchestrationService;
|
||||
private ObjectStorageFileService objectStorageFileService;
|
||||
private ObjectStorageBackupServiceImpl service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
objectStorageFileMapper = mock(ObjectStorageFileMapper.class);
|
||||
objectStorageOrchestrationService = mock(ObjectStorageOrchestrationService.class);
|
||||
objectStorageFileService = mock(ObjectStorageFileService.class);
|
||||
service = new ObjectStorageBackupServiceImpl(
|
||||
objectStorageFileMapper,
|
||||
objectStorageOrchestrationService,
|
||||
objectStorageFileService
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void backupFileMarksFileSucceededAfterCompletingReplicas() {
|
||||
ObjectStorageFileDO file = activePrimaryFile();
|
||||
when(objectStorageFileMapper.selectById(88L)).thenReturn(file);
|
||||
|
||||
service.backupFile(88L);
|
||||
|
||||
verify(objectStorageOrchestrationService).completeReplicas(file);
|
||||
ArgumentCaptor<ObjectStorageFileDO> captor = ArgumentCaptor.forClass(ObjectStorageFileDO.class);
|
||||
verify(objectStorageFileMapper).updateById(captor.capture());
|
||||
ObjectStorageFileDO updated = captor.getValue();
|
||||
assertThat(updated.getId()).isEqualTo(88L);
|
||||
assertThat(updated.getBackupUploadStatus()).isEqualTo(1);
|
||||
assertThat(updated.getBackupUploadedAt()).isNotNull();
|
||||
assertThat(updated.getBackupLastError()).isNull();
|
||||
verify(objectStorageFileService).evictObjectStorageFileCache(88L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void backupFileMarksFileFailedAndTruncatesErrorWhenReplicaCompletionFails() {
|
||||
ObjectStorageFileDO file = activePrimaryFile();
|
||||
file.setBackupRetryCount(2);
|
||||
when(objectStorageFileMapper.selectById(88L)).thenReturn(file);
|
||||
doThrow(new IllegalStateException("x".repeat(700)))
|
||||
.when(objectStorageOrchestrationService)
|
||||
.completeReplicas(file);
|
||||
|
||||
service.backupFile(88L);
|
||||
|
||||
ArgumentCaptor<ObjectStorageFileDO> captor = ArgumentCaptor.forClass(ObjectStorageFileDO.class);
|
||||
verify(objectStorageFileMapper).updateById(captor.capture());
|
||||
ObjectStorageFileDO updated = captor.getValue();
|
||||
assertThat(updated.getBackupUploadStatus()).isEqualTo(2);
|
||||
assertThat(updated.getBackupRetryCount()).isEqualTo(3);
|
||||
assertThat(updated.getBackupLastRetryTime()).isNotNull();
|
||||
assertThat(updated.getBackupLastError()).hasSizeLessThanOrEqualTo(500);
|
||||
verify(objectStorageFileService).evictObjectStorageFileCache(88L);
|
||||
}
|
||||
|
||||
private ObjectStorageFileDO activePrimaryFile() {
|
||||
ObjectStorageFileDO file = new ObjectStorageFileDO();
|
||||
file.setId(88L);
|
||||
file.setStatus(1);
|
||||
file.setObjectName("product/a.png");
|
||||
file.setPrimaryProvider("QINIU_KODO");
|
||||
file.setBackupProvider("ALIYUN_OSS");
|
||||
file.setPrimaryUploadStatus(1);
|
||||
file.setBackupUploadStatus(0);
|
||||
file.setContentType("image/png");
|
||||
file.setFileSize(3L);
|
||||
return file;
|
||||
}
|
||||
}
|
||||
-91
@@ -1,91 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.file.service.impl;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.config.AppCacheProperties;
|
||||
import com.xiaowang.fingertipdesigner.core.config.ObjectStorageProperties;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.file.dto.ObjectStorageFileDTO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.file.entity.ObjectStorageFileDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.file.mapper.ObjectStorageFileMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.file.mq.ObjectStorageBackupMessagePublisher;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageReplicaService;
|
||||
import com.xiaowang.fingertipdesigner.core.support.cache.MultiLevelCacheService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class ObjectStorageFileServiceImplTest {
|
||||
|
||||
private ObjectStorageFileMapper objectStorageFileMapper;
|
||||
private ObjectStorageBackupMessagePublisher objectStorageBackupMessagePublisher;
|
||||
private ObjectStorageReplicaService objectStorageReplicaService;
|
||||
private ObjectStorageFileServiceImpl service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
objectStorageFileMapper = mock(ObjectStorageFileMapper.class);
|
||||
MultiLevelCacheService multiLevelCacheService = mock(MultiLevelCacheService.class);
|
||||
AppCacheProperties appCacheProperties = new AppCacheProperties();
|
||||
objectStorageBackupMessagePublisher = mock(ObjectStorageBackupMessagePublisher.class);
|
||||
objectStorageReplicaService = mock(ObjectStorageReplicaService.class);
|
||||
service = new ObjectStorageFileServiceImpl(
|
||||
objectStorageFileMapper,
|
||||
multiLevelCacheService,
|
||||
appCacheProperties,
|
||||
objectStorageBackupMessagePublisher,
|
||||
objectStorageProperties(),
|
||||
objectStorageReplicaService
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createObjectStorageFilePublishesBackupMessageAfterPrimaryUploadSucceeded() {
|
||||
when(objectStorageFileMapper.insert(any(ObjectStorageFileDO.class))).thenAnswer(invocation -> {
|
||||
ObjectStorageFileDO file = invocation.getArgument(0);
|
||||
file.setId(66L);
|
||||
return 1;
|
||||
});
|
||||
|
||||
ObjectStorageFileDTO dto = new ObjectStorageFileDTO();
|
||||
dto.setFileName("a.png");
|
||||
dto.setFileUrl("https://cdn.test/product/a.png");
|
||||
dto.setObjectName("product/a.png");
|
||||
dto.setPrimaryProvider("QINIU_KODO");
|
||||
dto.setPrimaryUrl(dto.getFileUrl());
|
||||
dto.setBackupProvider("ALIYUN_OSS");
|
||||
dto.setContentType("image/png");
|
||||
dto.setFileSize(3L);
|
||||
dto.setStatus(1);
|
||||
dto.setPrimaryUploadStatus(1);
|
||||
dto.setBackupUploadStatus(0);
|
||||
dto.setBackupRetryCount(0);
|
||||
|
||||
Long fileId = service.createObjectStorageFile(dto);
|
||||
|
||||
assertThat(fileId).isEqualTo(66L);
|
||||
ArgumentCaptor<ObjectStorageFileDO> captor = ArgumentCaptor.forClass(ObjectStorageFileDO.class);
|
||||
verify(objectStorageFileMapper).insert(captor.capture());
|
||||
assertThat(captor.getValue().getObjectName()).isEqualTo("product/a.png");
|
||||
assertThat(captor.getValue().getPrimaryUploadStatus()).isEqualTo(1);
|
||||
assertThat(captor.getValue().getBackupUploadStatus()).isEqualTo(0);
|
||||
verify(objectStorageReplicaService).saveInitialReplicas(66L, dto.getUploadAttempts());
|
||||
verify(objectStorageBackupMessagePublisher).publish(66L);
|
||||
}
|
||||
|
||||
private ObjectStorageProperties objectStorageProperties() {
|
||||
ObjectStorageProperties properties = new ObjectStorageProperties();
|
||||
properties.setPrimaryProvider("QINIU_KODO");
|
||||
properties.setBackupProvider("ALIYUN_OSS");
|
||||
properties.setSignedUrlExpireMinutes(60);
|
||||
properties.setBackupQueueName("test.queue");
|
||||
properties.setBackupExchangeName("test.exchange");
|
||||
properties.setBackupRoutingKey("test.routing");
|
||||
properties.setBackupRetryBatchLimit(500);
|
||||
properties.setBackupRetryCron("0 0 2 * * ?");
|
||||
return properties;
|
||||
}
|
||||
}
|
||||
-153
@@ -1,153 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.file.support;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.config.ObjectStorageProperties;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.file.config.QiniuKodoConfig;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.file.service.AliyunOssService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageOrchestrationService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.file.service.PrimaryObjectStorageService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.file.vo.ObjectStorageFileVO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class ObjectStorageUrlSupportTest {
|
||||
|
||||
private PrimaryObjectStorageService primaryObjectStorageService;
|
||||
private AliyunOssService aliyunOssService;
|
||||
private ObjectStorageOrchestrationService objectStorageOrchestrationService;
|
||||
private ObjectStorageUrlSupport support;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
primaryObjectStorageService = mock(PrimaryObjectStorageService.class);
|
||||
aliyunOssService = mock(AliyunOssService.class);
|
||||
objectStorageOrchestrationService = mock(ObjectStorageOrchestrationService.class);
|
||||
|
||||
QiniuKodoConfig qiniuKodoConfig = new QiniuKodoConfig();
|
||||
qiniuKodoConfig.setDomain("https://cdn.test");
|
||||
|
||||
support = new ObjectStorageUrlSupport(
|
||||
primaryObjectStorageService,
|
||||
qiniuKodoConfig,
|
||||
aliyunOssService,
|
||||
objectStorageProperties(),
|
||||
objectStorageOrchestrationService
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void toAccessibleUrlFallsBackToOriginalExternalUrlWhenObjectNameCannotBeExtracted() {
|
||||
String externalUrl = "https://acceptance.local/assets/product-a.jpg";
|
||||
|
||||
String result = support.toAccessibleUrl(externalUrl);
|
||||
|
||||
assertThat(result).isEqualTo(externalUrl);
|
||||
verifyNoInteractions(primaryObjectStorageService, aliyunOssService, objectStorageOrchestrationService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractObjectNameStillAcceptsRawObjectName() {
|
||||
assertThat(support.extractObjectName("product/a.jpg?x=1")).isEqualTo("product/a.jpg");
|
||||
}
|
||||
|
||||
@Test
|
||||
void toAccessibleUrlMatchesHttpFileUrlWhenQiniuDomainMissesScheme() throws Exception {
|
||||
QiniuKodoConfig qiniuKodoConfig = new QiniuKodoConfig();
|
||||
qiniuKodoConfig.setDomain("img.example.com");
|
||||
|
||||
ObjectStorageUrlSupport urlSupport = new ObjectStorageUrlSupport(
|
||||
primaryObjectStorageService,
|
||||
qiniuKodoConfig,
|
||||
aliyunOssService,
|
||||
objectStorageProperties(),
|
||||
objectStorageOrchestrationService
|
||||
);
|
||||
|
||||
when(objectStorageOrchestrationService.getPresignedUrl("product/a.jpg", 60))
|
||||
.thenReturn("http://img.example.com/product/a.jpg?e=1&token=test");
|
||||
|
||||
assertThat(urlSupport.toAccessibleUrl("http://img.example.com/product/a.jpg"))
|
||||
.isEqualTo("http://img.example.com/product/a.jpg?e=1&token=test");
|
||||
}
|
||||
|
||||
@Test
|
||||
void toAccessibleUrlReturnsNullInsteadOfRawUrlWhenStringObjectSigningFails() throws Exception {
|
||||
when(objectStorageOrchestrationService.getPresignedUrl("product/a.jpg", 60))
|
||||
.thenThrow(new IllegalStateException("primary down"));
|
||||
|
||||
String result = support.toAccessibleUrl("https://cdn.test/product/a.jpg");
|
||||
|
||||
assertThat(result).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void toAccessibleUrlFallsBackToBackupSignedUrlWhenPrimarySigningFailsAndBackupSucceeded() throws Exception {
|
||||
ObjectStorageFileVO file = new ObjectStorageFileVO();
|
||||
file.setId(12L);
|
||||
file.setFileUrl("https://cdn.test/product/a.png");
|
||||
file.setPrimaryUrl("https://cdn.test/product/a.png");
|
||||
file.setObjectName("product/a.png");
|
||||
file.setBackupUploadStatus(1);
|
||||
|
||||
when(objectStorageOrchestrationService.getPresignedUrl(12L, "product/a.png", 60))
|
||||
.thenThrow(new IllegalStateException("primary down"));
|
||||
when(aliyunOssService.getPresignedUrl("product/a.png")).thenReturn("https://oss-signed.test/product/a.png");
|
||||
|
||||
String result = support.toAccessibleUrl(file);
|
||||
|
||||
assertThat(result).isEqualTo("https://oss-signed.test/product/a.png");
|
||||
}
|
||||
|
||||
@Test
|
||||
void toAccessibleUrlReturnsNullInsteadOfRawObjectStorageUrlWhenBothBackendsAreUnavailable() throws Exception {
|
||||
ObjectStorageFileVO file = new ObjectStorageFileVO();
|
||||
file.setId(12L);
|
||||
file.setFileUrl("https://cdn.test/product/a.png");
|
||||
file.setPrimaryUrl("https://cdn.test/product/a.png");
|
||||
file.setObjectName("product/a.png");
|
||||
file.setBackupUploadStatus(1);
|
||||
|
||||
when(objectStorageOrchestrationService.getPresignedUrl(12L, "product/a.png", 60))
|
||||
.thenThrow(new IllegalStateException("primary down"));
|
||||
when(aliyunOssService.getPresignedUrl("product/a.png")).thenThrow(new IllegalStateException("backup down"));
|
||||
|
||||
String result = support.toAccessibleUrl(file);
|
||||
|
||||
assertThat(result).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSignedUrlOrThrowReportsClearFailureWhenBothBackendsAreUnavailable() throws Exception {
|
||||
ObjectStorageFileVO file = new ObjectStorageFileVO();
|
||||
file.setId(12L);
|
||||
file.setFileUrl("https://cdn.test/product/a.png");
|
||||
file.setObjectName("product/a.png");
|
||||
file.setBackupUploadStatus(1);
|
||||
|
||||
when(objectStorageOrchestrationService.getPresignedUrl(12L, "product/a.png", 20))
|
||||
.thenThrow(new IllegalStateException("primary down"));
|
||||
when(aliyunOssService.getPresignedUrl("product/a.png")).thenThrow(new IllegalStateException("backup down"));
|
||||
|
||||
assertThatThrownBy(() -> support.getSignedUrlOrThrow(file, 20))
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("No available object storage signed URL");
|
||||
}
|
||||
|
||||
private ObjectStorageProperties objectStorageProperties() {
|
||||
ObjectStorageProperties properties = new ObjectStorageProperties();
|
||||
properties.setPrimaryProvider("QINIU_KODO");
|
||||
properties.setBackupProvider("ALIYUN_OSS");
|
||||
properties.setSignedUrlExpireMinutes(60);
|
||||
properties.setBackupQueueName("test.queue");
|
||||
properties.setBackupExchangeName("test.exchange");
|
||||
properties.setBackupRoutingKey("test.routing");
|
||||
properties.setBackupRetryBatchLimit(500);
|
||||
properties.setBackupRetryCron("0 0 2 * * ?");
|
||||
return properties;
|
||||
}
|
||||
}
|
||||
-63
@@ -1,63 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.integration.service.impl;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.modules.integration.entity.BusinessEventOutboxDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.integration.mapper.BusinessEventOutboxMapper;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class BusinessEventOutboxServiceTest {
|
||||
|
||||
@Mock
|
||||
private BusinessEventOutboxMapper outboxMapper;
|
||||
|
||||
private BusinessEventOutboxServiceImpl service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
service = new BusinessEventOutboxServiceImpl(outboxMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void enqueueOrderCompletedCreatesIdempotentEvent() {
|
||||
service.enqueueOrderCompleted(1L);
|
||||
|
||||
ArgumentCaptor<BusinessEventOutboxDO> captor = ArgumentCaptor.forClass(BusinessEventOutboxDO.class);
|
||||
verify(outboxMapper).insert(captor.capture());
|
||||
BusinessEventOutboxDO event = captor.getValue();
|
||||
assertThat(event.getEventType()).isEqualTo("ORDER_COMPLETED");
|
||||
assertThat(event.getBusinessType()).isEqualTo("ORDER");
|
||||
assertThat(event.getBusinessId()).isEqualTo(1L);
|
||||
assertThat(event.getEventKey()).isEqualTo("ORDER:1:COMPLETED");
|
||||
assertThat(event.getStatus()).isEqualTo("PENDING");
|
||||
assertThat(event.getPayloadJson()).contains("\"orderId\":1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void duplicateOrderCompletedEventIsIgnored() {
|
||||
when(outboxMapper.insert(any(BusinessEventOutboxDO.class))).thenThrow(new DuplicateKeyException("duplicate"));
|
||||
|
||||
service.enqueueOrderCompleted(1L);
|
||||
|
||||
verify(outboxMapper).insert(any(BusinessEventOutboxDO.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void processorPollsFrequentlyEnoughForOrderReviewPromptAcceptanceWindow() throws NoSuchMethodException {
|
||||
Scheduled scheduled = BusinessEventOutboxProcessor.class.getMethod("processDueEvents")
|
||||
.getAnnotation(Scheduled.class);
|
||||
|
||||
assertThat(scheduled).isNotNull();
|
||||
assertThat(scheduled.fixedDelay()).isLessThanOrEqualTo(3000L);
|
||||
}
|
||||
}
|
||||
-127
@@ -1,127 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.integration.service.impl;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.config.BrandProperties;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.integration.entity.MessageHubPushConfigDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.integration.service.MessageHubPushConfigService;
|
||||
import com.xiaowang.fingertipdesigner.core.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.springframework.amqp.core.Message;
|
||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class MessageHubClientServiceImplTest {
|
||||
|
||||
private static final long ALIYUN_CHANNEL_ID = 314055468907909120L;
|
||||
|
||||
@Mock
|
||||
private RabbitTemplate rabbitTemplate;
|
||||
|
||||
@Mock
|
||||
private TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
|
||||
|
||||
@Mock
|
||||
private MessageHubPushConfigService messageHubPushConfigService;
|
||||
|
||||
@Mock
|
||||
private BrandProperties brandProperties;
|
||||
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
private MessageHubClientServiceImpl service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
service = new MessageHubClientServiceImpl(
|
||||
rabbitTemplate,
|
||||
objectMapper,
|
||||
snowflakeIdGenerator,
|
||||
messageHubPushConfigService,
|
||||
brandProperties
|
||||
);
|
||||
when(snowflakeIdGenerator.nextIdString()).thenReturn("sms-message-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void registerVerificationMessageIncludesAliyunTemplateParameters() throws Exception {
|
||||
String sceneCode = "USER_REGISTER_SMS_CODE";
|
||||
when(messageHubPushConfigService.getEnabledConfig(sceneCode))
|
||||
.thenReturn(aliyunConfig(sceneCode, "100001"));
|
||||
|
||||
service.sendSmsVerificationCode(sceneCode, "13800138000", "123456");
|
||||
|
||||
Map<String, Object> messageBody = capturedMessageBody();
|
||||
assertThat(messageBody)
|
||||
.containsEntry("templateCode", "100001")
|
||||
.containsEntry("sourceSystem", "fingertipdesigner")
|
||||
.containsEntry("sendMethod", "OTHER");
|
||||
assertThat(((Number) messageBody.get("channelId")).longValue()).isEqualTo(ALIYUN_CHANNEL_ID);
|
||||
|
||||
Map<String, Object> templateParams = templateParams(messageBody);
|
||||
assertThat(templateParams)
|
||||
.containsEntry("code", "123456")
|
||||
.containsEntry("min", "5")
|
||||
.containsEntry("minutes", "5")
|
||||
.containsEntry("number", "5");
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetPasswordVerificationMessageUsesResetTemplateWithAliyunParameters() throws Exception {
|
||||
String sceneCode = "USER_RESET_PASSWORD_SMS_CODE";
|
||||
when(messageHubPushConfigService.getEnabledConfig(sceneCode))
|
||||
.thenReturn(aliyunConfig(sceneCode, "100003"));
|
||||
|
||||
service.sendSmsVerificationCode(sceneCode, "13800138000", "654321");
|
||||
|
||||
Map<String, Object> messageBody = capturedMessageBody();
|
||||
assertThat(messageBody).containsEntry("templateCode", "100003");
|
||||
assertThat(((Number) messageBody.get("channelId")).longValue()).isEqualTo(ALIYUN_CHANNEL_ID);
|
||||
|
||||
Map<String, Object> templateParams = templateParams(messageBody);
|
||||
assertThat(templateParams)
|
||||
.containsEntry("code", "654321")
|
||||
.containsEntry("min", "5")
|
||||
.containsEntry("minutes", "5")
|
||||
.containsEntry("number", "5");
|
||||
}
|
||||
|
||||
private MessageHubPushConfigDO aliyunConfig(String sceneCode, String templateCode) {
|
||||
MessageHubPushConfigDO config = new MessageHubPushConfigDO();
|
||||
config.setSceneCode(sceneCode);
|
||||
config.setPlatform("SMS");
|
||||
config.setMsgType("VERIFICATION");
|
||||
config.setQueueName("smsQueue");
|
||||
config.setSourceSystem("fingertipdesigner");
|
||||
config.setTemplateCode(templateCode);
|
||||
config.setChannelId(ALIYUN_CHANNEL_ID);
|
||||
config.setSendMethod("OTHER");
|
||||
config.setEnabled(1);
|
||||
config.setIsDelete(0);
|
||||
return config;
|
||||
}
|
||||
|
||||
private Map<String, Object> capturedMessageBody() throws Exception {
|
||||
ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
|
||||
verify(rabbitTemplate).convertAndSend(eq("smsQueue"), messageCaptor.capture());
|
||||
String jsonBody = new String(messageCaptor.getValue().getBody(), StandardCharsets.UTF_8);
|
||||
return objectMapper.readValue(jsonBody, new TypeReference<Map<String, Object>>() {});
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Map<String, Object> templateParams(Map<String, Object> messageBody) {
|
||||
return (Map<String, Object>) messageBody.get("templateParams");
|
||||
}
|
||||
}
|
||||
-184
@@ -1,184 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.integration.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.common.BusinessException;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.integration.dto.WechatMiniAutoLoginRequestDTO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.integration.dto.WechatMiniPhoneLoginRequestDTO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.integration.entity.WechatMiniBindingDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.integration.mapper.WechatMiniBindingMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.service.UserService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.integration.service.WechatMiniClientService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.support.UserShopBindingSupport;
|
||||
import com.xiaowang.fingertipdesigner.core.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.vo.ShopSimpleVO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.integration.vo.WechatMiniLoginResultVO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.data.redis.core.ValueOperations;
|
||||
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.common.Result;
|
||||
class WechatMiniAuthServiceImplTest {
|
||||
|
||||
@Mock
|
||||
private WechatMiniClientService wechatMiniClientService;
|
||||
|
||||
@Mock
|
||||
private WechatMiniBindingMapper wechatMiniBindingMapper;
|
||||
|
||||
@Mock
|
||||
private UserMapper userMapper;
|
||||
|
||||
@Mock
|
||||
private UserService userService;
|
||||
|
||||
@Mock
|
||||
private UserShopBindingSupport userShopBindingSupport;
|
||||
|
||||
@Mock
|
||||
private StringRedisTemplate redisTemplate;
|
||||
|
||||
@Mock
|
||||
private ValueOperations<String, String> valueOperations;
|
||||
|
||||
private WechatMiniAuthServiceImpl service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
when(redisTemplate.opsForValue()).thenReturn(valueOperations);
|
||||
initTableInfo(WechatMiniBindingDO.class);
|
||||
initTableInfo(UserDO.class);
|
||||
service = new WechatMiniAuthServiceImpl(
|
||||
wechatMiniClientService,
|
||||
wechatMiniBindingMapper,
|
||||
userMapper,
|
||||
userService,
|
||||
userShopBindingSupport,
|
||||
redisTemplate,
|
||||
new ObjectMapper(),
|
||||
new TimeOrderedSnowflakeIdGenerator(1704067200000L, 1L, 1L, "test-app")
|
||||
);
|
||||
}
|
||||
|
||||
private void initTableInfo(Class<?> entityClass) {
|
||||
MapperBuilderAssistant assistant = new MapperBuilderAssistant(new MybatisConfiguration(), "");
|
||||
assistant.setCurrentNamespace(entityClass.getName());
|
||||
TableInfoHelper.initTableInfo(assistant, entityClass);
|
||||
}
|
||||
|
||||
@Test
|
||||
void autoLoginShouldDeactivateInvalidBindingAndFallbackToManualLogin() {
|
||||
WechatMiniAutoLoginRequestDTO requestDTO = new WechatMiniAutoLoginRequestDTO();
|
||||
requestDTO.setWxCode("wx-code");
|
||||
when(wechatMiniClientService.code2Session("wx-code"))
|
||||
.thenReturn(new WechatMiniClientService.SessionInfo("openid-1", "union-1", "session-1"));
|
||||
|
||||
WechatMiniBindingDO bindingDO = new WechatMiniBindingDO();
|
||||
bindingDO.setId(100L);
|
||||
bindingDO.setUserId(200L);
|
||||
bindingDO.setStatus(1);
|
||||
when(wechatMiniBindingMapper.selectOne(any(LambdaQueryWrapper.class))).thenReturn(bindingDO);
|
||||
|
||||
UserDO deletedUser = new UserDO();
|
||||
deletedUser.setId(200L);
|
||||
deletedUser.setIsDelete(1);
|
||||
when(userMapper.selectById(200L)).thenReturn(deletedUser);
|
||||
|
||||
WechatMiniLoginResultVO result = service.autoLogin(requestDTO);
|
||||
|
||||
assertEquals(WechatMiniLoginResultVO.STATUS_NEED_MANUAL_LOGIN, result.getStatus());
|
||||
assertFalse(Boolean.TRUE.equals(result.getNewUser()));
|
||||
verify(wechatMiniBindingMapper).update(eq(null), any(LambdaUpdateWrapper.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void phoneLoginShouldReturnSelectShopWhenNewWechatPhoneNeedsShopSelection() {
|
||||
WechatMiniPhoneLoginRequestDTO requestDTO = new WechatMiniPhoneLoginRequestDTO();
|
||||
requestDTO.setWxCode("wx-code");
|
||||
requestDTO.setPhoneCode("phone-code");
|
||||
|
||||
when(wechatMiniClientService.code2Session("wx-code"))
|
||||
.thenReturn(new WechatMiniClientService.SessionInfo("openid-2", "union-2", "session-2"));
|
||||
when(wechatMiniClientService.getPhoneNumber("phone-code")).thenReturn("13800138000");
|
||||
when(wechatMiniBindingMapper.selectOne(any(LambdaQueryWrapper.class))).thenReturn(null);
|
||||
when(userMapper.selectOne(any(LambdaQueryWrapper.class))).thenReturn(null);
|
||||
when(userShopBindingSupport.listAllActiveShopOptions()).thenReturn(List.of(
|
||||
new ShopSimpleVO(1L, "A 店"),
|
||||
new ShopSimpleVO(2L, "B 店")
|
||||
));
|
||||
|
||||
WechatMiniLoginResultVO result = service.phoneLogin(requestDTO);
|
||||
|
||||
assertEquals(WechatMiniLoginResultVO.STATUS_SELECT_SHOP, result.getStatus());
|
||||
assertTrue(Boolean.TRUE.equals(result.getNewUser()));
|
||||
assertEquals(2, result.getShops().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void ensureBindingShouldDeactivateHistoricalDuplicatesAndKeepSingleActiveRecord() {
|
||||
when(wechatMiniClientService.getConfiguredAppId()).thenReturn("mini-app");
|
||||
|
||||
WechatMiniBindingDO currentBinding = new WechatMiniBindingDO();
|
||||
currentBinding.setId(1L);
|
||||
currentBinding.setUserId(8L);
|
||||
currentBinding.setOpenId("openid-3");
|
||||
currentBinding.setAppId("mini-app");
|
||||
currentBinding.setStatus(1);
|
||||
|
||||
WechatMiniBindingDO duplicateBinding = new WechatMiniBindingDO();
|
||||
duplicateBinding.setId(2L);
|
||||
duplicateBinding.setUserId(8L);
|
||||
duplicateBinding.setOpenId("openid-legacy");
|
||||
duplicateBinding.setAppId("mini-app");
|
||||
duplicateBinding.setStatus(0);
|
||||
|
||||
when(wechatMiniBindingMapper.selectList(any(LambdaQueryWrapper.class)))
|
||||
.thenReturn(List.of(currentBinding), List.of(currentBinding, duplicateBinding));
|
||||
|
||||
service.ensureBinding(8L, "openid-3", "union-3");
|
||||
|
||||
verify(wechatMiniBindingMapper).updateById(currentBinding);
|
||||
verify(wechatMiniBindingMapper).update(eq(null), any(LambdaUpdateWrapper.class));
|
||||
verify(wechatMiniBindingMapper, never()).insert(any(WechatMiniBindingDO.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void ensureBindingShouldRejectOtherUsersActiveBinding() {
|
||||
when(wechatMiniClientService.getConfiguredAppId()).thenReturn("mini-app");
|
||||
|
||||
WechatMiniBindingDO activeBinding = new WechatMiniBindingDO();
|
||||
activeBinding.setId(11L);
|
||||
activeBinding.setUserId(9L);
|
||||
activeBinding.setOpenId("openid-4");
|
||||
activeBinding.setAppId("mini-app");
|
||||
activeBinding.setStatus(1);
|
||||
|
||||
when(wechatMiniBindingMapper.selectList(any(LambdaQueryWrapper.class)))
|
||||
.thenReturn(List.of(activeBinding), List.of());
|
||||
|
||||
BusinessException exception = assertThrows(BusinessException.class, () -> service.ensureBinding(8L, "openid-4", "union-4"));
|
||||
assertEquals("当前微信已绑定其他账号,无法完成登录", exception.getMessage());
|
||||
}
|
||||
}
|
||||
-61
@@ -1,61 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.integration.service.impl;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.common.BusinessException;
|
||||
import com.xiaowang.fingertipdesigner.core.config.WechatMiniProperties;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.data.redis.core.ValueOperations;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class WechatMiniClientServiceImplTest {
|
||||
|
||||
@Mock
|
||||
private RestTemplate restTemplate;
|
||||
|
||||
@Mock
|
||||
private StringRedisTemplate redisTemplate;
|
||||
|
||||
@Mock
|
||||
private ValueOperations<String, String> valueOperations;
|
||||
|
||||
private WechatMiniClientServiceImpl service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
when(redisTemplate.opsForValue()).thenReturn(valueOperations);
|
||||
WechatMiniProperties properties = new WechatMiniProperties();
|
||||
properties.setAppId("app-id");
|
||||
properties.setAppSecret("app-secret");
|
||||
service = new WechatMiniClientServiceImpl(restTemplate, redisTemplate, new ObjectMapper(), properties);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getPhoneNumberShouldFailWhenWechatResponseMissesPhoneInfo() {
|
||||
when(valueOperations.get(anyString())).thenReturn(null);
|
||||
when(restTemplate.getForObject(anyString(), any())).thenReturn("{\"access_token\":\"access-token\",\"expires_in\":7200}");
|
||||
when(restTemplate.postForObject(anyString(), any(HttpEntity.class), any())).thenReturn("{\"errcode\":0}");
|
||||
|
||||
BusinessException exception = assertThrows(BusinessException.class, () -> service.getPhoneNumber("phone-code"));
|
||||
assertEquals("获取微信手机号失败:未返回手机号信息", exception.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void code2SessionShouldFailWhenWechatResponseMissesOpenId() {
|
||||
when(restTemplate.getForObject(anyString(), any())).thenReturn("{\"errcode\":0,\"session_key\":\"abc\"}");
|
||||
|
||||
BusinessException exception = assertThrows(BusinessException.class, () -> service.code2Session("wx-code"));
|
||||
assertEquals("获取微信登录身份失败:缺少 openid", exception.getMessage());
|
||||
}
|
||||
}
|
||||
-280
@@ -1,280 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.manager.controller.admin;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.common.Result;
|
||||
import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleDTO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleExceptionDTO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleRuleDTO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.NailArtistInfoDTO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.service.ArtistScheduleService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.service.NailArtistInfoService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleExceptionVO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleRuleSettingVO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleRuleVO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleVO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.manager.dto.ManagerCustomerCreateDTO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.planning.service.PlanningService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.service.ProductService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.vo.ProductVO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.dto.ShopDTO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.service.ShopService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.vo.ShopVO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.dto.UserDTO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.service.UserService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.vo.UserVO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class AdminManagerControllerTest {
|
||||
|
||||
@Mock
|
||||
private PlanningService planningService;
|
||||
|
||||
@Mock
|
||||
private UserService userService;
|
||||
|
||||
@Mock
|
||||
private NailArtistInfoService nailArtistInfoService;
|
||||
|
||||
@Mock
|
||||
private ArtistScheduleService artistScheduleService;
|
||||
|
||||
@Mock
|
||||
private ProductService productService;
|
||||
|
||||
@Mock
|
||||
private ShopService shopService;
|
||||
|
||||
@Mock
|
||||
private AdminScopeHelper adminScopeHelper;
|
||||
|
||||
private AdminManagerController controller;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
controller = new AdminManagerController(planningService, userService, nailArtistInfoService, artistScheduleService, productService, shopService, adminScopeHelper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void controllerShouldExposeManagerBoundary() {
|
||||
RequestMapping mapping = AdminManagerController.class.getAnnotation(RequestMapping.class);
|
||||
|
||||
assertThat(mapping.value()).containsExactly("/admin/manager");
|
||||
}
|
||||
|
||||
@Test
|
||||
void customersShouldResolveShopScopeAndForceCustomerType() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
UserDO manager = new UserDO();
|
||||
manager.setType(2);
|
||||
manager.setShopId(8L);
|
||||
PageResultVO<UserVO> pageResult = new PageResultVO<>();
|
||||
when(adminScopeHelper.getCurrentUser(request)).thenReturn(manager);
|
||||
when(adminScopeHelper.resolveShopScope(manager, 99L)).thenReturn(8L);
|
||||
when(userService.pageUsers(1, 10, "ann", 8L, 0, null, null, null, null, null, null, null, null, true)).thenReturn(pageResult);
|
||||
|
||||
Result<PageResultVO<UserVO>> result = controller.customers(request, 1, 10, "ann", 99L, true);
|
||||
|
||||
assertThat(result.getData()).isSameAs(pageResult);
|
||||
verify(adminScopeHelper).resolveShopScope(manager, 99L);
|
||||
verify(userService).pageUsers(1, 10, "ann", 8L, 0, null, null, null, null, null, null, null, null, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createEmployeeUserShouldBindNonPlatformUserToManagedShop() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
UserDO manager = new UserDO();
|
||||
manager.setType(2);
|
||||
manager.setShopId(8L);
|
||||
UserDTO dto = new UserDTO();
|
||||
dto.setType(3);
|
||||
dto.setShopId(99L);
|
||||
when(adminScopeHelper.getCurrentUser(request)).thenReturn(manager);
|
||||
when(adminScopeHelper.isPlatformAdmin(manager)).thenReturn(false);
|
||||
when(adminScopeHelper.getManagedShopId(manager)).thenReturn(8L);
|
||||
when(userService.createUser(dto)).thenReturn(101L);
|
||||
|
||||
Result<Long> result = controller.createEmployeeUser(request, dto);
|
||||
|
||||
assertThat(result.getData()).isEqualTo(101L);
|
||||
assertThat(dto.getShopId()).isEqualTo(8L);
|
||||
assertThat(dto.getShopIds()).containsExactly(8L);
|
||||
verify(adminScopeHelper).ensureAssignableUserType(manager, 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createEmployeeUserShouldForceNailArtistType() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
UserDO manager = new UserDO();
|
||||
manager.setType(2);
|
||||
UserDTO dto = new UserDTO();
|
||||
dto.setType(0);
|
||||
when(adminScopeHelper.getCurrentUser(request)).thenReturn(manager);
|
||||
when(adminScopeHelper.isPlatformAdmin(manager)).thenReturn(true);
|
||||
when(userService.createUser(dto)).thenReturn(102L);
|
||||
|
||||
Result<Long> result = controller.createEmployeeUser(request, dto);
|
||||
|
||||
assertThat(result.getData()).isEqualTo(102L);
|
||||
assertThat(dto.getType()).isEqualTo(3);
|
||||
verify(adminScopeHelper).ensureAssignableUserType(manager, 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createCustomerShouldForceNormalUserInCurrentShop() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
UserDO manager = new UserDO();
|
||||
manager.setType(2);
|
||||
ManagerCustomerCreateDTO dto = new ManagerCustomerCreateDTO();
|
||||
dto.setNickname(" 小王客户 ");
|
||||
dto.setPhone(" 13800138000 ");
|
||||
when(adminScopeHelper.getCurrentUser(request)).thenReturn(manager);
|
||||
when(adminScopeHelper.resolveShopScope(manager, null)).thenReturn(8L);
|
||||
when(userService.createUser(any(UserDTO.class))).thenReturn(103L);
|
||||
|
||||
Result<Long> result = controller.createCustomer(request, dto);
|
||||
|
||||
assertThat(result.getData()).isEqualTo(103L);
|
||||
verify(adminScopeHelper).requireShopContext(manager, "请先选择店铺后再新增客户");
|
||||
verify(userService).createUser(org.mockito.ArgumentMatchers.argThat(userDTO ->
|
||||
"小王客户".equals(userDTO.getNickname())
|
||||
&& "13800138000".equals(userDTO.getPhone())
|
||||
&& "13800138000".equals(userDTO.getContactPhone())
|
||||
&& "13800138000".equals(userDTO.getAccount())
|
||||
&& Integer.valueOf(0).equals(userDTO.getType())
|
||||
&& Long.valueOf(8L).equals(userDTO.getShopId())
|
||||
&& userDTO.getShopIds().equals(List.of(8L))
|
||||
&& "普通".equals(userDTO.getLevel())
|
||||
&& Long.valueOf(0L).equals(userDTO.getVipId())
|
||||
));
|
||||
}
|
||||
|
||||
@Test
|
||||
void saveScheduleShouldResolveShopScopeBeforeSaving() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
UserDO manager = new UserDO();
|
||||
ArtistScheduleDTO dto = new ArtistScheduleDTO();
|
||||
dto.setShopId(99L);
|
||||
ArtistScheduleVO vo = new ArtistScheduleVO();
|
||||
when(adminScopeHelper.getCurrentUser(request)).thenReturn(manager);
|
||||
when(adminScopeHelper.resolveShopScope(manager, 99L)).thenReturn(8L);
|
||||
when(artistScheduleService.saveSchedule(dto)).thenReturn(vo);
|
||||
|
||||
Result<ArtistScheduleVO> result = controller.saveSchedule(request, dto);
|
||||
|
||||
assertThat(result.getData()).isSameAs(vo);
|
||||
assertThat(dto.getShopId()).isEqualTo(8L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void scheduleRuleShouldResolveShopScopeBeforeReading() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
UserDO manager = new UserDO();
|
||||
ArtistScheduleRuleSettingVO vo = new ArtistScheduleRuleSettingVO();
|
||||
when(adminScopeHelper.getCurrentUser(request)).thenReturn(manager);
|
||||
when(adminScopeHelper.resolveShopScope(manager, null)).thenReturn(8L);
|
||||
when(artistScheduleService.getRuleSetting(8L, 30L)).thenReturn(vo);
|
||||
|
||||
Result<ArtistScheduleRuleSettingVO> result = controller.scheduleRule(request, 30L);
|
||||
|
||||
assertThat(result.getData()).isSameAs(vo);
|
||||
verify(artistScheduleService).getRuleSetting(8L, 30L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void saveScheduleRuleShouldResolveShopScopeBeforeSaving() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
UserDO manager = new UserDO();
|
||||
ArtistScheduleRuleDTO dto = new ArtistScheduleRuleDTO();
|
||||
dto.setShopId(99L);
|
||||
ArtistScheduleRuleVO vo = new ArtistScheduleRuleVO();
|
||||
when(adminScopeHelper.getCurrentUser(request)).thenReturn(manager);
|
||||
when(adminScopeHelper.resolveShopScope(manager, 99L)).thenReturn(8L);
|
||||
when(artistScheduleService.saveRule(dto)).thenReturn(vo);
|
||||
|
||||
Result<ArtistScheduleRuleVO> result = controller.saveScheduleRule(request, dto);
|
||||
|
||||
assertThat(result.getData()).isSameAs(vo);
|
||||
assertThat(dto.getShopId()).isEqualTo(8L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void saveScheduleExceptionShouldResolveShopScopeBeforeSaving() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
UserDO manager = new UserDO();
|
||||
ArtistScheduleExceptionDTO dto = new ArtistScheduleExceptionDTO();
|
||||
dto.setShopId(99L);
|
||||
ArtistScheduleExceptionVO vo = new ArtistScheduleExceptionVO();
|
||||
when(adminScopeHelper.getCurrentUser(request)).thenReturn(manager);
|
||||
when(adminScopeHelper.resolveShopScope(manager, 99L)).thenReturn(8L);
|
||||
when(artistScheduleService.saveException(dto)).thenReturn(vo);
|
||||
|
||||
Result<ArtistScheduleExceptionVO> result = controller.saveScheduleException(request, dto);
|
||||
|
||||
assertThat(result.getData()).isSameAs(vo);
|
||||
assertThat(dto.getShopId()).isEqualTo(8L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateShopShouldPreserveAuthorizationExpireTimeForNonPlatformUser() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
UserDO manager = new UserDO();
|
||||
ShopDTO dto = new ShopDTO();
|
||||
ShopVO shop = new ShopVO();
|
||||
when(adminScopeHelper.getCurrentUser(request)).thenReturn(manager);
|
||||
when(adminScopeHelper.resolveShopScope(manager, null)).thenReturn(8L);
|
||||
when(shopService.getShopById(8L)).thenReturn(shop);
|
||||
when(adminScopeHelper.isPlatformAdmin(manager)).thenReturn(false);
|
||||
when(shopService.updateShop(8L, dto)).thenReturn(true);
|
||||
|
||||
Result<Boolean> result = controller.updateShop(request, dto);
|
||||
|
||||
assertThat(result.getData()).isTrue();
|
||||
verify(adminScopeHelper).requireShopContext(manager);
|
||||
verify(shopService).updateShop(8L, dto);
|
||||
}
|
||||
|
||||
@Test
|
||||
void employeesShouldReturnScopedArtistsForNonPlatformUser() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
UserDO manager = new UserDO();
|
||||
List<NailArtistInfoDTO> artists = List.of(new NailArtistInfoDTO());
|
||||
when(adminScopeHelper.getCurrentUser(request)).thenReturn(manager);
|
||||
when(adminScopeHelper.isPlatformAdmin(manager)).thenReturn(false);
|
||||
when(adminScopeHelper.resolveShopScope(manager, null)).thenReturn(8L);
|
||||
when(nailArtistInfoService.getByShopId(8L)).thenReturn(artists);
|
||||
|
||||
Result<List<NailArtistInfoDTO>> result = controller.employees(request);
|
||||
|
||||
assertThat(result.getData()).isSameAs(artists);
|
||||
}
|
||||
|
||||
@Test
|
||||
void productsShouldResolveShopScope() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
UserDO manager = new UserDO();
|
||||
PageResultVO<ProductVO> pageResult = new PageResultVO<>();
|
||||
when(adminScopeHelper.getCurrentUser(request)).thenReturn(manager);
|
||||
when(adminScopeHelper.resolveShopScope(manager, 99L)).thenReturn(8L);
|
||||
when(productService.pageProducts(1, 10, "gel", 8L, null, null, null, null, null)).thenReturn(pageResult);
|
||||
|
||||
Result<PageResultVO<ProductVO>> result = controller.products(request, 1, 10, "gel", 99L, null, null, null, null, null);
|
||||
|
||||
assertThat(result.getData()).isSameAs(pageResult);
|
||||
verify(productService).pageProducts(1, 10, "gel", 8L, null, null, null, null, null);
|
||||
}
|
||||
}
|
||||
-208
@@ -1,208 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.marketing.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.Wrapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.WishlistAddWithGroupDTO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.WishlistMoveDTO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.WishlistGroupDTO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.entity.ProductDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.WishlistDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.WishlistGroupDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.mapper.ProductMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.marketing.mapper.WishlistGroupMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.marketing.mapper.WishlistMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.service.ProductService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.vo.ProductVO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.WishlistGroupVO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.WishlistInspirationVO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class WishlistServiceImplTest {
|
||||
|
||||
private static final String RECENT_GROUP = "\u6700\u8fd1\u60f3\u505a";
|
||||
private static final String WEDDING_GROUP = "\u5a5a\u793c\u6b3e";
|
||||
private static final String SUMMER_GROUP = "\u590f\u5929\u6b3e";
|
||||
|
||||
private WishlistMapper wishlistMapper;
|
||||
private WishlistGroupMapper wishlistGroupMapper;
|
||||
private ProductMapper productMapper;
|
||||
private ProductService productService;
|
||||
private WishlistServiceImpl service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
wishlistMapper = mock(WishlistMapper.class);
|
||||
wishlistGroupMapper = mock(WishlistGroupMapper.class);
|
||||
productMapper = mock(ProductMapper.class);
|
||||
productService = mock(ProductService.class);
|
||||
service = new WishlistServiceImpl(wishlistMapper, wishlistGroupMapper, productService, productMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void listGroupsCreatesPresetGroupsForNewUser() {
|
||||
when(wishlistGroupMapper.selectList(any(Wrapper.class))).thenReturn(List.of());
|
||||
|
||||
List<WishlistGroupVO> groups = service.listGroups(88L);
|
||||
|
||||
ArgumentCaptor<WishlistGroupDO> captor = ArgumentCaptor.forClass(WishlistGroupDO.class);
|
||||
verify(wishlistGroupMapper, org.mockito.Mockito.times(3)).insert(captor.capture());
|
||||
assertThat(captor.getAllValues())
|
||||
.extracting(WishlistGroupDO::getName)
|
||||
.containsExactly(RECENT_GROUP, WEDDING_GROUP, SUMMER_GROUP);
|
||||
assertThat(groups).extracting(WishlistGroupVO::getName)
|
||||
.containsExactly(RECENT_GROUP, WEDDING_GROUP, SUMMER_GROUP);
|
||||
}
|
||||
|
||||
@Test
|
||||
void addWithGroupCreatesWishlistEntryWithGroupMetadata() {
|
||||
ProductDO product = new ProductDO();
|
||||
product.setId(9L);
|
||||
product.setIsDelete(0);
|
||||
when(productMapper.selectById(9L)).thenReturn(product);
|
||||
when(wishlistGroupMapper.selectById(3L)).thenReturn(group(3L, 88L, WEDDING_GROUP, 20));
|
||||
when(wishlistMapper.selectOne(any(Wrapper.class))).thenReturn(null);
|
||||
|
||||
WishlistAddWithGroupDTO request = new WishlistAddWithGroupDTO();
|
||||
request.setProductId(9L);
|
||||
request.setGroupId(3L);
|
||||
request.setNote("Ask for pearl accent");
|
||||
request.setSortOrder(7);
|
||||
service.addToWishlist(88L, request);
|
||||
|
||||
ArgumentCaptor<WishlistDO> captor = ArgumentCaptor.forClass(WishlistDO.class);
|
||||
verify(wishlistMapper).insert(captor.capture());
|
||||
assertThat(captor.getValue().getUserId()).isEqualTo(88L);
|
||||
assertThat(captor.getValue().getProductId()).isEqualTo(9L);
|
||||
assertThat(captor.getValue().getGroupId()).isEqualTo(3L);
|
||||
assertThat(captor.getValue().getNote()).isEqualTo("Ask for pearl accent");
|
||||
assertThat(captor.getValue().getSortOrder()).isEqualTo(7);
|
||||
verify(productMapper).incrementCollectCount(9L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void addWithGroupUpdatesExistingWishlistWithoutIncrementingCollectCount() {
|
||||
ProductDO product = new ProductDO();
|
||||
product.setId(9L);
|
||||
product.setIsDelete(0);
|
||||
WishlistDO existing = new WishlistDO();
|
||||
existing.setId(11L);
|
||||
existing.setUserId(88L);
|
||||
existing.setProductId(9L);
|
||||
when(productMapper.selectById(9L)).thenReturn(product);
|
||||
when(wishlistGroupMapper.selectById(3L)).thenReturn(group(3L, 88L, WEDDING_GROUP, 20));
|
||||
when(wishlistMapper.selectOne(any(Wrapper.class))).thenReturn(existing);
|
||||
|
||||
WishlistAddWithGroupDTO request = new WishlistAddWithGroupDTO();
|
||||
request.setProductId(9L);
|
||||
request.setGroupId(3L);
|
||||
request.setNote("Move to wedding board");
|
||||
service.addToWishlist(88L, request);
|
||||
|
||||
assertThat(existing.getGroupId()).isEqualTo(3L);
|
||||
assertThat(existing.getNote()).isEqualTo("Move to wedding board");
|
||||
verify(wishlistMapper).updateById(existing);
|
||||
verify(productMapper, never()).incrementCollectCount(9L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void moveWishlistChangesGroupNoteAndOrder() {
|
||||
WishlistDO existing = new WishlistDO();
|
||||
existing.setId(11L);
|
||||
existing.setUserId(88L);
|
||||
existing.setProductId(9L);
|
||||
when(wishlistMapper.selectOne(any(Wrapper.class))).thenReturn(existing);
|
||||
when(wishlistGroupMapper.selectById(2L)).thenReturn(group(2L, 88L, SUMMER_GROUP, 30));
|
||||
|
||||
WishlistMoveDTO request = new WishlistMoveDTO();
|
||||
request.setProductId(9L);
|
||||
request.setGroupId(2L);
|
||||
request.setNote("Try blue");
|
||||
request.setSortOrder(4);
|
||||
service.moveWishlist(88L, request);
|
||||
|
||||
assertThat(existing.getGroupId()).isEqualTo(2L);
|
||||
assertThat(existing.getNote()).isEqualTo("Try blue");
|
||||
assertThat(existing.getSortOrder()).isEqualTo(4);
|
||||
verify(wishlistMapper).updateById(existing);
|
||||
}
|
||||
|
||||
@Test
|
||||
void inspirationGroupsWishlistItemsByGroupAndKeepsUngroupedInDefaultGroup() {
|
||||
WishlistGroupDO recent = group(1L, 88L, RECENT_GROUP, 10);
|
||||
WishlistGroupDO summer = group(2L, 88L, SUMMER_GROUP, 30);
|
||||
WishlistDO grouped = wishlist(101L, 88L, 9L, 2L, "Try blue", 4);
|
||||
WishlistDO legacy = wishlist(102L, 88L, 10L, null, null, 0);
|
||||
when(wishlistGroupMapper.selectList(any(Wrapper.class))).thenReturn(List.of(recent, summer));
|
||||
when(wishlistMapper.selectList(any(Wrapper.class))).thenReturn(List.of(grouped, legacy));
|
||||
when(productService.getProductById(9L)).thenReturn(product(9L, "Ocean glass"));
|
||||
when(productService.getProductById(10L)).thenReturn(product(10L, "Plain nude"));
|
||||
|
||||
WishlistInspirationVO inspiration = service.getInspiration(88L);
|
||||
|
||||
assertThat(inspiration.getTotal()).isEqualTo(2);
|
||||
assertThat(inspiration.getGroups()).extracting(WishlistGroupVO::getName)
|
||||
.containsExactly(RECENT_GROUP, WEDDING_GROUP, SUMMER_GROUP);
|
||||
assertThat(inspiration.getGroups().get(0).getItems())
|
||||
.extracting(item -> item.getProduct().getTitle())
|
||||
.containsExactly("Plain nude");
|
||||
assertThat(inspiration.getGroups().get(1).getItems()).isEmpty();
|
||||
assertThat(inspiration.getGroups().get(2).getItems())
|
||||
.extracting(item -> item.getProduct().getTitle())
|
||||
.containsExactly("Ocean glass");
|
||||
}
|
||||
|
||||
@Test
|
||||
void createGroupNormalizesNameAndSortOrder() {
|
||||
WishlistGroupDTO request = new WishlistGroupDTO();
|
||||
request.setName(" Bride ideas ");
|
||||
|
||||
service.createGroup(88L, request);
|
||||
|
||||
ArgumentCaptor<WishlistGroupDO> captor = ArgumentCaptor.forClass(WishlistGroupDO.class);
|
||||
verify(wishlistGroupMapper).insert(captor.capture());
|
||||
assertThat(captor.getValue().getName()).isEqualTo("Bride ideas");
|
||||
assertThat(captor.getValue().getSortOrder()).isEqualTo(100);
|
||||
assertThat(captor.getValue().getIsDelete()).isZero();
|
||||
}
|
||||
|
||||
private WishlistGroupDO group(Long id, Long userId, String name, Integer sortOrder) {
|
||||
WishlistGroupDO group = new WishlistGroupDO();
|
||||
group.setId(id);
|
||||
group.setUserId(userId);
|
||||
group.setName(name);
|
||||
group.setSortOrder(sortOrder);
|
||||
group.setIsDelete(0);
|
||||
return group;
|
||||
}
|
||||
|
||||
private WishlistDO wishlist(Long id, Long userId, Long productId, Long groupId, String note, Integer sortOrder) {
|
||||
WishlistDO wishlist = new WishlistDO();
|
||||
wishlist.setId(id);
|
||||
wishlist.setUserId(userId);
|
||||
wishlist.setProductId(productId);
|
||||
wishlist.setGroupId(groupId);
|
||||
wishlist.setNote(note);
|
||||
wishlist.setSortOrder(sortOrder);
|
||||
wishlist.setIsDelete(0);
|
||||
return wishlist;
|
||||
}
|
||||
|
||||
private ProductVO product(Long id, String title) {
|
||||
ProductVO product = new ProductVO();
|
||||
product.setId(id);
|
||||
product.setTitle(title);
|
||||
product.setPrice(new BigDecimal("168.00"));
|
||||
return product;
|
||||
}
|
||||
}
|
||||
-113
@@ -1,113 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.order.controller.admin;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.fingertipdesigner.core.common.Result;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.service.OrderService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.vo.OrderVO;
|
||||
import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Parameter;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
|
||||
class AdminOrderControllerTest {
|
||||
|
||||
@Mock
|
||||
private OrderService orderService;
|
||||
|
||||
@Mock
|
||||
private AdminScopeHelper adminScopeHelper;
|
||||
|
||||
private AdminOrderController controller;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
controller = new AdminOrderController(orderService, adminScopeHelper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void listOrdersShouldAcceptShopFilterAndResolveScopeOnServer() throws Exception {
|
||||
Method method = Arrays.stream(AdminOrderController.class.getDeclaredMethods())
|
||||
.filter(candidate -> "listOrders".equals(candidate.getName()))
|
||||
.filter(candidate -> Arrays.stream(candidate.getParameters()).anyMatch(this::isShopIdRequestParam))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new AssertionError("listOrders must expose optional shopId request parameter"));
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
UserDO platformAdmin = new UserDO();
|
||||
platformAdmin.setType(4);
|
||||
when(adminScopeHelper.getCurrentUser(request)).thenReturn(platformAdmin);
|
||||
when(adminScopeHelper.resolveShopScope(platformAdmin, 8L)).thenReturn(8L);
|
||||
|
||||
OrderVO visibleOrder = order(8L);
|
||||
OrderVO hiddenOrder = order(9L);
|
||||
when(orderService.getAllOrders()).thenReturn(List.of(visibleOrder, hiddenOrder));
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
Result<PageResultVO<OrderVO>> result = (Result<PageResultVO<OrderVO>>) method.invoke(controller, request, 1, 10, null, 8L, null);
|
||||
|
||||
verify(adminScopeHelper).resolveShopScope(platformAdmin, 8L);
|
||||
assertThat(result.getData().getList()).containsExactly(visibleOrder);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getOrderDetailShouldReturnVisibleOrderForAdmin() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
UserDO platformAdmin = new UserDO();
|
||||
platformAdmin.setType(4);
|
||||
when(adminScopeHelper.getCurrentUser(request)).thenReturn(platformAdmin);
|
||||
|
||||
OrderVO visibleOrder = order(8L);
|
||||
when(orderService.getAllOrders()).thenReturn(List.of(visibleOrder));
|
||||
|
||||
Result<OrderVO> result = controller.getOrderDetail(request, visibleOrder.getId());
|
||||
|
||||
assertThat(result.getData()).isSameAs(visibleOrder);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getOrderDetailShouldRejectOtherShopForManager() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
UserDO manager = new UserDO();
|
||||
manager.setType(2);
|
||||
manager.setShopId(8L);
|
||||
when(adminScopeHelper.getCurrentUser(request)).thenReturn(manager);
|
||||
|
||||
OrderVO otherShopOrder = order(9L);
|
||||
when(orderService.getAllOrders()).thenReturn(List.of(otherShopOrder));
|
||||
doThrow(new RuntimeException("无权查看其他店铺订单"))
|
||||
.when(adminScopeHelper)
|
||||
.ensureShopAccessible(manager, otherShopOrder.getShopId(), "无权查看其他店铺订单");
|
||||
|
||||
assertThatThrownBy(() -> controller.getOrderDetail(request, otherShopOrder.getId()))
|
||||
.isInstanceOf(RuntimeException.class)
|
||||
.hasMessageContaining("无权查看其他店铺订单");
|
||||
}
|
||||
|
||||
private boolean isShopIdRequestParam(Parameter parameter) {
|
||||
RequestParam requestParam = parameter.getAnnotation(RequestParam.class);
|
||||
return requestParam != null && Long.class.equals(parameter.getType());
|
||||
}
|
||||
|
||||
private OrderVO order(Long shopId) {
|
||||
OrderVO order = new OrderVO();
|
||||
order.setId(shopId);
|
||||
order.setShopId(shopId);
|
||||
return order;
|
||||
}
|
||||
}
|
||||
-101
@@ -1,101 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.order.service.impl;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.dto.AfterSaleApplyDTO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.dto.AfterSaleAuditDTO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.entity.AfterSaleDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.entity.AfterSaleLogDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.message.entity.SystemMessageDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.AfterSaleLogMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.AfterSaleMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.message.mapper.SystemMessageMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.vo.AfterSaleVO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.common.Result;
|
||||
class AfterSaleServiceImplTest {
|
||||
|
||||
@Mock
|
||||
private AfterSaleMapper afterSaleMapper;
|
||||
@Mock
|
||||
private AfterSaleLogMapper afterSaleLogMapper;
|
||||
@Mock
|
||||
private OrderMapper orderMapper;
|
||||
@Mock
|
||||
private SystemMessageMapper systemMessageMapper;
|
||||
|
||||
private AfterSaleServiceImpl service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
service = new AfterSaleServiceImpl(afterSaleMapper, afterSaleLogMapper, orderMapper, systemMessageMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void applyCreatesPendingAfterSaleForOwnedOrder() {
|
||||
OrderDO order = order();
|
||||
when(orderMapper.selectById(1L)).thenReturn(order);
|
||||
when(afterSaleMapper.insert(any(AfterSaleDO.class))).thenAnswer(invocation -> {
|
||||
AfterSaleDO afterSale = invocation.getArgument(0);
|
||||
afterSale.setId(100L);
|
||||
return 1;
|
||||
});
|
||||
|
||||
AfterSaleApplyDTO dto = new AfterSaleApplyDTO();
|
||||
dto.setOrderId(1L);
|
||||
dto.setType("REFUND_CONSULT");
|
||||
dto.setReason("Need help");
|
||||
dto.setRefundAmount(new BigDecimal("20.00"));
|
||||
|
||||
AfterSaleVO result = service.apply(2L, dto);
|
||||
|
||||
assertThat(result.getStatus()).isEqualTo("PENDING");
|
||||
ArgumentCaptor<AfterSaleLogDO> logCaptor = ArgumentCaptor.forClass(AfterSaleLogDO.class);
|
||||
verify(afterSaleLogMapper).insert(logCaptor.capture());
|
||||
assertThat(logCaptor.getValue().getAction()).isEqualTo("CREATE");
|
||||
}
|
||||
|
||||
@Test
|
||||
void approveChangesStatusAndNotifiesCustomer() {
|
||||
AfterSaleDO afterSale = new AfterSaleDO();
|
||||
afterSale.setId(100L);
|
||||
afterSale.setOrderId(1L);
|
||||
afterSale.setUserId(2L);
|
||||
afterSale.setShopId(9L);
|
||||
afterSale.setStatus("PENDING");
|
||||
when(afterSaleMapper.selectById(100L)).thenReturn(afterSale);
|
||||
|
||||
AfterSaleAuditDTO dto = new AfterSaleAuditDTO();
|
||||
dto.setAuditReason("OK");
|
||||
AfterSaleVO result = service.approve(900L, 100L, dto);
|
||||
|
||||
assertThat(result.getStatus()).isEqualTo("APPROVED");
|
||||
verify(afterSaleMapper).updateById(afterSale);
|
||||
verify(systemMessageMapper).insert(any(SystemMessageDO.class));
|
||||
}
|
||||
|
||||
private OrderDO order() {
|
||||
OrderDO order = new OrderDO();
|
||||
order.setId(1L);
|
||||
order.setOrderNo("ORD1");
|
||||
order.setUserId(2L);
|
||||
order.setShopId(9L);
|
||||
order.setActualAmount(new BigDecimal("88.00"));
|
||||
order.setStatus(1);
|
||||
order.setIsDelete(0);
|
||||
return order;
|
||||
}
|
||||
}
|
||||
-296
@@ -1,296 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.order.service.impl;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.common.BusinessException;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.dto.CheckoutPreviewDTO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.dto.OrderItemDTO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.entity.CartDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.CouponDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.entity.ShopDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.entity.ProductDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.CartMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.marketing.mapper.CouponMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderItemMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.mapper.ProductMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.ShopMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.planning.mapper.AppointmentReservationMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.planning.service.AppointmentCapacityService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.marketing.service.CouponService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.support.BookableArtistSupport;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.support.UserShopBindingSupport;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.vo.CheckoutPreviewVO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.UserCouponVO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
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.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class OrderServiceImplCheckoutPreviewTest {
|
||||
|
||||
@Mock
|
||||
private ProductMapper productMapper;
|
||||
@Mock
|
||||
private CartMapper cartMapper;
|
||||
@Mock
|
||||
private CouponMapper couponMapper;
|
||||
@Mock
|
||||
private OrderItemMapper orderItemMapper;
|
||||
@Mock
|
||||
private UserMapper userMapper;
|
||||
@Mock
|
||||
private ShopMapper shopMapper;
|
||||
@Mock
|
||||
private CouponService couponService;
|
||||
@Mock
|
||||
private BookableArtistSupport bookableArtistSupport;
|
||||
@Mock
|
||||
private UserShopBindingSupport userShopBindingSupport;
|
||||
@Mock
|
||||
private AppointmentCapacityService appointmentCapacityService;
|
||||
@Mock
|
||||
private AppointmentReservationMapper appointmentReservationMapper;
|
||||
|
||||
private OrderServiceImpl service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
service = new OrderServiceImpl();
|
||||
ReflectionTestUtils.setField(service, "productMapper", productMapper);
|
||||
ReflectionTestUtils.setField(service, "cartMapper", cartMapper);
|
||||
ReflectionTestUtils.setField(service, "couponMapper", couponMapper);
|
||||
ReflectionTestUtils.setField(service, "orderItemMapper", orderItemMapper);
|
||||
ReflectionTestUtils.setField(service, "userMapper", userMapper);
|
||||
ReflectionTestUtils.setField(service, "shopMapper", shopMapper);
|
||||
ReflectionTestUtils.setField(service, "couponService", couponService);
|
||||
ReflectionTestUtils.setField(service, "bookableArtistSupport", bookableArtistSupport);
|
||||
ReflectionTestUtils.setField(service, "userShopBindingSupport", userShopBindingSupport);
|
||||
ReflectionTestUtils.setField(service, "appointmentCapacityService", appointmentCapacityService);
|
||||
ReflectionTestUtils.setField(service, "appointmentReservationMapper", appointmentReservationMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void checkoutPreviewExplainsBestAvailableCouponAndUnavailableReasons() {
|
||||
ProductDO product = product(100L, "温柔法式", "法式,通勤", new BigDecimal("100.00"));
|
||||
CartDO cartItem = cartItem(100L, 2);
|
||||
UserCouponVO vipCoupon = couponOption(300L, 300L, "SYSTEM_VIP", "黄金VIP自动90折券", 1, "9.0", null, null);
|
||||
UserCouponVO userCoupon = couponOption(400L, 500L, "USER_COUPON", "满150减30", 2, null, "150.00", "30.00");
|
||||
|
||||
when(productMapper.selectById(100L)).thenReturn(product);
|
||||
when(cartMapper.selectByUserIdAndProductId(20L, 100L)).thenReturn(cartItem);
|
||||
when(userMapper.selectById(20L)).thenReturn(user("黄金"));
|
||||
when(userMapper.selectById(30L)).thenReturn(artist(30L));
|
||||
when(bookableArtistSupport.isBookableServiceUser(any(UserDO.class))).thenReturn(true);
|
||||
when(userShopBindingSupport.canUserAccessShop(20L, 9L, false, null)).thenReturn(true);
|
||||
when(userShopBindingSupport.isUserAccessibleInShop(30L, 9L)).thenReturn(true);
|
||||
when(couponService.getAvailableCoupons(20L, "法式,通勤", 200.0, 9L)).thenReturn(List.of(userCoupon, vipCoupon));
|
||||
when(couponMapper.selectById(300L)).thenReturn(coupon(300L, "黄金VIP自动90折券", 1, new BigDecimal("9.0"), null, null, 9L));
|
||||
when(couponMapper.selectById(400L)).thenReturn(coupon(400L, "满150减30", 2, null, new BigDecimal("150.00"), new BigDecimal("30.00"), 9L));
|
||||
when(couponMapper.selectList(any())).thenReturn(List.of(
|
||||
coupon(600L, "满300减80", 2, null, new BigDecimal("300.00"), new BigDecimal("80.00"), 9L),
|
||||
coupon(700L, "其他门店券", 2, null, new BigDecimal("50.00"), new BigDecimal("5.00"), 10L)
|
||||
));
|
||||
|
||||
CheckoutPreviewVO preview = service.checkoutPreview(20L, order(100L, 2));
|
||||
|
||||
assertThat(preview.getSubtotalAmount()).isEqualByComparingTo("200.00");
|
||||
assertThat(preview.getSavedAmount()).isEqualByComparingTo("30.00");
|
||||
assertThat(preview.getPayableAmount()).isEqualByComparingTo("170.00");
|
||||
assertThat(preview.getBestCoupon().getCouponName()).isEqualTo("满150减30");
|
||||
assertThat(preview.getAvailableCoupons()).extracting("couponName")
|
||||
.containsExactly("满150减30", "黄金VIP自动90折券");
|
||||
assertThat(preview.getUnavailableCoupons()).extracting("couponName")
|
||||
.containsExactly("满300减80", "其他门店券");
|
||||
assertThat(preview.getUnavailableCoupons()).extracting("unavailableReason")
|
||||
.containsExactly("还差 ¥100.00 可用", "仅限其他门店使用");
|
||||
assertThat(preview.getVipTip()).isEqualTo("黄金VIP本单可省 ¥20.00,已为你计算。");
|
||||
assertThat(preview.getSummaryText()).isEqualTo("参考价小计 ¥200.00,预估优惠 ¥30.00,预估应付 ¥170.00。");
|
||||
assertThat(ReflectionTestUtils.getField(preview, "bookingAvailable")).isEqualTo(true);
|
||||
assertThat((List<?>) ReflectionTestUtils.getField(preview, "bookingIssues")).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void checkoutPreviewReportsBookingIssuesWithoutReservingCapacity() {
|
||||
ProductDO product = product(100L, "夜间款", "通勤", new BigDecimal("80.00"));
|
||||
product.setApproximateDuration("60分钟");
|
||||
product.setBookableArtists("77");
|
||||
CartDO cartItem = cartItem(100L, 1);
|
||||
LocalDateTime appointmentTime = LocalDateTime.now().plusDays(1)
|
||||
.withHour(17)
|
||||
.withMinute(30)
|
||||
.withSecond(0)
|
||||
.withNano(0);
|
||||
|
||||
when(productMapper.selectById(100L)).thenReturn(product);
|
||||
when(cartMapper.selectByUserIdAndProductId(20L, 100L)).thenReturn(cartItem);
|
||||
when(userMapper.selectById(77L)).thenReturn(artist(77L));
|
||||
when(bookableArtistSupport.isBookableServiceUser(any(UserDO.class))).thenReturn(true);
|
||||
when(userShopBindingSupport.canUserAccessShop(20L, 9L, false, null)).thenReturn(true);
|
||||
when(userShopBindingSupport.isUserAccessibleInShop(77L, 9L)).thenReturn(true);
|
||||
when(shopMapper.selectById(9L)).thenReturn(shop("09:00-18:00"));
|
||||
when(couponService.getAvailableCoupons(20L, "通勤", 80.0, 9L)).thenReturn(List.of());
|
||||
when(couponMapper.selectList(any())).thenReturn(List.of());
|
||||
|
||||
CheckoutPreviewVO preview = service.checkoutPreview(20L, order(100L, 1, 77L, appointmentTime));
|
||||
|
||||
assertThat(preview.getSubtotalAmount()).isEqualByComparingTo("80.00");
|
||||
assertThat(ReflectionTestUtils.getField(preview, "bookingAvailable")).isEqualTo(false);
|
||||
List<?> bookingIssues = (List<?>) ReflectionTestUtils.getField(preview, "bookingIssues");
|
||||
assertThat(bookingIssues).hasSize(1);
|
||||
Object issue = bookingIssues.get(0);
|
||||
assertThat(ReflectionTestUtils.getField(issue, "code")).isEqualTo("BUSINESS_HOURS");
|
||||
assertThat(ReflectionTestUtils.getField(issue, "message").toString()).contains("营业时间");
|
||||
assertThat(ReflectionTestUtils.getField(issue, "productId")).isEqualTo(100L);
|
||||
assertThat(ReflectionTestUtils.getField(issue, "productTitle")).isEqualTo("夜间款");
|
||||
verifyNoInteractions(appointmentCapacityService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void checkoutPreviewReportsReservationOccupancyConflict() {
|
||||
ProductDO product = product(100L, "Classic", "regular", new BigDecimal("80.00"));
|
||||
product.setApproximateDuration("60");
|
||||
product.setBookableArtists("77");
|
||||
CartDO cartItem = cartItem(100L, 1);
|
||||
LocalDateTime appointmentTime = LocalDateTime.now().plusDays(1)
|
||||
.withHour(10)
|
||||
.withMinute(0)
|
||||
.withSecond(0)
|
||||
.withNano(0);
|
||||
LocalDateTime appointmentEndTime = appointmentTime.plusHours(1);
|
||||
|
||||
when(productMapper.selectById(100L)).thenReturn(product);
|
||||
when(cartMapper.selectByUserIdAndProductId(20L, 100L)).thenReturn(cartItem);
|
||||
when(userMapper.selectById(77L)).thenReturn(artist(77L));
|
||||
when(bookableArtistSupport.isBookableServiceUser(any(UserDO.class))).thenReturn(true);
|
||||
when(userShopBindingSupport.canUserAccessShop(20L, 9L, false, null)).thenReturn(true);
|
||||
when(userShopBindingSupport.isUserAccessibleInShop(77L, 9L)).thenReturn(true);
|
||||
when(shopMapper.selectById(9L)).thenReturn(shop("09:00-18:00"));
|
||||
when(appointmentReservationMapper.countOverlappingActive(77L, appointmentTime, appointmentEndTime)).thenReturn(1);
|
||||
when(couponService.getAvailableCoupons(20L, "regular", 80.0, 9L)).thenReturn(List.of());
|
||||
when(couponMapper.selectList(any())).thenReturn(List.of());
|
||||
|
||||
CheckoutPreviewVO preview = service.checkoutPreview(20L, order(100L, 1, 77L, appointmentTime));
|
||||
|
||||
assertThat(ReflectionTestUtils.getField(preview, "bookingAvailable")).isEqualTo(false);
|
||||
List<?> bookingIssues = (List<?>) ReflectionTestUtils.getField(preview, "bookingIssues");
|
||||
assertThat(bookingIssues).hasSize(1);
|
||||
Object issue = bookingIssues.get(0);
|
||||
assertThat(ReflectionTestUtils.getField(issue, "code")).isEqualTo("EXISTING_CONFLICT");
|
||||
assertThat(ReflectionTestUtils.getField(issue, "productId")).isEqualTo(100L);
|
||||
verifyNoInteractions(appointmentCapacityService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createOrderReturnsBusinessCodeForBookingValidationBeforeLocking() {
|
||||
assertThatThrownBy(() -> service.createOrder(20L, null))
|
||||
.isInstanceOfSatisfying(BusinessException.class, exception -> {
|
||||
assertThat(exception.getCode()).isEqualTo(409);
|
||||
assertThat(exception.getMessage()).isEqualTo("订单项不能为空");
|
||||
});
|
||||
}
|
||||
|
||||
private CheckoutPreviewDTO order(Long productId, Integer quantity) {
|
||||
return order(productId, quantity, 30L, LocalDateTime.now().plusDays(1)
|
||||
.withHour(10)
|
||||
.withMinute(0)
|
||||
.withSecond(0)
|
||||
.withNano(0));
|
||||
}
|
||||
|
||||
private CheckoutPreviewDTO order(Long productId, Integer quantity, Long artistId, LocalDateTime appointmentTime) {
|
||||
OrderItemDTO item = new OrderItemDTO();
|
||||
item.setProductId(productId);
|
||||
item.setQuantity(quantity);
|
||||
item.setArtistId(artistId);
|
||||
item.setAppointmentTime(appointmentTime.toString());
|
||||
|
||||
CheckoutPreviewDTO dto = new CheckoutPreviewDTO();
|
||||
dto.setItems(List.of(item));
|
||||
return dto;
|
||||
}
|
||||
|
||||
private ProductDO product(Long id, String title, String tags, BigDecimal price) {
|
||||
ProductDO product = new ProductDO();
|
||||
product.setId(id);
|
||||
product.setTitle(title);
|
||||
product.setTags(tags);
|
||||
product.setPrice(price);
|
||||
product.setShopId(9L);
|
||||
product.setIsDelete(0);
|
||||
return product;
|
||||
}
|
||||
|
||||
private ShopDO shop(String businessHours) {
|
||||
ShopDO shop = new ShopDO();
|
||||
shop.setId(9L);
|
||||
shop.setBusinessHours(businessHours);
|
||||
shop.setIsDelete(0);
|
||||
return shop;
|
||||
}
|
||||
|
||||
private CartDO cartItem(Long productId, Integer quantity) {
|
||||
CartDO item = new CartDO();
|
||||
item.setUserId(20L);
|
||||
item.setProductId(productId);
|
||||
item.setQuantity(quantity);
|
||||
item.setIsDelete(0);
|
||||
return item;
|
||||
}
|
||||
|
||||
private UserDO user(String level) {
|
||||
UserDO user = new UserDO();
|
||||
user.setId(20L);
|
||||
user.setLevel(level);
|
||||
user.setIsDelete(0);
|
||||
return user;
|
||||
}
|
||||
|
||||
private UserDO artist(Long id) {
|
||||
UserDO artist = new UserDO();
|
||||
artist.setId(id);
|
||||
artist.setStatus(1);
|
||||
artist.setIsDelete(0);
|
||||
return artist;
|
||||
}
|
||||
|
||||
private CouponDO coupon(Long id, String name, Integer type, BigDecimal discountValue, BigDecimal minAmount, BigDecimal reduceAmount, Long shopId) {
|
||||
CouponDO coupon = new CouponDO();
|
||||
coupon.setId(id);
|
||||
coupon.setCouponName(name);
|
||||
coupon.setCouponType(type);
|
||||
coupon.setDiscountValue(discountValue);
|
||||
coupon.setMinAmount(minAmount);
|
||||
coupon.setReduceAmount(reduceAmount);
|
||||
coupon.setShopId(shopId);
|
||||
coupon.setStatus(1);
|
||||
coupon.setStartTime(LocalDateTime.now().minusDays(1));
|
||||
coupon.setEndTime(LocalDateTime.now().plusDays(1));
|
||||
coupon.setIsDelete(0);
|
||||
return coupon;
|
||||
}
|
||||
|
||||
private UserCouponVO couponOption(Long id, Long couponId, String sourceType, String name, Integer type, String discountValue, String minAmount, String reduceAmount) {
|
||||
UserCouponVO coupon = new UserCouponVO();
|
||||
coupon.setId(id);
|
||||
coupon.setCouponId(couponId);
|
||||
coupon.setSourceType(sourceType);
|
||||
coupon.setCouponName(name);
|
||||
coupon.setCouponType(type);
|
||||
coupon.setDiscountValue(discountValue);
|
||||
coupon.setMinAmount(minAmount);
|
||||
coupon.setReduceAmount(reduceAmount);
|
||||
return coupon;
|
||||
}
|
||||
}
|
||||
-557
@@ -1,557 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.order.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.dto.OrderArtistChangeRejectDTO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.dto.OrderArtistChangeRequestDTO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.dto.OrderArtistReviewSubmitDTO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.entity.NailArtistInfoDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderArtistChangeRequestDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderArtistReviewDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderItemDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.entity.ProductDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.message.entity.SystemMessageDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.NailArtistInfoMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderArtistChangeRequestMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderArtistReviewMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderItemMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.mapper.ProductMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.message.mapper.SystemMessageMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.planning.service.AppointmentCapacityService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.integration.service.BusinessEventOutboxService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.support.BookableArtistSupport;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.file.support.ObjectStorageUrlSupport;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.support.UserShopBindingSupport;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
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.eq;
|
||||
import static org.mockito.Mockito.inOrder;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class OrderServiceImplReviewChangeTest {
|
||||
|
||||
@Mock
|
||||
private OrderMapper orderMapper;
|
||||
@Mock
|
||||
private OrderItemMapper orderItemMapper;
|
||||
@Mock
|
||||
private OrderArtistReviewMapper orderArtistReviewMapper;
|
||||
@Mock
|
||||
private OrderArtistChangeRequestMapper orderArtistChangeRequestMapper;
|
||||
@Mock
|
||||
private ProductMapper productMapper;
|
||||
@Mock
|
||||
private UserMapper userMapper;
|
||||
@Mock
|
||||
private SystemMessageMapper systemMessageMapper;
|
||||
@Mock
|
||||
private NailArtistInfoMapper nailArtistInfoMapper;
|
||||
@Mock
|
||||
private ObjectStorageUrlSupport objectStorageUrlSupport;
|
||||
@Mock
|
||||
private UserShopBindingSupport userShopBindingSupport;
|
||||
@Mock
|
||||
private BookableArtistSupport bookableArtistSupport;
|
||||
@Mock
|
||||
private BusinessEventOutboxService businessEventOutboxService;
|
||||
@Mock
|
||||
private AppointmentCapacityService appointmentCapacityService;
|
||||
|
||||
private OrderServiceImpl service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
service = new OrderServiceImpl();
|
||||
ReflectionTestUtils.setField(service, "orderMapper", orderMapper);
|
||||
ReflectionTestUtils.setField(service, "orderItemMapper", orderItemMapper);
|
||||
ReflectionTestUtils.setField(service, "orderArtistReviewMapper", orderArtistReviewMapper);
|
||||
ReflectionTestUtils.setField(service, "orderArtistChangeRequestMapper", orderArtistChangeRequestMapper);
|
||||
ReflectionTestUtils.setField(service, "productMapper", productMapper);
|
||||
ReflectionTestUtils.setField(service, "userMapper", userMapper);
|
||||
ReflectionTestUtils.setField(service, "systemMessageMapper", systemMessageMapper);
|
||||
ReflectionTestUtils.setField(service, "nailArtistInfoMapper", nailArtistInfoMapper);
|
||||
ReflectionTestUtils.setField(service, "objectStorageUrlSupport", objectStorageUrlSupport);
|
||||
ReflectionTestUtils.setField(service, "userShopBindingSupport", userShopBindingSupport);
|
||||
ReflectionTestUtils.setField(service, "bookableArtistSupport", bookableArtistSupport);
|
||||
ReflectionTestUtils.setField(service, "businessEventOutboxService", businessEventOutboxService);
|
||||
ReflectionTestUtils.setField(service, "appointmentCapacityService", appointmentCapacityService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void processOrderCompletionUpdatesStatusAndEnqueuesOutboxEvent() {
|
||||
OrderDO order = pendingOrder();
|
||||
when(orderMapper.selectById(1L)).thenReturn(order);
|
||||
when(orderMapper.updateStatusIfCurrent(1L, 1, 2)).thenReturn(1);
|
||||
|
||||
service.processOrder(1L, 2);
|
||||
|
||||
verify(orderMapper).updateStatusIfCurrent(1L, 1, 2);
|
||||
verify(businessEventOutboxService).enqueueOrderCompleted(1L);
|
||||
verify(orderArtistReviewMapper, never()).insert(any(OrderArtistReviewDO.class));
|
||||
verify(systemMessageMapper, never()).insert(any(SystemMessageDO.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void processOrderCompletionRejectsConcurrentStatusChangeBeforeSideEffects() {
|
||||
OrderDO order = pendingOrder();
|
||||
when(orderMapper.selectById(1L)).thenReturn(order);
|
||||
when(orderMapper.updateStatusIfCurrent(1L, 1, 2)).thenReturn(0);
|
||||
|
||||
assertThatThrownBy(() -> service.processOrder(1L, 2))
|
||||
.isInstanceOf(RuntimeException.class)
|
||||
.hasMessageContaining("状态已变化");
|
||||
|
||||
verify(businessEventOutboxService, never()).enqueueOrderCompleted(any());
|
||||
verify(orderArtistReviewMapper, never()).insert(any(OrderArtistReviewDO.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void outboxOrderCompletedCreatesPendingReviewTaskAndPopupMessageOnce() {
|
||||
OrderDO order = completedOrder();
|
||||
OrderItemDO item = orderItem();
|
||||
ProductDO product = product();
|
||||
UserDO artist = artist(30L);
|
||||
|
||||
when(orderItemMapper.selectByOrderId(1L)).thenReturn(List.of(item));
|
||||
when(orderArtistReviewMapper.selectByOrderItemId(10L)).thenReturn(null);
|
||||
when(productMapper.selectById(20L)).thenReturn(product);
|
||||
when(userMapper.selectById(30L)).thenReturn(artist);
|
||||
when(orderArtistReviewMapper.insert(any(OrderArtistReviewDO.class))).thenAnswer(invocation -> {
|
||||
OrderArtistReviewDO review = invocation.getArgument(0);
|
||||
review.setId(1000L);
|
||||
return 1;
|
||||
});
|
||||
|
||||
service.createPendingArtistReviewTasksAndNotifyFromOutbox(order);
|
||||
|
||||
ArgumentCaptor<OrderArtistReviewDO> reviewCaptor = ArgumentCaptor.forClass(OrderArtistReviewDO.class);
|
||||
verify(orderArtistReviewMapper).insert(reviewCaptor.capture());
|
||||
OrderArtistReviewDO review = reviewCaptor.getValue();
|
||||
assertThat(review.getOrderItemId()).isEqualTo(10L);
|
||||
assertThat(review.getCustomerId()).isEqualTo(2L);
|
||||
assertThat(review.getArtistId()).isEqualTo(30L);
|
||||
assertThat(review.getStatus()).isZero();
|
||||
|
||||
ArgumentCaptor<SystemMessageDO> messageCaptor = ArgumentCaptor.forClass(SystemMessageDO.class);
|
||||
verify(systemMessageMapper).insert(messageCaptor.capture());
|
||||
assertThat(messageCaptor.getValue().getBusinessType()).isEqualTo("ORDER_ARTIST_REVIEW");
|
||||
assertThat(messageCaptor.getValue().getTargetIds()).isEqualTo("2");
|
||||
}
|
||||
|
||||
@Test
|
||||
void outboxOrderCompletedDoesNotCreateDuplicateReviewTask() {
|
||||
OrderDO order = completedOrder();
|
||||
OrderItemDO item = orderItem();
|
||||
OrderArtistReviewDO existingReview = new OrderArtistReviewDO();
|
||||
existingReview.setId(99L);
|
||||
|
||||
when(orderItemMapper.selectByOrderId(1L)).thenReturn(List.of(item));
|
||||
when(orderArtistReviewMapper.selectByOrderItemId(10L)).thenReturn(existingReview);
|
||||
|
||||
service.createPendingArtistReviewTasksAndNotifyFromOutbox(order);
|
||||
|
||||
verify(orderArtistReviewMapper, never()).insert(any(OrderArtistReviewDO.class));
|
||||
verify(systemMessageMapper, never()).insert(any(SystemMessageDO.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void outboxOrderCompletedRecoversWhenConcurrentReviewTaskInsertWins() {
|
||||
OrderDO order = completedOrder();
|
||||
OrderItemDO item = orderItem();
|
||||
OrderArtistReviewDO existingReview = new OrderArtistReviewDO();
|
||||
existingReview.setId(99L);
|
||||
|
||||
when(orderItemMapper.selectByOrderId(1L)).thenReturn(List.of(item));
|
||||
when(orderArtistReviewMapper.selectByOrderItemId(10L)).thenReturn(null, existingReview);
|
||||
when(orderArtistReviewMapper.insert(any(OrderArtistReviewDO.class))).thenThrow(new DuplicateKeyException("duplicate"));
|
||||
|
||||
service.createPendingArtistReviewTasksAndNotifyFromOutbox(order);
|
||||
|
||||
verify(orderArtistReviewMapper).insert(any(OrderArtistReviewDO.class));
|
||||
verify(orderArtistReviewMapper, never()).updateById(existingReview);
|
||||
}
|
||||
|
||||
@Test
|
||||
void outboxOrderCompletedReusesExistingReviewReminderMessage() {
|
||||
OrderDO order = completedOrder();
|
||||
OrderItemDO item = orderItem();
|
||||
ProductDO product = product();
|
||||
SystemMessageDO existingMessage = new SystemMessageDO();
|
||||
existingMessage.setId(300L);
|
||||
|
||||
when(orderItemMapper.selectByOrderId(1L)).thenReturn(List.of(item));
|
||||
when(orderArtistReviewMapper.selectByOrderItemId(10L)).thenReturn(null);
|
||||
when(productMapper.selectById(20L)).thenReturn(product);
|
||||
when(userMapper.selectById(30L)).thenReturn(artist(30L));
|
||||
when(orderArtistReviewMapper.insert(any(OrderArtistReviewDO.class))).thenAnswer(invocation -> {
|
||||
OrderArtistReviewDO review = invocation.getArgument(0);
|
||||
review.setId(1000L);
|
||||
return 1;
|
||||
});
|
||||
when(systemMessageMapper.selectOne(any(LambdaQueryWrapper.class))).thenReturn(existingMessage);
|
||||
|
||||
service.createPendingArtistReviewTasksAndNotifyFromOutbox(order);
|
||||
|
||||
ArgumentCaptor<OrderArtistReviewDO> reviewCaptor = ArgumentCaptor.forClass(OrderArtistReviewDO.class);
|
||||
verify(orderArtistReviewMapper).insert(reviewCaptor.capture());
|
||||
verify(systemMessageMapper, never()).insert(any(SystemMessageDO.class));
|
||||
verify(orderArtistReviewMapper).updateById(reviewCaptor.getValue());
|
||||
assertThat(reviewCaptor.getValue().getReminderMessageId()).isEqualTo(300L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void outboxOrderCompletedRecoversReviewReminderWhenConcurrentInsertWins() {
|
||||
OrderDO order = completedOrder();
|
||||
OrderItemDO item = orderItem();
|
||||
ProductDO product = product();
|
||||
SystemMessageDO existingMessage = new SystemMessageDO();
|
||||
existingMessage.setId(301L);
|
||||
|
||||
when(orderItemMapper.selectByOrderId(1L)).thenReturn(List.of(item));
|
||||
when(orderArtistReviewMapper.selectByOrderItemId(10L)).thenReturn(null);
|
||||
when(productMapper.selectById(20L)).thenReturn(product);
|
||||
when(userMapper.selectById(30L)).thenReturn(artist(30L));
|
||||
when(orderArtistReviewMapper.insert(any(OrderArtistReviewDO.class))).thenAnswer(invocation -> {
|
||||
OrderArtistReviewDO review = invocation.getArgument(0);
|
||||
review.setId(1001L);
|
||||
return 1;
|
||||
});
|
||||
when(systemMessageMapper.selectOne(any(LambdaQueryWrapper.class))).thenReturn(null, existingMessage);
|
||||
when(systemMessageMapper.insert(any(SystemMessageDO.class))).thenThrow(new DuplicateKeyException("duplicate"));
|
||||
|
||||
service.createPendingArtistReviewTasksAndNotifyFromOutbox(order);
|
||||
|
||||
ArgumentCaptor<SystemMessageDO> messageCaptor = ArgumentCaptor.forClass(SystemMessageDO.class);
|
||||
verify(systemMessageMapper).insert(messageCaptor.capture());
|
||||
assertThat(messageCaptor.getValue().getIdempotencyKey()).isEqualTo("ORDER_ARTIST_REVIEW:1001:2");
|
||||
ArgumentCaptor<OrderArtistReviewDO> reviewCaptor = ArgumentCaptor.forClass(OrderArtistReviewDO.class);
|
||||
verify(orderArtistReviewMapper).updateById(reviewCaptor.capture());
|
||||
assertThat(reviewCaptor.getValue().getReminderMessageId()).isEqualTo(301L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void requestArtistChangeLocksOrderItemBeforeCheckingPendingRequest() {
|
||||
OrderDO order = pendingOrder();
|
||||
OrderItemDO item = orderItem();
|
||||
ProductDO product = product();
|
||||
UserDO requester = artist(30L);
|
||||
UserDO requestedArtist = artist(31L);
|
||||
product.setBookableArtists("30,31");
|
||||
OrderArtistChangeRequestDTO dto = new OrderArtistChangeRequestDTO();
|
||||
dto.setOrderId(1L);
|
||||
dto.setOrderItemId(10L);
|
||||
dto.setRequestedArtistId(31L);
|
||||
dto.setReason("临时调整");
|
||||
|
||||
when(userMapper.selectById(30L)).thenReturn(requester);
|
||||
when(userMapper.selectById(31L)).thenReturn(requestedArtist);
|
||||
when(orderMapper.selectById(1L)).thenReturn(order);
|
||||
when(orderItemMapper.selectByIdForUpdate(10L)).thenReturn(item);
|
||||
when(productMapper.selectById(20L)).thenReturn(product);
|
||||
when(userShopBindingSupport.isUserAccessibleInShop(30L, 3L)).thenReturn(true);
|
||||
when(userShopBindingSupport.isUserAccessibleInShop(31L, 3L)).thenReturn(true);
|
||||
when(bookableArtistSupport.isBookableServiceUser(requestedArtist)).thenReturn(true);
|
||||
when(bookableArtistSupport.isValidBookableArtist(3L, 31L)).thenReturn(true);
|
||||
|
||||
service.requestArtistChange(30L, dto);
|
||||
|
||||
ArgumentCaptor<OrderArtistChangeRequestDO> requestCaptor = ArgumentCaptor.forClass(OrderArtistChangeRequestDO.class);
|
||||
verify(orderArtistChangeRequestMapper).insert(requestCaptor.capture());
|
||||
assertThat(requestCaptor.getValue().getPendingKey()).isEqualTo("ORDER_ITEM:10");
|
||||
inOrder(orderItemMapper, orderArtistChangeRequestMapper).verify(orderItemMapper).selectByIdForUpdate(10L);
|
||||
inOrder(orderItemMapper, orderArtistChangeRequestMapper).verify(orderArtistChangeRequestMapper).selectPendingByOrderItemId(10L);
|
||||
verify(orderItemMapper, never()).selectById(10L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void approveArtistChangeRejectsAlreadyProcessedRequest() {
|
||||
OrderArtistChangeRequestDO request = pendingChangeRequest();
|
||||
request.setStatus("APPROVED");
|
||||
when(orderArtistChangeRequestMapper.selectById(500L)).thenReturn(request);
|
||||
|
||||
assertThatThrownBy(() -> service.approveArtistChange(500L, 2L, 0))
|
||||
.isInstanceOf(RuntimeException.class)
|
||||
.hasMessage("改派申请已处理");
|
||||
|
||||
verify(orderItemMapper, never()).selectByIdForUpdate(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void approveArtistChangeUsesPendingConditionalUpdateBeforeAssigningArtist() {
|
||||
OrderArtistChangeRequestDO request = pendingChangeRequest();
|
||||
OrderDO order = pendingOrder();
|
||||
OrderItemDO item = orderItem();
|
||||
ProductDO product = product();
|
||||
UserDO newArtist = artist(31L);
|
||||
product.setBookableArtists("30,31");
|
||||
|
||||
when(orderArtistChangeRequestMapper.selectById(500L)).thenReturn(request);
|
||||
when(orderMapper.selectById(1L)).thenReturn(order);
|
||||
when(orderItemMapper.selectByIdForUpdate(10L)).thenReturn(item);
|
||||
when(productMapper.selectById(20L)).thenReturn(product);
|
||||
when(userMapper.selectById(31L)).thenReturn(newArtist);
|
||||
when(userShopBindingSupport.isUserAccessibleInShop(31L, 3L)).thenReturn(true);
|
||||
when(bookableArtistSupport.isBookableServiceUser(newArtist)).thenReturn(true);
|
||||
when(bookableArtistSupport.isValidBookableArtist(3L, 31L)).thenReturn(true);
|
||||
when(orderArtistChangeRequestMapper.approvePending(eq(500L), any(LocalDateTime.class))).thenReturn(1);
|
||||
|
||||
service.approveArtistChange(500L, 2L, 0);
|
||||
|
||||
inOrder(orderArtistChangeRequestMapper, orderItemMapper)
|
||||
.verify(orderArtistChangeRequestMapper).approvePending(eq(500L), any(LocalDateTime.class));
|
||||
inOrder(orderArtistChangeRequestMapper, orderItemMapper).verify(orderItemMapper).updateById(item);
|
||||
assertThat(item.getArtistId()).isEqualTo(31L);
|
||||
verify(orderArtistChangeRequestMapper, never()).updateById(any(OrderArtistChangeRequestDO.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void approveArtistChangeRejectsConcurrentProcessedRequestBeforeAssigningArtist() {
|
||||
OrderArtistChangeRequestDO request = pendingChangeRequest();
|
||||
OrderDO order = pendingOrder();
|
||||
OrderItemDO item = orderItem();
|
||||
ProductDO product = product();
|
||||
UserDO newArtist = artist(31L);
|
||||
product.setBookableArtists("30,31");
|
||||
|
||||
when(orderArtistChangeRequestMapper.selectById(500L)).thenReturn(request);
|
||||
when(orderMapper.selectById(1L)).thenReturn(order);
|
||||
when(orderItemMapper.selectByIdForUpdate(10L)).thenReturn(item);
|
||||
when(productMapper.selectById(20L)).thenReturn(product);
|
||||
when(userMapper.selectById(31L)).thenReturn(newArtist);
|
||||
when(userShopBindingSupport.isUserAccessibleInShop(31L, 3L)).thenReturn(true);
|
||||
when(bookableArtistSupport.isBookableServiceUser(newArtist)).thenReturn(true);
|
||||
when(bookableArtistSupport.isValidBookableArtist(3L, 31L)).thenReturn(true);
|
||||
when(orderArtistChangeRequestMapper.approvePending(eq(500L), any(LocalDateTime.class))).thenReturn(0);
|
||||
|
||||
assertThatThrownBy(() -> service.approveArtistChange(500L, 2L, 0))
|
||||
.isInstanceOf(RuntimeException.class)
|
||||
.hasMessage("改派申请已处理");
|
||||
|
||||
verify(orderItemMapper, never()).updateById(any(OrderItemDO.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void approveArtistChangeExpiresPendingRequestBeforeProcessing() {
|
||||
OrderArtistChangeRequestDO request = pendingChangeRequest();
|
||||
request.setExpireTime(LocalDateTime.now().minusMinutes(1));
|
||||
when(orderArtistChangeRequestMapper.selectById(500L)).thenReturn(request);
|
||||
|
||||
assertThatThrownBy(() -> service.approveArtistChange(500L, 2L, 0))
|
||||
.isInstanceOf(RuntimeException.class)
|
||||
.hasMessageContaining("过期");
|
||||
|
||||
verify(orderArtistChangeRequestMapper).expirePendingById(eq(500L), any(LocalDateTime.class));
|
||||
verify(orderItemMapper, never()).selectByIdForUpdate(any());
|
||||
verify(orderItemMapper, never()).updateById(any(OrderItemDO.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectArtistChangeUsesPendingConditionalUpdate() {
|
||||
OrderArtistChangeRequestDO request = pendingChangeRequest();
|
||||
when(orderArtistChangeRequestMapper.selectById(500L)).thenReturn(request);
|
||||
when(orderArtistChangeRequestMapper.rejectPending(eq(500L), eq("客户不方便"), any(LocalDateTime.class))).thenReturn(1);
|
||||
|
||||
OrderArtistChangeRejectDTO dto = new OrderArtistChangeRejectDTO();
|
||||
dto.setRejectReason("客户不方便");
|
||||
|
||||
service.rejectArtistChange(500L, 2L, 0, dto);
|
||||
|
||||
verify(orderArtistChangeRequestMapper).rejectPending(eq(500L), eq("客户不方便"), any(LocalDateTime.class));
|
||||
verify(orderArtistChangeRequestMapper, never()).updateById(any(OrderArtistChangeRequestDO.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectArtistChangeRejectsConcurrentProcessedRequest() {
|
||||
OrderArtistChangeRequestDO request = pendingChangeRequest();
|
||||
when(orderArtistChangeRequestMapper.selectById(500L)).thenReturn(request);
|
||||
when(orderArtistChangeRequestMapper.rejectPending(eq(500L), eq("客户不方便"), any(LocalDateTime.class))).thenReturn(0);
|
||||
|
||||
OrderArtistChangeRejectDTO dto = new OrderArtistChangeRejectDTO();
|
||||
dto.setRejectReason("客户不方便");
|
||||
|
||||
assertThatThrownBy(() -> service.rejectArtistChange(500L, 2L, 0, dto))
|
||||
.isInstanceOf(RuntimeException.class)
|
||||
.hasMessage("改派申请已处理");
|
||||
|
||||
verify(orderArtistChangeRequestMapper, never()).updateById(any(OrderArtistChangeRequestDO.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listMyPendingArtistChangeRequestsExpiresDueRequestsFirst() {
|
||||
when(orderArtistChangeRequestMapper.selectPendingByUserId(2L)).thenReturn(List.of());
|
||||
|
||||
assertThat(service.listMyPendingArtistChangeRequests(2L, 0)).isEmpty();
|
||||
|
||||
verify(orderArtistChangeRequestMapper).expirePendingBefore(any(LocalDateTime.class));
|
||||
verify(orderArtistChangeRequestMapper).selectPendingByUserId(2L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void listOrderArtistChangeRequestsExpiresDueRequestsAndReturnsHistoryForAccessibleOrder() {
|
||||
OrderDO order = pendingOrder();
|
||||
OrderArtistChangeRequestDO approved = pendingChangeRequest();
|
||||
approved.setStatus("APPROVED");
|
||||
approved.setApprovedTime(LocalDateTime.now().minusHours(2));
|
||||
OrderArtistChangeRequestDO rejected = pendingChangeRequest();
|
||||
rejected.setId(501L);
|
||||
rejected.setStatus("REJECTED");
|
||||
rejected.setRejectedTime(LocalDateTime.now().minusHours(1));
|
||||
rejected.setRejectReason("时间不合适");
|
||||
|
||||
when(orderMapper.selectById(1L)).thenReturn(order);
|
||||
when(orderArtistChangeRequestMapper.selectByOrderId(1L)).thenReturn(List.of(approved, rejected));
|
||||
when(productMapper.selectById(20L)).thenReturn(product());
|
||||
when(userMapper.selectById(30L)).thenReturn(artist(30L));
|
||||
when(userMapper.selectById(31L)).thenReturn(artist(31L));
|
||||
|
||||
assertThat(service.listOrderArtistChangeRequests(1L, 2L, 0))
|
||||
.extracting("id")
|
||||
.containsExactly(500L, 501L);
|
||||
|
||||
verify(orderArtistChangeRequestMapper).expirePendingBefore(any(LocalDateTime.class));
|
||||
verify(orderArtistChangeRequestMapper).selectByOrderId(1L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void listOrderArtistChangeRequestsRejectsInaccessibleOrder() {
|
||||
OrderDO order = pendingOrder();
|
||||
when(orderMapper.selectById(1L)).thenReturn(order);
|
||||
when(orderItemMapper.selectByOrderId(1L)).thenReturn(List.of(orderItem()));
|
||||
|
||||
assertThatThrownBy(() -> service.listOrderArtistChangeRequests(1L, 99L, 0))
|
||||
.isInstanceOf(RuntimeException.class)
|
||||
.hasMessageContaining("ORDER_ARTIST_CHANGE_FORBIDDEN");
|
||||
|
||||
verify(orderArtistChangeRequestMapper).expirePendingBefore(any(LocalDateTime.class));
|
||||
verify(orderArtistChangeRequestMapper, never()).selectByOrderId(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void submitArtistReviewRequiresHalfPointRating() {
|
||||
OrderArtistReviewDO review = pendingReview();
|
||||
when(orderArtistReviewMapper.selectById(100L)).thenReturn(review);
|
||||
|
||||
OrderArtistReviewSubmitDTO dto = new OrderArtistReviewSubmitDTO();
|
||||
dto.setRating(new BigDecimal("4.25"));
|
||||
|
||||
assertThatThrownBy(() -> service.submitArtistReview(100L, 2L, dto))
|
||||
.isInstanceOf(RuntimeException.class)
|
||||
.hasMessage("评分必须按0.5分递增");
|
||||
|
||||
verify(orderArtistReviewMapper, never()).updateById(any(OrderArtistReviewDO.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void submitArtistReviewAcceptsValidRatingAndRefreshesArtistRating() {
|
||||
OrderArtistReviewDO review = pendingReview();
|
||||
NailArtistInfoDO artistInfo = new NailArtistInfoDO();
|
||||
artistInfo.setId(200L);
|
||||
when(orderArtistReviewMapper.selectById(100L)).thenReturn(review);
|
||||
when(orderArtistReviewMapper.selectAverageSubmittedRatingByArtistId(30L)).thenReturn(new BigDecimal("4.75"));
|
||||
when(nailArtistInfoMapper.selectOne(any(LambdaQueryWrapper.class))).thenReturn(artistInfo);
|
||||
|
||||
OrderArtistReviewSubmitDTO dto = new OrderArtistReviewSubmitDTO();
|
||||
dto.setRating(new BigDecimal("4.5"));
|
||||
dto.setContent("服务很细致");
|
||||
|
||||
assertThat(service.submitArtistReview(100L, 2L, dto).getRatingScore()).isEqualByComparingTo("4.5");
|
||||
|
||||
verify(orderArtistReviewMapper).updateById(review);
|
||||
verify(nailArtistInfoMapper).updateById(artistInfo);
|
||||
assertThat(artistInfo.getRating()).isEqualByComparingTo("4.8");
|
||||
}
|
||||
|
||||
private OrderDO pendingOrder() {
|
||||
OrderDO order = new OrderDO();
|
||||
order.setId(1L);
|
||||
order.setUserId(2L);
|
||||
order.setShopId(3L);
|
||||
order.setStatus(1);
|
||||
order.setIsDelete(0);
|
||||
return order;
|
||||
}
|
||||
|
||||
private OrderDO completedOrder() {
|
||||
OrderDO order = pendingOrder();
|
||||
order.setStatus(2);
|
||||
return order;
|
||||
}
|
||||
|
||||
private OrderItemDO orderItem() {
|
||||
OrderItemDO item = new OrderItemDO();
|
||||
item.setId(10L);
|
||||
item.setOrderId(1L);
|
||||
item.setProductId(20L);
|
||||
item.setArtistId(30L);
|
||||
item.setQuantity(1);
|
||||
item.setIsDelete(0);
|
||||
return item;
|
||||
}
|
||||
|
||||
private ProductDO product() {
|
||||
ProductDO product = new ProductDO();
|
||||
product.setId(20L);
|
||||
product.setTitle("凝胶美甲");
|
||||
product.setIsDelete(0);
|
||||
return product;
|
||||
}
|
||||
|
||||
private UserDO artist(Long id) {
|
||||
UserDO artist = new UserDO();
|
||||
artist.setId(id);
|
||||
artist.setType(3);
|
||||
artist.setStatus(1);
|
||||
artist.setIsDelete(0);
|
||||
artist.setNickname("美甲师" + id);
|
||||
return artist;
|
||||
}
|
||||
|
||||
private OrderArtistReviewDO pendingReview() {
|
||||
OrderArtistReviewDO review = new OrderArtistReviewDO();
|
||||
review.setId(100L);
|
||||
review.setOrderId(1L);
|
||||
review.setOrderItemId(10L);
|
||||
review.setProductId(20L);
|
||||
review.setCustomerId(2L);
|
||||
review.setArtistId(30L);
|
||||
review.setStatus(0);
|
||||
review.setIsDelete(0);
|
||||
return review;
|
||||
}
|
||||
|
||||
private OrderArtistChangeRequestDO pendingChangeRequest() {
|
||||
OrderArtistChangeRequestDO request = new OrderArtistChangeRequestDO();
|
||||
request.setId(500L);
|
||||
request.setOrderId(1L);
|
||||
request.setOrderItemId(10L);
|
||||
request.setProductId(20L);
|
||||
request.setShopId(3L);
|
||||
request.setCustomerId(2L);
|
||||
request.setFromArtistId(30L);
|
||||
request.setToArtistId(31L);
|
||||
request.setRequesterId(30L);
|
||||
request.setStatus("PENDING");
|
||||
request.setExpireTime(LocalDateTime.now().plusDays(1));
|
||||
request.setIsDelete(0);
|
||||
return request;
|
||||
}
|
||||
}
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.order.support;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
class OrderStateMachineTest {
|
||||
|
||||
@Test
|
||||
void allowsPriceConfirmingOrderToBecomePendingServiceOrCancelled() {
|
||||
assertThat(OrderStateMachine.isAllowedTransition(0, 1)).isTrue();
|
||||
assertThat(OrderStateMachine.isAllowedTransition(0, 3)).isTrue();
|
||||
assertThat(OrderStateMachine.isAllowedTransition(0, 2)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void allowsPendingOrderToCompleteOrCancel() {
|
||||
assertThat(OrderStateMachine.isAllowedTransition(1, 2)).isTrue();
|
||||
assertThat(OrderStateMachine.isAllowedTransition(1, 3)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsInvalidOrderTransition() {
|
||||
assertThat(OrderStateMachine.isAllowedTransition(2, 3)).isFalse();
|
||||
assertThatThrownBy(() -> OrderStateMachine.requireAllowedTransition(2, 3))
|
||||
.isInstanceOf(RuntimeException.class)
|
||||
.hasMessage("订单状态不允许处理");
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsUnknownTargetStatus() {
|
||||
assertThatThrownBy(() -> OrderStatus.requireKnown(9))
|
||||
.isInstanceOf(RuntimeException.class)
|
||||
.hasMessage("无效的订单状态");
|
||||
}
|
||||
}
|
||||
-124
@@ -1,124 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.payment.service.impl;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.payment.entity.PaymentOrderDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.payment.entity.RefundOrderDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.payment.mapper.PaymentOrderMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.payment.mapper.RefundOrderMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.payment.vo.PaymentOrderVO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.payment.vo.RefundOrderVO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.common.Result;
|
||||
class PaymentServiceImplTest {
|
||||
|
||||
@Mock
|
||||
private OrderMapper orderMapper;
|
||||
@Mock
|
||||
private PaymentOrderMapper paymentOrderMapper;
|
||||
@Mock
|
||||
private RefundOrderMapper refundOrderMapper;
|
||||
|
||||
private PaymentServiceImpl service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
service = new PaymentServiceImpl(orderMapper, paymentOrderMapper, refundOrderMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void prepareOrderPaymentCreatesManualPaymentOrderForUnpaidOrder() {
|
||||
OrderDO order = order();
|
||||
when(orderMapper.selectById(1L)).thenReturn(order);
|
||||
when(paymentOrderMapper.selectLatestByOrderId(1L)).thenReturn(null);
|
||||
when(paymentOrderMapper.insert(any(PaymentOrderDO.class))).thenAnswer(invocation -> {
|
||||
PaymentOrderDO payment = invocation.getArgument(0);
|
||||
payment.setId(100L);
|
||||
return 1;
|
||||
});
|
||||
|
||||
PaymentOrderVO result = service.prepareOrderPayment(2L, 1L);
|
||||
|
||||
assertThat(result.getOrderId()).isEqualTo(1L);
|
||||
assertThat(result.getStatus()).isEqualTo("PAYING");
|
||||
assertThat(result.getPayAmount()).isEqualByComparingTo("88.00");
|
||||
ArgumentCaptor<PaymentOrderDO> captor = ArgumentCaptor.forClass(PaymentOrderDO.class);
|
||||
verify(paymentOrderMapper).insert(captor.capture());
|
||||
assertThat(captor.getValue().getChannel()).isEqualTo("MANUAL");
|
||||
}
|
||||
|
||||
@Test
|
||||
void manualConfirmOrderPaidUpdatesPaymentAndOrderSnapshot() {
|
||||
OrderDO order = order();
|
||||
PaymentOrderDO payment = new PaymentOrderDO();
|
||||
payment.setId(100L);
|
||||
payment.setOrderId(1L);
|
||||
payment.setStatus("PAYING");
|
||||
payment.setPayAmount(new BigDecimal("88.00"));
|
||||
when(orderMapper.selectById(1L)).thenReturn(order);
|
||||
when(paymentOrderMapper.selectLatestByOrderId(1L)).thenReturn(payment);
|
||||
|
||||
PaymentOrderVO result = service.manualConfirmOrderPaid(900L, 1L, "cash");
|
||||
|
||||
assertThat(result.getStatus()).isEqualTo("PAID");
|
||||
verify(paymentOrderMapper).updateById(payment);
|
||||
verify(orderMapper).updateById(order);
|
||||
assertThat(order.getPaymentStatus()).isEqualTo("PAID");
|
||||
assertThat(order.getPaidAmount()).isEqualByComparingTo("88.00");
|
||||
}
|
||||
|
||||
@Test
|
||||
void manualRefundOrderCreatesRefundAndUpdatesOrderSnapshot() {
|
||||
OrderDO order = order();
|
||||
order.setPaymentStatus("PAID");
|
||||
PaymentOrderDO payment = new PaymentOrderDO();
|
||||
payment.setId(100L);
|
||||
payment.setOrderId(1L);
|
||||
payment.setStatus("PAID");
|
||||
payment.setPayAmount(new BigDecimal("88.00"));
|
||||
payment.setPaidAmount(new BigDecimal("88.00"));
|
||||
payment.setChannel("MANUAL");
|
||||
when(orderMapper.selectById(1L)).thenReturn(order);
|
||||
when(paymentOrderMapper.selectLatestByOrderId(1L)).thenReturn(payment);
|
||||
when(refundOrderMapper.insert(any(RefundOrderDO.class))).thenAnswer(invocation -> {
|
||||
RefundOrderDO refund = invocation.getArgument(0);
|
||||
refund.setId(200L);
|
||||
return 1;
|
||||
});
|
||||
|
||||
RefundOrderVO result = service.manualRefundOrder(900L, 1L, 300L, "manual");
|
||||
|
||||
assertThat(result.getStatus()).isEqualTo("REFUNDED");
|
||||
assertThat(result.getRefundAmount()).isEqualByComparingTo("88.00");
|
||||
verify(refundOrderMapper).insert(any(RefundOrderDO.class));
|
||||
verify(orderMapper).updateById(order);
|
||||
assertThat(order.getPaymentStatus()).isEqualTo("REFUNDED");
|
||||
assertThat(order.getRefundStatus()).isEqualTo("REFUNDED");
|
||||
}
|
||||
|
||||
private OrderDO order() {
|
||||
OrderDO order = new OrderDO();
|
||||
order.setId(1L);
|
||||
order.setOrderNo("ORD1");
|
||||
order.setUserId(2L);
|
||||
order.setShopId(9L);
|
||||
order.setActualAmount(new BigDecimal("88.00"));
|
||||
order.setStatus(1);
|
||||
order.setIsDelete(0);
|
||||
order.setPaymentStatus("UNPAID");
|
||||
return order;
|
||||
}
|
||||
}
|
||||
-175
@@ -1,175 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.planning.service.impl;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.modules.planning.entity.AppointmentReservationDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.planning.mapper.AppointmentReservationMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.ArtistScheduleMapper;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class AppointmentCapacityServiceImplTest {
|
||||
|
||||
@Mock
|
||||
private AppointmentReservationMapper reservationMapper;
|
||||
@Mock
|
||||
private ArtistScheduleMapper scheduleMapper;
|
||||
|
||||
private AppointmentCapacityServiceImpl service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
service = new AppointmentCapacityServiceImpl(reservationMapper, scheduleMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void reserveRejectsWhenConfiguredCapacityIsFull() {
|
||||
LocalDateTime start = LocalDateTime.of(2026, 6, 1, 10, 0);
|
||||
LocalDateTime end = start.plusHours(1);
|
||||
when(scheduleMapper.selectCoveringSchedule(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime()))
|
||||
.thenReturn(schedule(2));
|
||||
when(reservationMapper.countOverlappingActiveForUpdate(30L, start, end)).thenReturn(2);
|
||||
|
||||
assertThatThrownBy(() -> service.reserveOrThrow(1L, 10L, 9L, 30L, "French", start, end))
|
||||
.isInstanceOf(RuntimeException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void reserveCreatesConfirmedReservationWhenCapacityRemains() {
|
||||
LocalDateTime start = LocalDateTime.of(2026, 6, 1, 10, 0);
|
||||
LocalDateTime end = start.plusHours(1);
|
||||
when(scheduleMapper.selectCoveringSchedule(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime()))
|
||||
.thenReturn(schedule(2));
|
||||
when(reservationMapper.countOverlappingActiveForUpdate(30L, start, end)).thenReturn(1);
|
||||
|
||||
service.reserveOrThrow(1L, 10L, 9L, 30L, "French", start, end);
|
||||
|
||||
ArgumentCaptor<AppointmentReservationDO> captor = ArgumentCaptor.forClass(AppointmentReservationDO.class);
|
||||
verify(reservationMapper).insert(captor.capture());
|
||||
AppointmentReservationDO reservation = captor.getValue();
|
||||
assertThat(reservation.getOrderId()).isEqualTo(1L);
|
||||
assertThat(reservation.getOrderItemId()).isEqualTo(10L);
|
||||
assertThat(reservation.getArtistId()).isEqualTo(30L);
|
||||
assertThat(reservation.getStatus()).isEqualTo("CONFIRMED");
|
||||
}
|
||||
|
||||
@Test
|
||||
void reservePendingQuoteCreatesPendingReservationWithClientRequestId() {
|
||||
LocalDateTime start = LocalDateTime.of(2026, 6, 1, 10, 0);
|
||||
LocalDateTime end = start.plusHours(1);
|
||||
when(scheduleMapper.selectCoveringSchedule(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime()))
|
||||
.thenReturn(schedule(2));
|
||||
when(reservationMapper.countOverlappingActiveForUpdate(30L, start, end)).thenReturn(0);
|
||||
|
||||
service.reservePendingQuoteOrThrow(1L, 10L, 9L, 30L, "French", start, end, "req-1");
|
||||
|
||||
ArgumentCaptor<AppointmentReservationDO> captor = ArgumentCaptor.forClass(AppointmentReservationDO.class);
|
||||
verify(reservationMapper).insert(captor.capture());
|
||||
AppointmentReservationDO reservation = captor.getValue();
|
||||
assertThat(reservation.getStatus()).isEqualTo("PENDING_QUOTE");
|
||||
assertThat(reservation.getClientRequestId()).isEqualTo("req-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void confirmReservationUpgradesExistingPendingReservationWithoutSelfConflict() {
|
||||
LocalDateTime start = LocalDateTime.of(2026, 6, 1, 10, 0);
|
||||
LocalDateTime end = start.plusHours(1);
|
||||
when(scheduleMapper.selectCoveringSchedule(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime()))
|
||||
.thenReturn(schedule(2));
|
||||
when(reservationMapper.countOverlappingActiveForUpdateExcludingOrderItem(30L, 10L, start, end)).thenReturn(0);
|
||||
when(reservationMapper.updateActiveReservationForOrderItemWithClientRequest(10L, 1L, 9L, 30L, "French", start, end, "CONFIRMED", null))
|
||||
.thenReturn(1);
|
||||
|
||||
service.confirmReservationOrThrow(1L, 10L, 9L, 30L, "French", start, end);
|
||||
|
||||
verify(reservationMapper).updateActiveReservationForOrderItemWithClientRequest(10L, 1L, 9L, 30L, "French", start, end, "CONFIRMED", null);
|
||||
verify(reservationMapper, never()).insert(org.mockito.ArgumentMatchers.any(AppointmentReservationDO.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void reserveRejectsWhenNoCoveringScheduleExists() {
|
||||
LocalDateTime start = LocalDateTime.of(2026, 6, 2, 10, 0);
|
||||
LocalDateTime end = start.plusHours(1);
|
||||
when(scheduleMapper.selectCoveringSchedule(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime()))
|
||||
.thenReturn(null);
|
||||
|
||||
assertThatThrownBy(() -> service.reserveOrThrow(1L, 10L, 9L, 30L, "French", start, end))
|
||||
.isInstanceOf(RuntimeException.class)
|
||||
.hasMessageContaining("涓嶅彲棰勭害");
|
||||
|
||||
verify(reservationMapper, never()).insert(org.mockito.ArgumentMatchers.any(AppointmentReservationDO.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void reserveRejectsWhenCoveringScheduleIsDisabled() {
|
||||
LocalDateTime start = LocalDateTime.of(2026, 6, 1, 10, 0);
|
||||
LocalDateTime end = start.plusHours(1);
|
||||
ArtistScheduleDO disabled = schedule(1);
|
||||
disabled.setStatus(0);
|
||||
when(scheduleMapper.selectCoveringSchedule(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime()))
|
||||
.thenReturn(disabled);
|
||||
|
||||
assertThatThrownBy(() -> service.reserveOrThrow(1L, 10L, 9L, 30L, "French", start, end))
|
||||
.isInstanceOf(RuntimeException.class)
|
||||
.hasMessageContaining("涓嶅彲棰勭害");
|
||||
|
||||
verify(reservationMapper, never()).insert(org.mockito.ArgumentMatchers.any(AppointmentReservationDO.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void reserveRejectsWhenCoveringScheduleHasZeroCapacity() {
|
||||
LocalDateTime start = LocalDateTime.of(2026, 6, 1, 10, 0);
|
||||
LocalDateTime end = start.plusHours(1);
|
||||
when(scheduleMapper.selectCoveringSchedule(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime()))
|
||||
.thenReturn(schedule(0));
|
||||
|
||||
assertThatThrownBy(() -> service.reserveOrThrow(1L, 10L, 9L, 30L, "French", start, end))
|
||||
.isInstanceOf(RuntimeException.class)
|
||||
.hasMessageContaining("涓嶅彲棰勭害");
|
||||
|
||||
verify(reservationMapper, never()).insert(org.mockito.ArgumentMatchers.any(AppointmentReservationDO.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void moveReservationRechecksNewArtistCapacityBeforeUpdatingArtist() {
|
||||
LocalDateTime start = LocalDateTime.of(2026, 6, 1, 10, 0);
|
||||
LocalDateTime end = start.plusHours(1);
|
||||
when(scheduleMapper.selectCoveringSchedule(9L, 31L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime()))
|
||||
.thenReturn(schedule(1));
|
||||
when(reservationMapper.countOverlappingActiveForUpdateExcludingOrderItem(31L, 10L, start, end)).thenReturn(0);
|
||||
when(reservationMapper.updateActiveReservationForOrderItem(10L, 1L, 9L, 31L, "French", start, end, "CONFIRMED"))
|
||||
.thenReturn(1);
|
||||
|
||||
service.moveReservationForArtistChange(1L, 10L, 9L, 30L, 31L, "French", start, end);
|
||||
|
||||
verify(reservationMapper).updateActiveReservationForOrderItem(10L, 1L, 9L, 31L, "French", start, end, "CONFIRMED");
|
||||
verify(reservationMapper, never()).releaseByOrderItem(10L, "RELEASED");
|
||||
verify(reservationMapper, never()).insert(org.mockito.ArgumentMatchers.any(AppointmentReservationDO.class));
|
||||
}
|
||||
|
||||
private ArtistScheduleDO schedule(int capacity) {
|
||||
ArtistScheduleDO schedule = new ArtistScheduleDO();
|
||||
schedule.setShopId(9L);
|
||||
schedule.setArtistId(30L);
|
||||
schedule.setWorkDate(LocalDate.of(2026, 6, 1));
|
||||
schedule.setStartTime(LocalTime.of(10, 0));
|
||||
schedule.setEndTime(LocalTime.of(20, 0));
|
||||
schedule.setCapacity(capacity);
|
||||
schedule.setStatus(1);
|
||||
schedule.setIsDelete(0);
|
||||
return schedule;
|
||||
}
|
||||
}
|
||||
-305
@@ -1,305 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.planning.service.impl;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.ArtistScheduleMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.NailArtistInfoMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderItemDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderItemMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.service.OrderService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.planning.dto.PlanningAppointmentCreateDTO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.planning.entity.AppointmentReservationDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.planning.mapper.AppointmentReservationMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.planning.service.AppointmentCapacityService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.entity.ProductDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.mapper.ProductMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.entity.ShopDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.ShopMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class PlanningServiceImplTest {
|
||||
|
||||
@Mock
|
||||
private AdminScopeHelper adminScopeHelper;
|
||||
|
||||
@Mock
|
||||
private UserMapper userMapper;
|
||||
|
||||
@Mock
|
||||
private NailArtistInfoMapper nailArtistInfoMapper;
|
||||
|
||||
@Mock
|
||||
private ArtistScheduleMapper artistScheduleMapper;
|
||||
|
||||
@Mock
|
||||
private AppointmentReservationMapper appointmentReservationMapper;
|
||||
|
||||
@Mock
|
||||
private OrderMapper orderMapper;
|
||||
|
||||
@Mock
|
||||
private OrderItemMapper orderItemMapper;
|
||||
|
||||
@Mock
|
||||
private ProductMapper productMapper;
|
||||
|
||||
@Mock
|
||||
private ShopMapper shopMapper;
|
||||
|
||||
@Mock
|
||||
private AppointmentCapacityService appointmentCapacityService;
|
||||
|
||||
@Mock
|
||||
private OrderService orderService;
|
||||
|
||||
@Mock
|
||||
private TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
|
||||
|
||||
private PlanningServiceImpl planningService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
planningService = new PlanningServiceImpl(
|
||||
adminScopeHelper,
|
||||
userMapper,
|
||||
nailArtistInfoMapper,
|
||||
artistScheduleMapper,
|
||||
appointmentReservationMapper,
|
||||
orderMapper,
|
||||
orderItemMapper,
|
||||
productMapper,
|
||||
shopMapper,
|
||||
appointmentCapacityService,
|
||||
orderService,
|
||||
snowflakeIdGenerator
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createAppointmentShouldHideManualProductFromFront() {
|
||||
UserDO manager = user(2, 8L);
|
||||
UserDO artist = user(3, 8L);
|
||||
artist.setId(20L);
|
||||
UserDO customer = user(0, 8L);
|
||||
customer.setId(30L);
|
||||
ShopDO shop = new ShopDO();
|
||||
shop.setBusinessHours("10:00-22:00");
|
||||
PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO();
|
||||
dto.setCustomerUserId(30L);
|
||||
dto.setArtistId(20L);
|
||||
dto.setAppointmentDate("2026-06-26");
|
||||
dto.setAppointmentTime("13:00");
|
||||
dto.setDurationMinutes(90);
|
||||
dto.setManualProductTitle(" 日落贝壳 ");
|
||||
dto.setManualProductPrice(new BigDecimal("168.00"));
|
||||
dto.setClientRequestId("manual-product-test");
|
||||
|
||||
when(adminScopeHelper.resolveShopScope(manager, null)).thenReturn(8L);
|
||||
when(productMapper.insert(any(ProductDO.class))).thenAnswer(invocation -> {
|
||||
ProductDO product = invocation.getArgument(0);
|
||||
product.setId(100L);
|
||||
return 1;
|
||||
});
|
||||
when(userMapper.selectById(20L)).thenReturn(artist);
|
||||
when(userMapper.selectById(30L)).thenReturn(customer);
|
||||
when(shopMapper.selectById(8L)).thenReturn(shop);
|
||||
when(snowflakeIdGenerator.nextIdString()).thenReturn("202606260001");
|
||||
when(orderMapper.insert(any(OrderDO.class))).thenAnswer(invocation -> {
|
||||
OrderDO order = invocation.getArgument(0);
|
||||
order.setId(200L);
|
||||
return 1;
|
||||
});
|
||||
when(orderItemMapper.insert(any(OrderItemDO.class))).thenAnswer(invocation -> {
|
||||
OrderItemDO item = invocation.getArgument(0);
|
||||
item.setId(300L);
|
||||
return 1;
|
||||
});
|
||||
when(orderItemMapper.selectById(300L)).thenAnswer(invocation -> {
|
||||
OrderItemDO item = new OrderItemDO();
|
||||
item.setId(300L);
|
||||
item.setOrderId(200L);
|
||||
item.setProductId(100L);
|
||||
item.setArtistId(20L);
|
||||
item.setQuantity(1);
|
||||
item.setAppointmentTime(LocalDateTime.of(2026, 6, 26, 13, 0));
|
||||
item.setIsDelete(0);
|
||||
return item;
|
||||
});
|
||||
when(orderMapper.selectById(200L)).thenAnswer(invocation -> {
|
||||
OrderDO order = new OrderDO();
|
||||
order.setId(200L);
|
||||
order.setUserId(30L);
|
||||
order.setShopId(8L);
|
||||
order.setStatus(1);
|
||||
order.setIsDelete(0);
|
||||
return order;
|
||||
});
|
||||
when(productMapper.selectById(100L)).thenAnswer(invocation -> {
|
||||
ProductDO product = new ProductDO();
|
||||
product.setId(100L);
|
||||
product.setShopId(8L);
|
||||
product.setTitle("日落贝壳");
|
||||
product.setPrice(new BigDecimal("168.00"));
|
||||
product.setApproximateDuration("90分钟");
|
||||
product.setFrontVisible(0);
|
||||
product.setSourceType("MANAGER_APPOINTMENT");
|
||||
product.setIsDelete(0);
|
||||
return product;
|
||||
});
|
||||
AppointmentReservationDO reservation = new AppointmentReservationDO();
|
||||
reservation.setOrderItemId(300L);
|
||||
reservation.setArtistId(20L);
|
||||
reservation.setProductTitle("日落贝壳");
|
||||
reservation.setAppointmentStartTime(LocalDateTime.of(2026, 6, 26, 13, 0));
|
||||
reservation.setAppointmentEndTime(LocalDateTime.of(2026, 6, 26, 14, 30));
|
||||
when(appointmentReservationMapper.selectOne(any())).thenReturn(reservation);
|
||||
when(userMapper.selectBatchIds(any())).thenReturn(List.of(customer));
|
||||
|
||||
planningService.createAppointment(manager, dto);
|
||||
|
||||
ArgumentCaptor<ProductDO> captor = ArgumentCaptor.forClass(ProductDO.class);
|
||||
org.mockito.Mockito.verify(productMapper).insert(captor.capture());
|
||||
ProductDO product = captor.getValue();
|
||||
assertThat(product.getTitle()).isEqualTo("日落贝壳");
|
||||
assertThat(product.getFrontVisible()).isZero();
|
||||
assertThat(product.getSourceType()).isEqualTo("MANAGER_APPOINTMENT");
|
||||
assertThat(product.getImageFileIds()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void calendarMarksMonthAvailabilityByContinuousNinetyMinuteWindow() {
|
||||
UserDO manager = user(2, 8L);
|
||||
UserDO freeArtist = user(3, 8L);
|
||||
freeArtist.setId(20L);
|
||||
freeArtist.setNickname("小王");
|
||||
UserDO shortShiftArtist = user(3, 8L);
|
||||
shortShiftArtist.setId(21L);
|
||||
shortShiftArtist.setNickname("小李");
|
||||
LocalDate date = LocalDate.of(2026, 6, 26);
|
||||
ShopDO shop = new ShopDO();
|
||||
shop.setBusinessHours("09:00-18:00");
|
||||
ArtistScheduleDO freeSchedule = schedule(20L, date, LocalTime.of(9, 0), LocalTime.of(12, 0));
|
||||
ArtistScheduleDO shortSchedule = schedule(21L, date, LocalTime.of(9, 0), LocalTime.of(10, 0));
|
||||
AppointmentReservationDO reservation = reservation(20L, 200L, 300L, date.atTime(10, 30), date.atTime(12, 0));
|
||||
OrderDO order = order(200L, 8L, 30L);
|
||||
OrderItemDO item = orderItem(300L, 200L, 100L, 20L, date.atTime(10, 30));
|
||||
ProductDO product = product(100L, 8L, "90分钟");
|
||||
UserDO customer = user(0, 8L);
|
||||
customer.setId(30L);
|
||||
customer.setNickname("测试客户");
|
||||
|
||||
when(adminScopeHelper.resolveShopScope(manager, null)).thenReturn(8L);
|
||||
when(shopMapper.selectById(8L)).thenReturn(shop);
|
||||
when(userMapper.selectList(any())).thenReturn(List.of(freeArtist, shortShiftArtist));
|
||||
when(nailArtistInfoMapper.selectList(any())).thenReturn(List.of());
|
||||
when(artistScheduleMapper.selectList(any())).thenReturn(List.of(freeSchedule, shortSchedule));
|
||||
when(appointmentReservationMapper.selectList(any())).thenReturn(List.of(reservation));
|
||||
when(orderItemMapper.selectList(any())).thenReturn(List.of());
|
||||
when(orderItemMapper.selectBatchIds(any())).thenReturn(List.of(item));
|
||||
when(orderMapper.selectBatchIds(any())).thenReturn(List.of(order));
|
||||
when(productMapper.selectBatchIds(any())).thenReturn(List.of(product));
|
||||
when(userMapper.selectBatchIds(any())).thenReturn(List.of(customer));
|
||||
|
||||
var calendar = planningService.getCalendar(manager, date, date, null);
|
||||
|
||||
var summary = calendar.getDaySummaries().get(0);
|
||||
assertThat(summary.getDayStatus()).isEqualTo("working");
|
||||
assertThat(summary.getArtistCounts())
|
||||
.extracting(count -> count.getArtistId() + ":" + count.getStatus())
|
||||
.contains("20:working", "21:full");
|
||||
}
|
||||
|
||||
private UserDO user(Integer type, Long shopId) {
|
||||
UserDO user = new UserDO();
|
||||
user.setId(10L + type);
|
||||
user.setType(type);
|
||||
user.setShopId(shopId);
|
||||
user.setIsDelete(0);
|
||||
user.setNickname("测试用户");
|
||||
user.setPhone("13800138000");
|
||||
return user;
|
||||
}
|
||||
|
||||
private ArtistScheduleDO schedule(Long artistId, LocalDate date, LocalTime startTime, LocalTime endTime) {
|
||||
ArtistScheduleDO schedule = new ArtistScheduleDO();
|
||||
schedule.setId(1000L + artistId);
|
||||
schedule.setShopId(8L);
|
||||
schedule.setArtistId(artistId);
|
||||
schedule.setWorkDate(date);
|
||||
schedule.setStartTime(startTime);
|
||||
schedule.setEndTime(endTime);
|
||||
schedule.setCapacity(1);
|
||||
schedule.setSlotMinutes(90);
|
||||
schedule.setStatus(1);
|
||||
schedule.setIsDelete(0);
|
||||
return schedule;
|
||||
}
|
||||
|
||||
private AppointmentReservationDO reservation(Long artistId, Long orderId, Long orderItemId,
|
||||
LocalDateTime startTime, LocalDateTime endTime) {
|
||||
AppointmentReservationDO reservation = new AppointmentReservationDO();
|
||||
reservation.setOrderId(orderId);
|
||||
reservation.setOrderItemId(orderItemId);
|
||||
reservation.setShopId(8L);
|
||||
reservation.setArtistId(artistId);
|
||||
reservation.setProductTitle("测试预约");
|
||||
reservation.setAppointmentStartTime(startTime);
|
||||
reservation.setAppointmentEndTime(endTime);
|
||||
reservation.setStatus("CONFIRMED");
|
||||
reservation.setIsDelete(0);
|
||||
return reservation;
|
||||
}
|
||||
|
||||
private OrderDO order(Long orderId, Long shopId, Long customerId) {
|
||||
OrderDO order = new OrderDO();
|
||||
order.setId(orderId);
|
||||
order.setShopId(shopId);
|
||||
order.setUserId(customerId);
|
||||
order.setStatus(1);
|
||||
order.setIsDelete(0);
|
||||
return order;
|
||||
}
|
||||
|
||||
private OrderItemDO orderItem(Long orderItemId, Long orderId, Long productId, Long artistId, LocalDateTime appointmentTime) {
|
||||
OrderItemDO item = new OrderItemDO();
|
||||
item.setId(orderItemId);
|
||||
item.setOrderId(orderId);
|
||||
item.setProductId(productId);
|
||||
item.setArtistId(artistId);
|
||||
item.setQuantity(1);
|
||||
item.setAppointmentTime(appointmentTime);
|
||||
item.setIsDelete(0);
|
||||
return item;
|
||||
}
|
||||
|
||||
private ProductDO product(Long productId, Long shopId, String durationText) {
|
||||
ProductDO product = new ProductDO();
|
||||
product.setId(productId);
|
||||
product.setShopId(shopId);
|
||||
product.setTitle("测试作品");
|
||||
product.setApproximateDuration(durationText);
|
||||
product.setIsDelete(0);
|
||||
return product;
|
||||
}
|
||||
}
|
||||
-43
@@ -1,43 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.planning.support;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.LocalTime;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class PlanningCalendarSupportTest {
|
||||
|
||||
@Test
|
||||
void shortNameUsesReadableSingleCharacterForDenseMonthCells() {
|
||||
assertEquals("王", PlanningCalendarSupport.shortName("小王"));
|
||||
assertEquals("李", PlanningCalendarSupport.shortName("李老师"));
|
||||
assertEquals("A", PlanningCalendarSupport.shortName("Alice"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void businessHoursFallbackToShopManagerPlanningDefaults() {
|
||||
PlanningCalendarSupport.BusinessHours hours = PlanningCalendarSupport.parseBusinessHours("10:00-22:00");
|
||||
assertEquals(LocalTime.of(10, 0), hours.start());
|
||||
assertEquals(LocalTime.of(22, 0), hours.end());
|
||||
|
||||
PlanningCalendarSupport.BusinessHours fallback = PlanningCalendarSupport.parseBusinessHours(null);
|
||||
assertEquals(LocalTime.of(10, 0), fallback.start());
|
||||
assertEquals(LocalTime.of(22, 0), fallback.end());
|
||||
}
|
||||
|
||||
@Test
|
||||
void durationParserSupportsChineseHourAndMinuteText() {
|
||||
assertEquals(90, PlanningCalendarSupport.parseDurationMinutes("1.5小时", 60));
|
||||
assertEquals(120, PlanningCalendarSupport.parseDurationMinutes("约120分钟", 60));
|
||||
assertEquals(60, PlanningCalendarSupport.parseDurationMinutes("", 60));
|
||||
}
|
||||
|
||||
@Test
|
||||
void dayStatusKeepsMonthViewOperationalAtAGlance() {
|
||||
assertEquals("rest", PlanningCalendarSupport.resolveDayStatus(0, false, false));
|
||||
assertEquals("free", PlanningCalendarSupport.resolveDayStatus(0, true, false));
|
||||
assertEquals("working", PlanningCalendarSupport.resolveDayStatus(2, true, false));
|
||||
assertEquals("full", PlanningCalendarSupport.resolveDayStatus(6, true, true));
|
||||
}
|
||||
}
|
||||
-102
@@ -1,102 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.product.controller.front;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.service.ProductService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.support.UserShopBindingSupport;
|
||||
import com.xiaowang.fingertipdesigner.core.support.security.UserSessionService;
|
||||
import com.xiaowang.fingertipdesigner.core.utils.JwtUtil;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.vo.ProductVO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class ProductControllerTest {
|
||||
|
||||
@Mock
|
||||
private ProductService productService;
|
||||
|
||||
@Mock
|
||||
private AdminScopeHelper adminScopeHelper;
|
||||
|
||||
@Mock
|
||||
private JwtUtil jwtUtil;
|
||||
|
||||
@Mock
|
||||
private UserSessionService userSessionService;
|
||||
|
||||
@Mock
|
||||
private UserShopBindingSupport userShopBindingSupport;
|
||||
|
||||
private ProductController controller;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
controller = new ProductController(productService, adminScopeHelper, jwtUtil, userSessionService, userShopBindingSupport);
|
||||
}
|
||||
|
||||
@Test
|
||||
void listAllProductsShouldUseCurrentShopFromValidToken() {
|
||||
MockHttpServletRequest request = authenticatedShopRequest(7L, 3L);
|
||||
when(productService.listPublicProductsByShopId(3L)).thenReturn(List.of(new ProductVO()));
|
||||
|
||||
controller.listAllProducts(request);
|
||||
|
||||
verify(productService).listPublicProductsByShopId(3L);
|
||||
verify(productService, never()).listPublicProducts();
|
||||
}
|
||||
|
||||
@Test
|
||||
void searchProductsShouldUseCurrentShopFromValidToken() {
|
||||
MockHttpServletRequest request = authenticatedShopRequest(7L, 3L);
|
||||
when(productService.searchProducts("猫眼", 3L)).thenReturn(List.of(new ProductVO()));
|
||||
|
||||
controller.searchProducts(request, "猫眼");
|
||||
|
||||
verify(productService).searchProducts("猫眼", 3L);
|
||||
verify(productService, never()).searchProducts("猫眼");
|
||||
}
|
||||
|
||||
@Test
|
||||
void listAllProductsShouldRemainPublicWithoutToken() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
when(productService.listPublicProducts()).thenReturn(List.of(new ProductVO()));
|
||||
|
||||
controller.listAllProducts(request);
|
||||
|
||||
verify(productService).listPublicProducts();
|
||||
verify(productService, never()).listPublicProductsByShopId(3L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void pagePublicProductsShouldPassGroupedTagIdsToService() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
|
||||
controller.pagePublicProducts(request, 1, 10, "", "", "11,22");
|
||||
|
||||
verify(productService).pagePublicProducts(1, 10, "", "", "11,22", null);
|
||||
}
|
||||
|
||||
private MockHttpServletRequest authenticatedShopRequest(Long userId, Long shopId) {
|
||||
String token = "access-token";
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addHeader("Authorization", "Bearer " + token);
|
||||
when(jwtUtil.validateToken(token)).thenReturn(true);
|
||||
when(jwtUtil.isAccessToken(token)).thenReturn(true);
|
||||
when(jwtUtil.getShopIdFromToken(token)).thenReturn(shopId);
|
||||
when(jwtUtil.getUserIdFromToken(token)).thenReturn(userId);
|
||||
when(jwtUtil.getSessionIdFromToken(token)).thenReturn("session-id");
|
||||
when(jwtUtil.getJtiFromToken(token)).thenReturn("jti");
|
||||
when(userSessionService.isAccessSessionActive(userId, "session-id", "jti")).thenReturn(true);
|
||||
when(userShopBindingSupport.canUserAccessShop(userId, shopId, false, null)).thenReturn(true);
|
||||
return request;
|
||||
}
|
||||
}
|
||||
-153
@@ -1,153 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.product.service.impl;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.config.AppCacheProperties;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.dto.ProductDTO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.entity.ProductDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.marketing.mapper.CouponMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.mapper.ProductMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.ShopMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.mapper.TagMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageFileService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.file.support.ObjectStorageUrlSupport;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.support.BookableArtistSupport;
|
||||
import com.xiaowang.fingertipdesigner.core.support.cache.MultiLevelCacheService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.vo.ProductVO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Duration;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.service.ProductService;
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class ProductServiceImplTest {
|
||||
|
||||
@Mock
|
||||
private ProductMapper productMapper;
|
||||
|
||||
@Mock
|
||||
private ObjectStorageFileService objectStorageFileService;
|
||||
|
||||
@Mock
|
||||
private ObjectStorageUrlSupport objectStorageUrlSupport;
|
||||
|
||||
@Mock
|
||||
private CouponMapper couponMapper;
|
||||
|
||||
@Mock
|
||||
private ShopMapper shopMapper;
|
||||
|
||||
@Mock
|
||||
private TagMapper tagMapper;
|
||||
|
||||
@Mock
|
||||
private BookableArtistSupport bookableArtistSupport;
|
||||
|
||||
@Mock
|
||||
private MultiLevelCacheService multiLevelCacheService;
|
||||
|
||||
private ProductServiceImpl productService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
AppCacheProperties cacheProperties = new AppCacheProperties();
|
||||
productService = new ProductServiceImpl(
|
||||
productMapper,
|
||||
objectStorageFileService,
|
||||
objectStorageUrlSupport,
|
||||
couponMapper,
|
||||
shopMapper,
|
||||
tagMapper,
|
||||
bookableArtistSupport,
|
||||
multiLevelCacheService,
|
||||
cacheProperties
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createProductShouldPersistTargetAudienceAndPrecautions() {
|
||||
ProductDTO dto = new ProductDTO();
|
||||
dto.setShopId(3L);
|
||||
dto.setTitle("French cat eye");
|
||||
dto.setDescription("soft shimmer");
|
||||
dto.setPrice(new BigDecimal("168.00"));
|
||||
dto.setTargetAudience("Short nails, daily office style");
|
||||
dto.setPrecautions("Avoid long hot baths within 24 hours");
|
||||
when(bookableArtistSupport.filterValidBookableArtists(3L, null)).thenReturn("");
|
||||
when(productMapper.insert(any(ProductDO.class))).thenAnswer(invocation -> {
|
||||
ProductDO product = invocation.getArgument(0);
|
||||
product.setId(99L);
|
||||
return 1;
|
||||
});
|
||||
|
||||
productService.createProduct(dto);
|
||||
|
||||
ArgumentCaptor<ProductDO> captor = ArgumentCaptor.forClass(ProductDO.class);
|
||||
org.mockito.Mockito.verify(productMapper).insert(captor.capture());
|
||||
assertEquals("Short nails, daily office style", captor.getValue().getTargetAudience());
|
||||
assertEquals("Avoid long hot baths within 24 hours", captor.getValue().getPrecautions());
|
||||
assertEquals(1, captor.getValue().getFrontVisible());
|
||||
assertEquals("BACKEND", captor.getValue().getSourceType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getProductByIdShouldExposeTargetAudienceAndPrecautions() {
|
||||
ProductDO product = new ProductDO();
|
||||
product.setId(99L);
|
||||
product.setShopId(3L);
|
||||
product.setTitle("French cat eye");
|
||||
product.setDescription("soft shimmer");
|
||||
product.setPrice(new BigDecimal("168.00"));
|
||||
product.setTargetAudience("Short nails, daily office style");
|
||||
product.setPrecautions("Avoid long hot baths within 24 hours");
|
||||
product.setIsDelete(0);
|
||||
when(productMapper.selectById(99L)).thenReturn(product);
|
||||
when(bookableArtistSupport.filterValidBookableArtists(3L, null)).thenReturn("");
|
||||
when(multiLevelCacheService.getOrLoad(
|
||||
anyString(),
|
||||
any(Duration.class),
|
||||
any(Duration.class),
|
||||
any(),
|
||||
any()
|
||||
)).thenAnswer(invocation -> ((java.util.function.Supplier<?>) invocation.getArgument(4)).get());
|
||||
|
||||
ProductVO productVO = productService.getProductById(99L);
|
||||
|
||||
assertEquals("Short nails, daily office style", productVO.getTargetAudience());
|
||||
assertEquals("Avoid long hot baths within 24 hours", productVO.getPrecautions());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getPublicProductByIdShouldHideInvisibleProduct() {
|
||||
ProductDO product = new ProductDO();
|
||||
product.setId(99L);
|
||||
product.setShopId(3L);
|
||||
product.setTitle("Manual appointment item");
|
||||
product.setDescription("hidden");
|
||||
product.setPrice(new BigDecimal("88.00"));
|
||||
product.setFrontVisible(0);
|
||||
product.setIsDelete(0);
|
||||
when(productMapper.selectById(99L)).thenReturn(product);
|
||||
when(multiLevelCacheService.getOrLoad(
|
||||
anyString(),
|
||||
any(Duration.class),
|
||||
any(Duration.class),
|
||||
any(),
|
||||
any()
|
||||
)).thenAnswer(invocation -> ((java.util.function.Supplier<?>) invocation.getArgument(4)).get());
|
||||
|
||||
ProductVO productVO = productService.getPublicProductById(99L);
|
||||
|
||||
assertNull(productVO);
|
||||
}
|
||||
}
|
||||
-73
@@ -1,73 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.product.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.xiaowang.fingertipdesigner.core.config.AppCacheProperties;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.entity.TagDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.ShopMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.mapper.TagMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.support.cache.MultiLevelCacheService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.vo.TagFilterGroupVO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class TagServiceImplTest {
|
||||
|
||||
private TagMapper tagMapper;
|
||||
private TagServiceImpl service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
tagMapper = mock(TagMapper.class);
|
||||
ShopMapper shopMapper = mock(ShopMapper.class);
|
||||
MultiLevelCacheService cacheService = mock(MultiLevelCacheService.class);
|
||||
AppCacheProperties cacheProperties = new AppCacheProperties();
|
||||
when(cacheService.getOrLoad(
|
||||
anyString(),
|
||||
any(Duration.class),
|
||||
any(Duration.class),
|
||||
any(TypeReference.class),
|
||||
any(Supplier.class)
|
||||
)).thenAnswer(invocation -> ((Supplier<?>) invocation.getArgument(4)).get());
|
||||
service = new TagServiceImpl(tagMapper, shopMapper, cacheService, cacheProperties);
|
||||
}
|
||||
|
||||
@Test
|
||||
void listFilterOptionsGroupsOnlyFrontVisibleTagsAndKeepsLegacyDefaults() {
|
||||
TagDO style = tag(1L, "日常", "风格", "通勤", 20, 1);
|
||||
TagDO legacy = tag(2L, "显白", null, null, null, null);
|
||||
TagDO hidden = tag(3L, "隐藏", "风格", "隐藏", 1, 0);
|
||||
when(tagMapper.selectList(any(LambdaQueryWrapper.class))).thenReturn(List.of(hidden, legacy, style));
|
||||
|
||||
List<TagFilterGroupVO> groups = service.listFilterOptions(null);
|
||||
|
||||
assertThat(groups).hasSize(2);
|
||||
assertThat(groups.get(0).getGroupName()).isEqualTo("风格");
|
||||
assertThat(groups.get(0).getTags()).extracting("displayName").containsExactly("通勤");
|
||||
assertThat(groups.get(1).getGroupName()).isEqualTo("其他");
|
||||
assertThat(groups.get(1).getTags()).extracting("displayName").containsExactly("显白");
|
||||
}
|
||||
|
||||
private TagDO tag(Long id, String tagName, String sceneGroup, String displayName, Integer sortOrder, Integer frontVisible) {
|
||||
TagDO tag = new TagDO();
|
||||
tag.setId(id);
|
||||
tag.setShopId(8L);
|
||||
tag.setTagName(tagName);
|
||||
tag.setSceneGroup(sceneGroup);
|
||||
tag.setDisplayName(displayName);
|
||||
tag.setSortOrder(sortOrder);
|
||||
tag.setFrontVisible(frontVisible);
|
||||
tag.setIsDelete(0);
|
||||
return tag;
|
||||
}
|
||||
}
|
||||
-46
@@ -1,46 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.security.controller.admin;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.common.Result;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.security.service.SecurityAuditLogService;
|
||||
import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.security.vo.SecurityAuditLogVO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class AdminSecurityAuditControllerTest {
|
||||
|
||||
@Mock
|
||||
private SecurityAuditLogService securityAuditLogService;
|
||||
|
||||
private AdminSecurityAuditController controller;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
controller = new AdminSecurityAuditController(securityAuditLogService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void listLogsDelegatesToServiceWithFilters() {
|
||||
PageResultVO<SecurityAuditLogVO> page = new PageResultVO<>();
|
||||
page.setTotal(0L);
|
||||
when(securityAuditLogService.pageLogs(eq("admin"), eq("ORDER_PROCESS"), eq("SUCCESS"),
|
||||
any(), any(), eq(1), eq(20))).thenReturn(page);
|
||||
|
||||
Result<PageResultVO<SecurityAuditLogVO>> result = controller.listLogs(
|
||||
"admin", "ORDER_PROCESS", "SUCCESS",
|
||||
"2026-05-01 00:00:00", "2026-05-23 23:59:59", 1, 20);
|
||||
|
||||
assertThat(result.getData()).isSameAs(page);
|
||||
verify(securityAuditLogService).pageLogs(eq("admin"), eq("ORDER_PROCESS"), eq("SUCCESS"),
|
||||
any(), any(), eq(1), eq(20));
|
||||
}
|
||||
}
|
||||
-258
@@ -1,258 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.security.service.impl;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.modules.security.entity.PermissionDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.security.entity.ShopRolePermissionDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.security.entity.UserPermissionDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.security.entity.UserShopRoleDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.security.mapper.PermissionMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.security.mapper.ShopRolePermissionMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.security.mapper.UserPermissionMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.security.mapper.UserShopRoleMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.support.RequestShopContext;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.support.UserShopBindingSupport;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.security.vo.PermissionVO;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class PermissionServiceImplTest {
|
||||
|
||||
@Mock
|
||||
private PermissionMapper permissionMapper;
|
||||
|
||||
@Mock
|
||||
private UserPermissionMapper userPermissionMapper;
|
||||
|
||||
@Mock
|
||||
private ShopRolePermissionMapper shopRolePermissionMapper;
|
||||
|
||||
@Mock
|
||||
private UserShopRoleMapper userShopRoleMapper;
|
||||
|
||||
@Mock
|
||||
private UserMapper userMapper;
|
||||
|
||||
@Mock
|
||||
private UserShopBindingSupport userShopBindingSupport;
|
||||
|
||||
private PermissionServiceImpl service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
service = new PermissionServiceImpl(
|
||||
permissionMapper,
|
||||
userPermissionMapper,
|
||||
shopRolePermissionMapper,
|
||||
userShopRoleMapper,
|
||||
userMapper,
|
||||
userShopBindingSupport
|
||||
);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
RequestContextHolder.resetRequestAttributes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void activeShopRoleRestrictsWritePermissionFromDefaultUserPermissions() {
|
||||
long userId = 10L;
|
||||
long productCreateId = 101L;
|
||||
long productViewId = 102L;
|
||||
long roleId = 201L;
|
||||
|
||||
UserDO user = new UserDO();
|
||||
user.setId(userId);
|
||||
user.setType(2);
|
||||
user.setIsDelete(0);
|
||||
when(userMapper.selectById(userId)).thenReturn(user);
|
||||
|
||||
UserPermissionDO defaultProductCreate = new UserPermissionDO();
|
||||
defaultProductCreate.setUserId(userId);
|
||||
defaultProductCreate.setPermissionId(productCreateId);
|
||||
when(userPermissionMapper.selectList(any())).thenReturn(List.of(defaultProductCreate));
|
||||
|
||||
PermissionDO productCreate = permission(productCreateId, "product:create");
|
||||
PermissionDO productView = permission(productViewId, "product:view");
|
||||
when(permissionMapper.selectOne(any()))
|
||||
.thenReturn(productCreate)
|
||||
.thenReturn(productView);
|
||||
|
||||
UserShopRoleDO roleBinding = new UserShopRoleDO();
|
||||
roleBinding.setUserId(userId);
|
||||
roleBinding.setRoleId(roleId);
|
||||
roleBinding.setStatus(1);
|
||||
roleBinding.setIsDelete(0);
|
||||
when(userShopRoleMapper.selectList(any())).thenReturn(List.of(roleBinding));
|
||||
|
||||
ShopRolePermissionDO rolePermission = new ShopRolePermissionDO();
|
||||
rolePermission.setRoleId(roleId);
|
||||
rolePermission.setPermissionId(productViewId);
|
||||
rolePermission.setIsDelete(0);
|
||||
when(shopRolePermissionMapper.selectList(any())).thenReturn(List.of(rolePermission));
|
||||
|
||||
assertThat(service.hasPermission(userId, "product:create")).isFalse();
|
||||
assertThat(service.hasPermission(userId, "product:view")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void listUserPermissionsUsesActiveShopRoleAsVisiblePermissions() {
|
||||
long userId = 10L;
|
||||
long productCreateId = 101L;
|
||||
long productViewId = 102L;
|
||||
long roleId = 201L;
|
||||
|
||||
UserDO user = new UserDO();
|
||||
user.setId(userId);
|
||||
user.setType(2);
|
||||
user.setIsDelete(0);
|
||||
when(userMapper.selectById(userId)).thenReturn(user);
|
||||
|
||||
UserPermissionDO defaultProductCreate = new UserPermissionDO();
|
||||
defaultProductCreate.setUserId(userId);
|
||||
defaultProductCreate.setPermissionId(productCreateId);
|
||||
when(userPermissionMapper.selectList(any())).thenReturn(List.of(defaultProductCreate));
|
||||
|
||||
UserShopRoleDO roleBinding = new UserShopRoleDO();
|
||||
roleBinding.setUserId(userId);
|
||||
roleBinding.setRoleId(roleId);
|
||||
roleBinding.setStatus(1);
|
||||
roleBinding.setIsDelete(0);
|
||||
when(userShopRoleMapper.selectList(any())).thenReturn(List.of(roleBinding));
|
||||
|
||||
ShopRolePermissionDO rolePermission = new ShopRolePermissionDO();
|
||||
rolePermission.setRoleId(roleId);
|
||||
rolePermission.setPermissionId(productViewId);
|
||||
rolePermission.setIsDelete(0);
|
||||
when(shopRolePermissionMapper.selectList(any())).thenReturn(List.of(rolePermission));
|
||||
|
||||
when(permissionMapper.selectList(any())).thenReturn(List.of(permission(productViewId, "product:view")));
|
||||
|
||||
List<PermissionVO> permissions = service.listUserPermissions(userId);
|
||||
|
||||
assertThat(permissions)
|
||||
.extracting(PermissionVO::getPermissionCode)
|
||||
.containsExactly("product:view");
|
||||
verify(shopRolePermissionMapper).selectList(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void staleDirectPermissionsCannotExceedUserTypeDefaultPermissions() {
|
||||
long userId = 30L;
|
||||
|
||||
UserDO user = new UserDO();
|
||||
user.setId(userId);
|
||||
user.setType(3);
|
||||
user.setIsDelete(0);
|
||||
when(userMapper.selectById(userId)).thenReturn(user);
|
||||
|
||||
assertThat(service.hasPermission(userId, "product:create")).isFalse();
|
||||
|
||||
verifyNoInteractions(userPermissionMapper);
|
||||
verifyNoInteractions(userShopRoleMapper);
|
||||
verifyNoInteractions(shopRolePermissionMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void activeShopRolesAreScopedToCurrentShop() {
|
||||
long userId = 10L;
|
||||
long currentShopId = 301L;
|
||||
long otherShopId = 302L;
|
||||
long currentShopRoleId = 401L;
|
||||
long otherShopRoleId = 402L;
|
||||
long productCreateId = 101L;
|
||||
long productViewId = 102L;
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setAttribute(RequestShopContext.CURRENT_SHOP_ID_ATTRIBUTE, currentShopId);
|
||||
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
|
||||
|
||||
UserDO user = new UserDO();
|
||||
user.setId(userId);
|
||||
user.setType(2);
|
||||
user.setIsDelete(0);
|
||||
when(userMapper.selectById(userId)).thenReturn(user);
|
||||
|
||||
UserShopRoleDO currentShopRole = roleBinding(userId, currentShopId, currentShopRoleId);
|
||||
UserShopRoleDO otherShopRole = roleBinding(userId, otherShopId, otherShopRoleId);
|
||||
when(userShopRoleMapper.selectList(any())).thenReturn(List.of(currentShopRole, otherShopRole));
|
||||
|
||||
ShopRolePermissionDO currentShopPermission = rolePermission(currentShopRoleId, productViewId);
|
||||
ShopRolePermissionDO otherShopPermission = rolePermission(otherShopRoleId, productCreateId);
|
||||
when(shopRolePermissionMapper.selectList(any())).thenReturn(List.of(currentShopPermission, otherShopPermission));
|
||||
|
||||
when(permissionMapper.selectOne(any()))
|
||||
.thenReturn(permission(productCreateId, "product:create"))
|
||||
.thenReturn(permission(productViewId, "product:view"));
|
||||
|
||||
assertThat(service.hasPermission(userId, "product:create")).isFalse();
|
||||
assertThat(service.hasPermission(userId, "product:view")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shoplessPlatformAdminCurrentPermissionsIncludeSecurityAuditView() {
|
||||
long userId = 1L;
|
||||
UserDO user = new UserDO();
|
||||
user.setId(userId);
|
||||
user.setType(4);
|
||||
user.setIsDelete(0);
|
||||
when(userMapper.selectById(userId)).thenReturn(user);
|
||||
when(permissionMapper.selectList(any())).thenReturn(List.of(
|
||||
permission(101L, "shop:view"),
|
||||
permission(102L, "security:audit:view")
|
||||
));
|
||||
|
||||
List<PermissionVO> permissions = service.listUserPermissions(userId);
|
||||
|
||||
assertThat(permissions)
|
||||
.extracting(PermissionVO::getPermissionCode)
|
||||
.contains("security:audit:view");
|
||||
verifyNoInteractions(userPermissionMapper);
|
||||
verifyNoInteractions(userShopRoleMapper);
|
||||
verifyNoInteractions(shopRolePermissionMapper);
|
||||
}
|
||||
|
||||
private UserShopRoleDO roleBinding(long userId, long shopId, long roleId) {
|
||||
UserShopRoleDO roleBinding = new UserShopRoleDO();
|
||||
roleBinding.setUserId(userId);
|
||||
roleBinding.setShopId(shopId);
|
||||
roleBinding.setRoleId(roleId);
|
||||
roleBinding.setStatus(1);
|
||||
roleBinding.setIsDelete(0);
|
||||
return roleBinding;
|
||||
}
|
||||
|
||||
private ShopRolePermissionDO rolePermission(long roleId, long permissionId) {
|
||||
ShopRolePermissionDO rolePermission = new ShopRolePermissionDO();
|
||||
rolePermission.setRoleId(roleId);
|
||||
rolePermission.setPermissionId(permissionId);
|
||||
rolePermission.setIsDelete(0);
|
||||
return rolePermission;
|
||||
}
|
||||
|
||||
private PermissionDO permission(long id, String code) {
|
||||
PermissionDO permission = new PermissionDO();
|
||||
permission.setId(id);
|
||||
permission.setPermissionCode(code);
|
||||
permission.setPermissionName(code);
|
||||
permission.setPermissionGroup("test");
|
||||
permission.setIsDelete(0);
|
||||
return permission;
|
||||
}
|
||||
}
|
||||
-81
@@ -1,81 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.security.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.security.entity.SecurityAuditLogDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.security.mapper.SecurityAuditLogMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.security.vo.SecurityAuditLogVO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.common.Result;
|
||||
class SecurityAuditLogServiceImplTest {
|
||||
|
||||
@Mock
|
||||
private SecurityAuditLogMapper auditLogMapper;
|
||||
|
||||
private SecurityAuditLogServiceImpl service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
service = new SecurityAuditLogServiceImpl(auditLogMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void recordTruncatesOversizedFieldsAndCapturesForwardedIp() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addHeader("X-Forwarded-For", "10.0.0.1, 10.0.0.2");
|
||||
|
||||
service.record(1L, "a".repeat(100), "b".repeat(100), "SUCCESS", "c".repeat(600), request);
|
||||
|
||||
ArgumentCaptor<SecurityAuditLogDO> captor = ArgumentCaptor.forClass(SecurityAuditLogDO.class);
|
||||
verify(auditLogMapper).insert(captor.capture());
|
||||
SecurityAuditLogDO log = captor.getValue();
|
||||
assertThat(log.getAccount()).hasSize(80);
|
||||
assertThat(log.getAction()).hasSize(80);
|
||||
assertThat(log.getReason()).hasSize(500);
|
||||
assertThat(log.getIpAddress()).isEqualTo("10.0.0.1");
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void pageLogsFiltersAndMapsPagedResult() {
|
||||
SecurityAuditLogDO log = new SecurityAuditLogDO();
|
||||
log.setId(100L);
|
||||
log.setUserId(1L);
|
||||
log.setAccount("admin");
|
||||
log.setAction("ORDER_PROCESS");
|
||||
log.setResult("SUCCESS");
|
||||
log.setReason("orderId=1");
|
||||
log.setIpAddress("127.0.0.1");
|
||||
log.setDeviceId("device-1");
|
||||
log.setOperateTime(LocalDateTime.now());
|
||||
Page<SecurityAuditLogDO> page = new Page<>(2, 5);
|
||||
page.setRecords(List.of(log));
|
||||
page.setTotal(11);
|
||||
when(auditLogMapper.selectPage(any(Page.class), any(LambdaQueryWrapper.class))).thenReturn(page);
|
||||
|
||||
PageResultVO<SecurityAuditLogVO> result = service.pageLogs("admin", "ORDER_PROCESS", "SUCCESS",
|
||||
LocalDateTime.now().minusDays(1), LocalDateTime.now(), 2, 5);
|
||||
|
||||
assertThat(result.getTotal()).isEqualTo(11);
|
||||
assertThat(result.getPage()).isEqualTo(2);
|
||||
assertThat(result.getSize()).isEqualTo(5);
|
||||
assertThat(result.getList()).hasSize(1);
|
||||
assertThat(result.getList().get(0).getAction()).isEqualTo("ORDER_PROCESS");
|
||||
}
|
||||
}
|
||||
-97
@@ -1,97 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.security.support;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class PermissionCatalogTest {
|
||||
|
||||
@Test
|
||||
void announcementPermissionsUseChineseDisplayText() {
|
||||
assertChinesePermission("announcement:view", "查看公告", "公告管理", "查看公告列表与详情");
|
||||
assertChinesePermission("announcement:create", "发布公告", "公告管理", "发布公告");
|
||||
assertChinesePermission("announcement:delete", "撤回公告", "公告管理", "撤回已发布公告");
|
||||
}
|
||||
|
||||
@Test
|
||||
void platformOnlyPermissionsAreAvailableToAdminAndOverviewMode() {
|
||||
assertThat(PermissionCatalog.getDefaultPermissionCodes(4))
|
||||
.contains("messagehub:config:manage", "security:audit:view", "legal_agreement:manage");
|
||||
assertThat(PermissionCatalog.isAllowedForPlatformOverview("user:create")).isTrue();
|
||||
assertThat(PermissionCatalog.isAllowedForPlatformOverview("user:balance:manage")).isTrue();
|
||||
assertThat(PermissionCatalog.isAllowedForPlatformOverview("shop:delete")).isTrue();
|
||||
assertThat(PermissionCatalog.isAllowedForPlatformOverview("permission:assign")).isTrue();
|
||||
assertThat(PermissionCatalog.isAllowedForPlatformOverview("message:create")).isTrue();
|
||||
assertThat(PermissionCatalog.isAllowedForPlatformOverview("announcement:create")).isTrue();
|
||||
assertThat(PermissionCatalog.isAllowedForPlatformOverview("messagehub:config:manage")).isTrue();
|
||||
assertThat(PermissionCatalog.isAllowedForPlatformOverview("security:audit:view")).isTrue();
|
||||
assertThat(PermissionCatalog.isAllowedForPlatformOverview("legal_agreement:manage")).isTrue();
|
||||
assertThat(PermissionCatalog.isAllowedForPlatformOverview("product:view")).isTrue();
|
||||
assertThat(PermissionCatalog.isAllowedForPlatformOverview("order:view")).isTrue();
|
||||
assertThat(PermissionCatalog.isAllowedForPlatformOverview("product:create")).isFalse();
|
||||
assertThat(PermissionCatalog.isAllowedForPlatformOverview("order:process")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyManagedDefaultPermissionHasDefinition() {
|
||||
Set<String> definedCodes = PermissionCatalog.getManagedPermissionCodes();
|
||||
assertThat(definedCodes)
|
||||
.containsAll(PermissionCatalog.getDefaultPermissionCodes(4))
|
||||
.containsAll(PermissionCatalog.getDefaultPermissionCodes(2))
|
||||
.containsAll(PermissionCatalog.getDefaultPermissionCodes(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nailArtistDefaultPermissionsAreWorkbenchOnly() {
|
||||
assertThat(PermissionCatalog.getDefaultPermissionCodes(3))
|
||||
.contains("product:view", "tag:view", "coupon:view", "order:view", "order:process", "order:artist-change")
|
||||
.doesNotContain("product:create", "product:edit", "product:delete",
|
||||
"tag:create", "tag:edit", "tag:delete",
|
||||
"user:create", "user:edit", "coupon:create", "coupon:assign");
|
||||
}
|
||||
|
||||
@Test
|
||||
void artistChangePermissionIsGrantedToProductionRoles() {
|
||||
assertChinesePermission("order:artist-change", "处理改派申请", "订单管理", "处理订单美甲师改派申请");
|
||||
|
||||
assertThat(PermissionCatalog.getDefaultPermissionCodes(2)).contains("order:artist-change");
|
||||
assertThat(PermissionCatalog.getDefaultPermissionCodes(3)).contains("order:artist-change");
|
||||
}
|
||||
|
||||
@Test
|
||||
void vNextOperationsPermissionsAreGrantedByRole() {
|
||||
assertThat(PermissionCatalog.getDefaultPermissionCodes(4))
|
||||
.contains("schedule:view", "schedule:edit", "payment:manage", "refund:manage",
|
||||
"after_sale:view", "after_sale:audit", "inventory:view", "inventory:manage",
|
||||
"campaign:view", "campaign:manage", "growth:view", "analytics:view", "performance:view");
|
||||
assertThat(PermissionCatalog.getDefaultPermissionCodes(2))
|
||||
.contains("schedule:view", "schedule:edit", "payment:view", "refund:view",
|
||||
"after_sale:view", "after_sale:audit", "inventory:view", "inventory:manage",
|
||||
"campaign:view", "campaign:manage", "analytics:view", "performance:view");
|
||||
assertThat(PermissionCatalog.getDefaultPermissionCodes(3))
|
||||
.contains("schedule:view", "after_sale:view", "performance:view")
|
||||
.doesNotContain("payment:manage", "refund:manage", "inventory:manage", "campaign:manage");
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyManagedDefaultPermissionUsesChineseDisplayText() {
|
||||
PermissionCatalog.getManagedDefinitions().forEach(definition -> {
|
||||
assertThat(definition.permissionName()).matches(PermissionCatalogTest::containsChinese);
|
||||
assertThat(definition.permissionGroup()).matches(PermissionCatalogTest::containsChinese);
|
||||
assertThat(definition.description()).matches(PermissionCatalogTest::containsChinese);
|
||||
});
|
||||
}
|
||||
|
||||
private void assertChinesePermission(String code, String name, String group, String description) {
|
||||
PermissionCatalog.PermissionDefinition definition = PermissionCatalog.getRequiredDefinition(code);
|
||||
assertThat(definition.permissionName()).isEqualTo(name);
|
||||
assertThat(definition.permissionGroup()).isEqualTo(group);
|
||||
assertThat(definition.description()).isEqualTo(description);
|
||||
}
|
||||
|
||||
private static boolean containsChinese(String value) {
|
||||
return value != null && value.chars().anyMatch(codePoint -> codePoint >= 0x4E00 && codePoint <= 0x9FFF);
|
||||
}
|
||||
}
|
||||
-209
@@ -1,209 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.shop.service.impl;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.config.AppCacheProperties;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.dto.ShopDTO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderArtistReviewDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.entity.ProductDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.entity.ShopDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.content.mapper.CommentMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.marketing.mapper.CouponMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderArtistReviewMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.mapper.ProductMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.ShopMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.mapper.TagMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.marketing.mapper.UserCouponMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.marketing.service.CouponService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.integration.service.MapService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.service.NailArtistInfoService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageFileService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.file.support.ObjectStorageUrlSupport;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.support.UserShopBindingSupport;
|
||||
import com.xiaowang.fingertipdesigner.core.support.cache.MultiLevelCacheService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.file.vo.ObjectStorageFileVO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.vo.ShopTrustProfileVO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
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.anyString;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class ShopServiceImplTest {
|
||||
@Mock
|
||||
private ShopMapper shopMapper;
|
||||
@Mock
|
||||
private CouponService couponService;
|
||||
@Mock
|
||||
private CouponMapper couponMapper;
|
||||
@Mock
|
||||
private ProductMapper productMapper;
|
||||
@Mock
|
||||
private TagMapper tagMapper;
|
||||
@Mock
|
||||
private CommentMapper commentMapper;
|
||||
@Mock
|
||||
private UserCouponMapper userCouponMapper;
|
||||
@Mock
|
||||
private OrderArtistReviewMapper orderArtistReviewMapper;
|
||||
@Mock
|
||||
private ObjectStorageFileService objectStorageFileService;
|
||||
@Mock
|
||||
private ObjectStorageUrlSupport objectStorageUrlSupport;
|
||||
@Mock
|
||||
private UserShopBindingSupport userShopBindingSupport;
|
||||
@Mock
|
||||
private NailArtistInfoService nailArtistInfoService;
|
||||
@Mock
|
||||
private MultiLevelCacheService multiLevelCacheService;
|
||||
@Mock
|
||||
private AppCacheProperties appCacheProperties;
|
||||
@Mock
|
||||
private MapService mapService;
|
||||
|
||||
private ShopServiceImpl service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
service = new ShopServiceImpl(
|
||||
shopMapper,
|
||||
couponService,
|
||||
couponMapper,
|
||||
productMapper,
|
||||
tagMapper,
|
||||
commentMapper,
|
||||
userCouponMapper,
|
||||
orderArtistReviewMapper,
|
||||
objectStorageFileService,
|
||||
objectStorageUrlSupport,
|
||||
userShopBindingSupport,
|
||||
nailArtistInfoService,
|
||||
multiLevelCacheService,
|
||||
appCacheProperties,
|
||||
mapService
|
||||
);
|
||||
when(objectStorageUrlSupport.toAccessibleUrl(anyString()))
|
||||
.thenAnswer(invocation -> invocation.getArgument(0, String.class));
|
||||
when(objectStorageUrlSupport.toAccessibleUrl(any(ObjectStorageFileVO.class)))
|
||||
.thenAnswer(invocation -> invocation.getArgument(0, ObjectStorageFileVO.class).getFileUrl());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteShopRejectsBusinessDeleteWithoutCascadeSoftDelete() {
|
||||
assertThatThrownBy(() -> service.deleteShop(1L))
|
||||
.isInstanceOf(RuntimeException.class)
|
||||
.hasMessage("店铺删除已停用,请使用停用封存");
|
||||
|
||||
verifyNoInteractions(
|
||||
shopMapper,
|
||||
couponMapper,
|
||||
productMapper,
|
||||
tagMapper,
|
||||
commentMapper,
|
||||
userCouponMapper,
|
||||
userShopBindingSupport
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateShopRejectsDisabledArchivedShop() {
|
||||
ShopDO disabledShop = new ShopDO();
|
||||
disabledShop.setId(1L);
|
||||
disabledShop.setStatus(0);
|
||||
disabledShop.setIsDelete(0);
|
||||
when(shopMapper.selectById(1L)).thenReturn(disabledShop);
|
||||
|
||||
assertThatThrownBy(() -> service.updateShop(1L, new ShopDTO()))
|
||||
.isInstanceOf(RuntimeException.class)
|
||||
.hasMessage("停用店铺已封存,仅允许重新启用");
|
||||
|
||||
verify(shopMapper, never()).updateById(disabledShop);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getShopTrustProfileAggregatesPublicTrustDataWithoutContactPhone() {
|
||||
ShopDO shop = new ShopDO();
|
||||
shop.setId(9L);
|
||||
shop.setShopName("Yumi Test Shop");
|
||||
shop.setStatus(1);
|
||||
shop.setIsDelete(0);
|
||||
shop.setBusinessHours("10:00-20:00");
|
||||
shop.setImageFileIds("101,102");
|
||||
shop.setCoverImageFileId("100");
|
||||
shop.setCreateTime(LocalDateTime.now().minusDays(10));
|
||||
when(shopMapper.selectById(9L)).thenReturn(shop);
|
||||
|
||||
ProductDO featured = new ProductDO();
|
||||
featured.setId(31L);
|
||||
featured.setShopId(9L);
|
||||
featured.setTitle("琉璃猫眼");
|
||||
featured.setDescription("透亮显白");
|
||||
featured.setPrice(new BigDecimal("168.00"));
|
||||
featured.setImageFileIds("201");
|
||||
featured.setLikeCount(5);
|
||||
featured.setCollectCount(12);
|
||||
featured.setBookableArtists("7,8");
|
||||
featured.setIsDelete(0);
|
||||
featured.setCreateTime(LocalDateTime.now().minusDays(1));
|
||||
when(productMapper.selectCount(any())).thenReturn(1L);
|
||||
when(productMapper.selectList(any())).thenReturn(List.of(featured));
|
||||
|
||||
OrderArtistReviewDO submitted = new OrderArtistReviewDO();
|
||||
submitted.setId(51L);
|
||||
submitted.setShopId(9L);
|
||||
submitted.setProductId(31L);
|
||||
submitted.setRatingScore(new BigDecimal("4.5"));
|
||||
submitted.setContent("环境干净,做得很细");
|
||||
submitted.setStatus(1);
|
||||
submitted.setIsDelete(0);
|
||||
submitted.setSubmittedAt(LocalDateTime.now().minusHours(3));
|
||||
OrderArtistReviewDO pending = new OrderArtistReviewDO();
|
||||
pending.setId(52L);
|
||||
pending.setShopId(9L);
|
||||
pending.setRatingScore(new BigDecimal("1.0"));
|
||||
pending.setContent("待评价不应展示");
|
||||
pending.setStatus(0);
|
||||
pending.setIsDelete(0);
|
||||
when(orderArtistReviewMapper.selectList(any())).thenReturn(List.of(submitted));
|
||||
when(orderArtistReviewMapper.selectCount(any())).thenReturn(1L);
|
||||
|
||||
ObjectStorageFileVO cover = new ObjectStorageFileVO();
|
||||
cover.setId(100L);
|
||||
cover.setFileUrl("https://img.test/cover.jpg");
|
||||
ObjectStorageFileVO env = new ObjectStorageFileVO();
|
||||
env.setId(101L);
|
||||
env.setFileUrl("https://img.test/env.jpg");
|
||||
ObjectStorageFileVO productImage = new ObjectStorageFileVO();
|
||||
productImage.setId(201L);
|
||||
productImage.setFileUrl("https://img.test/product.jpg");
|
||||
when(objectStorageFileService.getObjectStorageFileMapByIds(any()))
|
||||
.thenReturn(Map.of(100L, cover, 101L, env, 201L, productImage));
|
||||
|
||||
ShopTrustProfileVO profile = service.getShopTrustProfile(9L);
|
||||
|
||||
assertThat(profile).isNotNull();
|
||||
assertThat(profile.getShopId()).isEqualTo(9L);
|
||||
assertThat(profile.getStats().getProductCount()).isEqualTo(1L);
|
||||
assertThat(profile.getStats().getReviewCount()).isEqualTo(1L);
|
||||
assertThat(profile.getStats().getAverageRating()).isEqualByComparingTo("4.5");
|
||||
assertThat(profile.getEnvironmentImages()).contains("https://img.test/cover.jpg", "https://img.test/env.jpg");
|
||||
assertThat(profile.getFeaturedProducts()).hasSize(1);
|
||||
assertThat(profile.getFeaturedProducts().get(0).getImageUrl()).isEqualTo("https://img.test/product.jpg");
|
||||
assertThat(profile.getRecentReviews()).hasSize(1);
|
||||
assertThat(profile.getRecentReviews().get(0).getContent()).isEqualTo("环境干净,做得很细");
|
||||
assertThat(profile.getContactSummary().getPhoneExposed()).isFalse();
|
||||
assertThat(profile.getContactSummary().getPhone()).isNull();
|
||||
}
|
||||
}
|
||||
-30
@@ -1,30 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.shop.support;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
class ShopThemeSupportTest {
|
||||
|
||||
@Test
|
||||
void normalizeColorAcceptsOnlySixDigitHexAndUppercasesIt() {
|
||||
assertThat(ShopThemeSupport.normalizeColor("#c6597d", "themePrimaryColor")).isEqualTo("#C6597D");
|
||||
assertThat(ShopThemeSupport.normalizeColor(" #ffffff ", "themeCardBgColor")).isEqualTo("#FFFFFF");
|
||||
}
|
||||
|
||||
@Test
|
||||
void normalizeColorTreatsBlankAsUnset() {
|
||||
assertThat(ShopThemeSupport.normalizeColor(null, "themePrimaryColor")).isNull();
|
||||
assertThat(ShopThemeSupport.normalizeColor(" ", "themePrimaryColor")).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void normalizeColorRejectsUnsafeValues() {
|
||||
assertThatThrownBy(() -> ShopThemeSupport.normalizeColor("#fff", "themePrimaryColor"))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("themePrimaryColor");
|
||||
assertThatThrownBy(() -> ShopThemeSupport.normalizeColor("url(javascript:alert(1))", "themePrimaryColor"))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
}
|
||||
-44
@@ -1,44 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.system.service.impl;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.modules.system.dto.SystemParameterConfigDTO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.system.mapper.SystemParameterConfigMapper;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
|
||||
class SystemParameterConfigServiceImplTest {
|
||||
|
||||
@Mock
|
||||
private SystemParameterConfigMapper configMapper;
|
||||
|
||||
private SystemParameterConfigServiceImpl service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
service = new SystemParameterConfigServiceImpl(configMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void saveConfigRejectsWeakAdminDefaultPassword() {
|
||||
UserDO admin = new UserDO();
|
||||
admin.setType(4);
|
||||
|
||||
SystemParameterConfigDTO dto = new SystemParameterConfigDTO();
|
||||
dto.setConfigGroup("USER");
|
||||
dto.setConfigKey("DEFAULT_PASSWORD");
|
||||
dto.setConfigName("后台新增用户默认密码");
|
||||
dto.setConfigValue("12345678");
|
||||
dto.setEnabled(1);
|
||||
|
||||
assertThatThrownBy(() -> service.saveConfig(admin, dto))
|
||||
.isInstanceOf(RuntimeException.class)
|
||||
.hasMessageContaining("默认密码");
|
||||
verifyNoInteractions(configMapper);
|
||||
}
|
||||
}
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.system.support;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
class AdminDefaultPasswordSupportTest {
|
||||
|
||||
@Test
|
||||
void resolveCreatePasswordUsesConfiguredDefaultWhenPasswordBlank() {
|
||||
String password = AdminDefaultPasswordSupport.resolveCreatePassword(" ", " Config@123 ");
|
||||
|
||||
assertThat(password).isEqualTo("Config@123");
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolveCreatePasswordKeepsExplicitPassword() {
|
||||
String password = AdminDefaultPasswordSupport.resolveCreatePassword(" User@1234 ", "Config@123");
|
||||
|
||||
assertThat(password).isEqualTo("User@1234");
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolveDefaultPasswordFallsBackToStrongBuiltInDefault() {
|
||||
String password = AdminDefaultPasswordSupport.resolveDefaultPassword("");
|
||||
|
||||
assertThat(password).isEqualTo(AdminDefaultPasswordSupport.FALLBACK_DEFAULT_PASSWORD);
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateDefaultPasswordRejectsWeakConfig() {
|
||||
assertThatThrownBy(() -> AdminDefaultPasswordSupport.validateDefaultPassword("12345678"))
|
||||
.isInstanceOf(RuntimeException.class)
|
||||
.hasMessageContaining("默认密码");
|
||||
}
|
||||
}
|
||||
-200
@@ -1,200 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.user.service.impl;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.modules.security.mapper.PermissionMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.config.BrandProperties;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.ShopMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserInviteCodeMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.security.mapper.UserPermissionMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserRelationMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.security.mapper.UserShopRoleMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.integration.mapper.WechatMiniBindingMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.auth.dto.RegisterRequestDTO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.security.entity.PermissionDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.service.NailArtistInfoService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.service.ShopService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.system.service.SystemParameterConfigService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.auth.service.VerificationCodeService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.file.support.ObjectStorageUrlSupport;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.security.support.PermissionCatalog;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.support.UserShopBindingSupport;
|
||||
import com.xiaowang.fingertipdesigner.core.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import com.xiaowang.fingertipdesigner.core.support.security.UserSessionService;
|
||||
import com.xiaowang.fingertipdesigner.core.utils.JwtUtil;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.List;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class UserServiceImplPermissionAssignmentTest {
|
||||
|
||||
@Mock
|
||||
private UserMapper userMapper;
|
||||
|
||||
@Mock
|
||||
private ShopMapper shopMapper;
|
||||
|
||||
@Mock
|
||||
private JwtUtil jwtUtil;
|
||||
|
||||
@Mock
|
||||
private ShopService shopService;
|
||||
|
||||
@Mock
|
||||
private UserPermissionMapper userPermissionMapper;
|
||||
|
||||
@Mock
|
||||
private PermissionMapper permissionMapper;
|
||||
|
||||
@Mock
|
||||
private UserRelationMapper userRelationMapper;
|
||||
|
||||
@Mock
|
||||
private UserInviteCodeMapper userInviteCodeMapper;
|
||||
|
||||
@Mock
|
||||
private BrandProperties brandProperties;
|
||||
|
||||
@Mock
|
||||
private UserShopRoleMapper userShopRoleMapper;
|
||||
|
||||
@Mock
|
||||
private NailArtistInfoService nailArtistInfoService;
|
||||
|
||||
@Mock
|
||||
private VerificationCodeService verificationCodeService;
|
||||
|
||||
@Mock
|
||||
private UserShopBindingSupport userShopBindingSupport;
|
||||
|
||||
@Mock
|
||||
private ObjectStorageUrlSupport objectStorageUrlSupport;
|
||||
|
||||
@Mock
|
||||
private StringRedisTemplate redisTemplate;
|
||||
|
||||
@Mock
|
||||
private TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
|
||||
|
||||
@Mock
|
||||
private WechatMiniBindingMapper wechatMiniBindingMapper;
|
||||
|
||||
@Mock
|
||||
private UserSessionService userSessionService;
|
||||
|
||||
@Mock
|
||||
private SystemParameterConfigService systemParameterConfigService;
|
||||
|
||||
private AutoCloseable mocks;
|
||||
private UserServiceImpl service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
mocks = MockitoAnnotations.openMocks(this);
|
||||
service = new UserServiceImpl(
|
||||
userMapper,
|
||||
shopMapper,
|
||||
jwtUtil,
|
||||
shopService,
|
||||
userPermissionMapper,
|
||||
permissionMapper,
|
||||
userRelationMapper,
|
||||
userInviteCodeMapper,
|
||||
brandProperties,
|
||||
userShopRoleMapper,
|
||||
nailArtistInfoService,
|
||||
verificationCodeService,
|
||||
userShopBindingSupport,
|
||||
objectStorageUrlSupport,
|
||||
redisTemplate,
|
||||
snowflakeIdGenerator,
|
||||
wechatMiniBindingMapper,
|
||||
userSessionService,
|
||||
systemParameterConfigService
|
||||
);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
mocks.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void assignDefaultPermissionsSkipsPermissionSyncForPlainCustomer() throws Exception {
|
||||
Method method = UserServiceImpl.class.getDeclaredMethod("assignDefaultPermissions", Long.class, Integer.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
method.invoke(service, 1001L, 0);
|
||||
|
||||
verifyNoInteractions(permissionMapper, userPermissionMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void ensurePermissionDefinitionsSkipsUnchangedExistingDefinitions() throws Exception {
|
||||
when(permissionMapper.selectList(any())).thenReturn(existingManagedPermissionsFromCatalog());
|
||||
|
||||
Method method = UserServiceImpl.class.getDeclaredMethod("ensurePermissionDefinitions");
|
||||
method.setAccessible(true);
|
||||
|
||||
method.invoke(service);
|
||||
|
||||
verify(permissionMapper, never()).insert(any(PermissionDO.class));
|
||||
verify(permissionMapper, never()).updateById(any(PermissionDO.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void registerSkipsPermissionSyncForPlainCustomer() {
|
||||
RegisterRequestDTO request = new RegisterRequestDTO();
|
||||
request.setAccount("codexregister1");
|
||||
request.setPassword("Abc123456");
|
||||
request.setNickname("Codex");
|
||||
request.setPhone("13900000001");
|
||||
request.setVerificationCode("123456");
|
||||
request.setShopId(1L);
|
||||
|
||||
when(verificationCodeService.verifyCode("13900000001", "123456")).thenReturn(true);
|
||||
when(userShopBindingSupport.isShopActive(1L)).thenReturn(true);
|
||||
when(userMapper.selectOne(org.mockito.ArgumentMatchers.any()))
|
||||
.thenReturn(null)
|
||||
.thenReturn(null)
|
||||
.thenReturn(new UserDO());
|
||||
doAnswer(invocation -> {
|
||||
UserDO userDO = invocation.getArgument(0);
|
||||
userDO.setId(42L);
|
||||
return 1;
|
||||
}).when(userMapper).insert(org.mockito.ArgumentMatchers.any());
|
||||
|
||||
assertThat(service.register(request)).isTrue();
|
||||
verifyNoInteractions(permissionMapper, userPermissionMapper);
|
||||
}
|
||||
|
||||
private static List<PermissionDO> existingManagedPermissionsFromCatalog() {
|
||||
long id = 1L;
|
||||
List<PermissionDO> permissions = new java.util.ArrayList<>();
|
||||
for (PermissionCatalog.PermissionDefinition definition : PermissionCatalog.getManagedDefinitions()) {
|
||||
PermissionDO permission = new PermissionDO();
|
||||
permission.setId(id++);
|
||||
permission.setPermissionCode(definition.permissionCode());
|
||||
permission.setPermissionName(definition.permissionName());
|
||||
permission.setPermissionGroup(definition.permissionGroup());
|
||||
permission.setDescription(definition.description());
|
||||
permission.setIsDelete(0);
|
||||
permissions.add(permission);
|
||||
}
|
||||
return permissions;
|
||||
}
|
||||
}
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.user.support;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
class UserProfileFieldSupportTest {
|
||||
|
||||
@Test
|
||||
void requiresWechatIdForShopManagersAndNailArtists() {
|
||||
assertThatThrownBy(() -> UserProfileFieldSupport.requireWechatIdForServiceUser(2, " "))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("微信号");
|
||||
assertThatThrownBy(() -> UserProfileFieldSupport.requireWechatIdForServiceUser(3, null))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("微信号");
|
||||
}
|
||||
|
||||
@Test
|
||||
void allowsBlankWechatIdForNormalUsersAndAdmins() {
|
||||
UserProfileFieldSupport.requireWechatIdForServiceUser(0, " ");
|
||||
UserProfileFieldSupport.requireWechatIdForServiceUser(4, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void normalizesOptionalProfileText() {
|
||||
assertThat(UserProfileFieldSupport.normalizeOptionalText(null)).isNull();
|
||||
assertThat(UserProfileFieldSupport.normalizeOptionalText(" ")).isNull();
|
||||
assertThat(UserProfileFieldSupport.normalizeOptionalText(" fingertip-designer-nail ")).isEqualTo("fingertip-designer-nail");
|
||||
}
|
||||
}
|
||||
-127
@@ -1,127 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.support;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class FingertipDesignerSqlSchemaTest {
|
||||
|
||||
private static final Path INIT_SQL_PATH = Path.of("../scripts/sql/init/FingertipDesigner.sql");
|
||||
|
||||
@Test
|
||||
void balanceTableDefinesUpdateTimeColumnBeforeSeedMigrations() throws Exception {
|
||||
String sql = Files.readString(INIT_SQL_PATH);
|
||||
|
||||
assertThat(sql).containsPattern("(?is)create table t_balance\\s*\\([^;]*\\bupdate_time\\s+datetime");
|
||||
assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_balance', 'update_time'");
|
||||
}
|
||||
|
||||
@Test
|
||||
void orderArtistReviewAndChangeSchemasAreSeeded() throws Exception {
|
||||
String sql = Files.readString(INIT_SQL_PATH);
|
||||
|
||||
assertThat(sql).contains("CREATE TABLE IF NOT EXISTS t_order_artist_review");
|
||||
assertThat(sql).contains("CREATE TABLE IF NOT EXISTS t_order_artist_change_request");
|
||||
assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_system_message', 'business_type'");
|
||||
assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_system_message', 'business_id'");
|
||||
assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_system_message', 'action_path'");
|
||||
assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_system_message', 'idempotency_key'");
|
||||
assertThat(sql).contains("CALL sp_add_unique_index_if_not_exists('t_system_message', 'uk_t_system_message_idempotency'");
|
||||
assertThat(sql).contains("pending_key");
|
||||
assertThat(sql).contains("EXPIRED");
|
||||
assertThat(sql).contains("idx_order_artist_change_expire");
|
||||
assertThat(sql).contains("CALL sp_add_unique_index_if_not_exists('t_order_artist_change_request', 'uk_order_artist_change_pending_key'");
|
||||
assertThat(sql).contains("'order:artist-change'");
|
||||
}
|
||||
|
||||
@Test
|
||||
void businessEventOutboxAndSecurityAuditPermissionAreSeeded() throws Exception {
|
||||
String sql = Files.readString(INIT_SQL_PATH);
|
||||
|
||||
assertThat(sql).contains("CREATE TABLE IF NOT EXISTS t_business_event_outbox");
|
||||
assertThat(sql).contains("uk_business_event_outbox_event_key");
|
||||
assertThat(sql).contains("idx_business_event_outbox_due");
|
||||
assertThat(sql).contains("'security:audit:view'");
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagSceneFilterColumnsAreSeeded() throws Exception {
|
||||
String sql = Files.readString(INIT_SQL_PATH);
|
||||
|
||||
assertThat(sql).contains("scene_group");
|
||||
assertThat(sql).contains("display_name");
|
||||
assertThat(sql).contains("front_visible");
|
||||
assertThat(sql).contains("idx_t_tag_front_filter");
|
||||
assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_tag', 'scene_group'");
|
||||
assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_tag', 'front_visible'");
|
||||
}
|
||||
|
||||
@Test
|
||||
void vNextOperationsSchemasAndPermissionsAreSeeded() throws Exception {
|
||||
String sql = Files.readString(INIT_SQL_PATH);
|
||||
|
||||
assertThat(sql).contains("CREATE TABLE IF NOT EXISTS t_artist_schedule");
|
||||
assertThat(sql).contains("CREATE TABLE IF NOT EXISTS t_appointment_reservation");
|
||||
assertThat(sql).contains("CREATE TABLE IF NOT EXISTS t_payment_order");
|
||||
assertThat(sql).contains("CREATE TABLE IF NOT EXISTS t_refund_order");
|
||||
assertThat(sql).contains("CREATE TABLE IF NOT EXISTS t_after_sale");
|
||||
assertThat(sql).contains("CREATE TABLE IF NOT EXISTS t_after_sale_log");
|
||||
assertThat(sql).contains("CREATE TABLE IF NOT EXISTS t_inventory_item");
|
||||
assertThat(sql).contains("CREATE TABLE IF NOT EXISTS t_inventory_record");
|
||||
assertThat(sql).contains("CREATE TABLE IF NOT EXISTS t_campaign");
|
||||
assertThat(sql).contains("CREATE TABLE IF NOT EXISTS t_user_growth_record");
|
||||
assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_order', 'payment_status'");
|
||||
assertThat(sql).contains("'schedule:view'");
|
||||
assertThat(sql).contains("'payment:manage'");
|
||||
assertThat(sql).contains("'after_sale:audit'");
|
||||
assertThat(sql).contains("'inventory:manage'");
|
||||
assertThat(sql).contains("'campaign:manage'");
|
||||
assertThat(sql).contains("'growth:view'");
|
||||
assertThat(sql).contains("'analytics:view'");
|
||||
assertThat(sql).contains("'performance:view'");
|
||||
assertThat(sql).contains("'workbench:view'");
|
||||
}
|
||||
|
||||
@Test
|
||||
void adminDefaultPasswordConfigIsSeeded() throws Exception {
|
||||
String sql = Files.readString(INIT_SQL_PATH);
|
||||
|
||||
assertThat(sql).contains("'USER', 'DEFAULT_PASSWORD'");
|
||||
assertThat(sql).contains("后台新增用户默认密码");
|
||||
}
|
||||
@Test
|
||||
void userProfileContactColumnsAreSeeded() throws Exception {
|
||||
String sql = Files.readString(INIT_SQL_PATH);
|
||||
|
||||
assertThat(sql).contains("contact_phone varchar(50)");
|
||||
assertThat(sql).contains("birthday date");
|
||||
assertThat(sql).contains("wechat_id varchar(100)");
|
||||
assertThat(sql).contains("wechat_qr_code varchar(512)");
|
||||
assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_user', 'contact_phone'");
|
||||
assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_user', 'wechat_qr_code'");
|
||||
}
|
||||
|
||||
@Test
|
||||
void objectStorageFileBackupColumnsAreSeeded() throws Exception {
|
||||
String sql = Files.readString(INIT_SQL_PATH);
|
||||
|
||||
assertThat(sql).contains("object_name");
|
||||
assertThat(sql).contains("primary_provider");
|
||||
assertThat(sql).contains("primary_url");
|
||||
assertThat(sql).contains("backup_provider");
|
||||
assertThat(sql).contains("backup_url");
|
||||
assertThat(sql).contains("content_type");
|
||||
assertThat(sql).contains("file_size");
|
||||
assertThat(sql).contains("primary_upload_status");
|
||||
assertThat(sql).contains("backup_upload_status");
|
||||
assertThat(sql).contains("backup_retry_count");
|
||||
assertThat(sql).contains("backup_last_error");
|
||||
assertThat(sql).contains("backup_uploaded_at");
|
||||
assertThat(sql).contains("backup_last_retry_time");
|
||||
assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_object_storage_file', 'object_name'");
|
||||
assertThat(sql).contains("CALL sp_add_index_if_not_exists('t_object_storage_file', 'idx_object_storage_file_backup_retry'");
|
||||
}
|
||||
}
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.support;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class WishlistSqlSchemaTest {
|
||||
|
||||
@Test
|
||||
void wishlistGroupsAndMetadataAreSeededInInitSql() throws Exception {
|
||||
String sql = Files.readString(Path.of("../scripts/sql/init/FingertipDesigner.sql"));
|
||||
|
||||
assertWishlistSchema(sql);
|
||||
}
|
||||
|
||||
private void assertWishlistSchema(String sql) {
|
||||
assertThat(sql).contains("t_wishlist_group");
|
||||
assertThat(sql).contains("group_id");
|
||||
assertThat(sql).contains("note");
|
||||
assertThat(sql).contains("sort_order");
|
||||
assertThat(sql).contains("最近想做");
|
||||
assertThat(sql).contains("婚礼款");
|
||||
assertThat(sql).contains("夏天款");
|
||||
assertThat(sql).contains("idx_t_wishlist_group_user");
|
||||
assertThat(sql).contains("idx_t_wishlist_group_sort");
|
||||
assertThat(sql).contains("idx_t_wishlist_group_sort");
|
||||
assertThat(sql).contains("idx_t_wishlist_user_group_sort");
|
||||
assertThat(sql).contains("sp_drop_auto_increment_on_id_if_exists('t_wishlist_group')");
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.utils;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.config.JwtProperties;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class JwtUtilTest {
|
||||
|
||||
@Test
|
||||
void resolveAccessTokenExpirationSecondsShouldUseRememberMeSeconds() {
|
||||
JwtProperties properties = new JwtProperties();
|
||||
properties.setAccessTokenExpirationSeconds(120L);
|
||||
properties.setRememberMeAccessTokenExpirationSeconds(604800L);
|
||||
JwtUtil jwtUtil = new JwtUtil(properties);
|
||||
|
||||
assertThat(jwtUtil.resolveAccessTokenExpirationSeconds(false)).isEqualTo(120L);
|
||||
assertThat(jwtUtil.resolveAccessTokenExpirationSeconds(true)).isEqualTo(604800L);
|
||||
}
|
||||
}
|
||||
@@ -1,371 +0,0 @@
|
||||
import { createRouter, createWebHistory } from 'vue-router'
|
||||
import {
|
||||
canAccessAdminRoute,
|
||||
clearAdminBootstrapSession,
|
||||
ensureAdminAuthBootstrap,
|
||||
getAdminBootstrapSnapshot,
|
||||
resolveAdminLandingPath,
|
||||
} from '@/utils/admin-auth-bootstrap'
|
||||
|
||||
/**
|
||||
* Purpose: router supports index.ts by holding or executing the router page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const router = createRouter({
|
||||
history: createWebHistory(import.meta.env.BASE_URL),
|
||||
routes: [
|
||||
{
|
||||
path: '/',
|
||||
name: 'auth',
|
||||
component: () => import('../views/AuthView.vue'),
|
||||
meta: { requiresAuth: false, hideNav: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/home',
|
||||
name: 'home',
|
||||
component: () => import('../views/HomeView.vue'),
|
||||
meta: { requiresAuth: false, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/products',
|
||||
name: 'products',
|
||||
component: () => import('../views/ProductListView.vue'),
|
||||
meta: { requiresAuth: false, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/product/:id',
|
||||
name: 'product-detail',
|
||||
component: () => import('../views/ProductDetailView.vue'),
|
||||
meta: { requiresAuth: false, hideNav: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/cart',
|
||||
name: 'cart',
|
||||
component: () => import('../views/CartView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/profile',
|
||||
name: 'profile',
|
||||
component: () => import('../views/ProfileView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/shop/:id',
|
||||
name: 'shop-detail',
|
||||
component: () => import('../views/ShopDetailView.vue'),
|
||||
meta: { requiresAuth: false, hideNav: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/shop/:shopId/artists',
|
||||
name: 'shop-artists',
|
||||
component: () => import('../views/ArtistListView.vue'),
|
||||
meta: { requiresAuth: false, hideNav: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/artist/:id',
|
||||
name: 'artist-profile',
|
||||
component: () => import('../views/ArtistProfileView.vue'),
|
||||
meta: { requiresAuth: false, hideNav: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/wishlist',
|
||||
name: 'wishlist',
|
||||
component: () => import('../views/WishlistView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/orders',
|
||||
name: 'orders',
|
||||
component: () => import('../views/OrderView.vue'),
|
||||
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/orders/:id',
|
||||
name: 'order-detail',
|
||||
component: () => import('../views/OrderDetailView.vue'),
|
||||
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/after-sales',
|
||||
name: 'after-sales',
|
||||
component: () => import('../views/AfterSalesView.vue'),
|
||||
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/after-sale/apply',
|
||||
name: 'after-sale-apply',
|
||||
component: () => import('../views/AfterSaleApplyView.vue'),
|
||||
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/service-progress',
|
||||
name: 'service-progress',
|
||||
component: () => import('../views/ServiceProgressView.vue'),
|
||||
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/help',
|
||||
name: 'help',
|
||||
component: () => import('../views/HelpView.vue'),
|
||||
meta: { requiresAuth: false, hideNav: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/artist-orders',
|
||||
name: 'artist-orders',
|
||||
component: () => import('../views/ArtistOrderView.vue'),
|
||||
meta: { requiresAuth: true, hideNav: true, isAdmin: false, permissionCode: 'order:view' }
|
||||
},
|
||||
{
|
||||
path: '/artist-calendar',
|
||||
name: 'artist-calendar',
|
||||
component: () => import('../views/ArtistCalendarView.vue'),
|
||||
meta: { requiresAuth: true, hideNav: true, isAdmin: false, permissionCode: 'order:view' }
|
||||
},
|
||||
{
|
||||
path: '/settings',
|
||||
name: 'settings',
|
||||
component: () => import('../views/SettingsView.vue'),
|
||||
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/settings/account',
|
||||
name: 'account-settings',
|
||||
component: () => import('../views/AccountSettingsView.vue'),
|
||||
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/settings/password',
|
||||
name: 'password-settings',
|
||||
component: () => import('../views/PasswordSettingsView.vue'),
|
||||
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/coupons',
|
||||
name: 'coupons',
|
||||
component: () => import('../views/CouponView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: false, hideNav: true }
|
||||
},
|
||||
{
|
||||
path: '/vip-center',
|
||||
name: 'vip-center',
|
||||
component: () => import('../views/VipCenterView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: false, hideNav: true }
|
||||
},
|
||||
{
|
||||
path: '/notifications',
|
||||
name: 'notifications',
|
||||
component: () => import('../views/NotificationsView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: false, hideNav: true }
|
||||
},
|
||||
{
|
||||
path: '/admin/login',
|
||||
name: 'admin-login',
|
||||
component: () => import('../views/admin/AdminLoginView.vue'),
|
||||
meta: { requiresAuth: false, isAdmin: true, hideNav: true }
|
||||
},
|
||||
{
|
||||
path: '/admin',
|
||||
component: () => import('../views/admin/AdminLayout.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true },
|
||||
children: [
|
||||
{
|
||||
path: '',
|
||||
name: 'admin',
|
||||
component: () => import('../views/admin/HomeView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true }
|
||||
},
|
||||
{
|
||||
path: 'dashboard',
|
||||
name: 'admin-dashboard',
|
||||
component: () => import('../views/admin/DashboardView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'dashboard:view' }
|
||||
},
|
||||
{
|
||||
path: 'users',
|
||||
name: 'admin-users',
|
||||
component: () => import('../views/admin/UsersView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'user:view' }
|
||||
},
|
||||
{
|
||||
path: 'products',
|
||||
name: 'admin-products',
|
||||
component: () => import('../views/admin/ProductsView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'product:view' }
|
||||
},
|
||||
{
|
||||
path: 'coupons',
|
||||
name: 'admin-coupons',
|
||||
component: () => import('../views/admin/CouponsView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'coupon:view' }
|
||||
},
|
||||
{
|
||||
path: 'comments',
|
||||
name: 'admin-comments',
|
||||
component: () => import('../views/admin/CommentsView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'comment:view' }
|
||||
},
|
||||
{
|
||||
path: 'shops',
|
||||
name: 'admin-shops',
|
||||
component: () => import('../views/admin/ShopsView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'shop:view' }
|
||||
},
|
||||
{
|
||||
path: 'permissions',
|
||||
name: 'admin-permissions',
|
||||
component: () => import('../views/admin/PermissionsView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'permission:view' }
|
||||
},
|
||||
{
|
||||
path: 'orders',
|
||||
name: 'admin-orders',
|
||||
component: () => import('../views/admin/OrdersView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'order:view' }
|
||||
},
|
||||
{
|
||||
path: 'schedules',
|
||||
name: 'admin-schedules',
|
||||
component: () => import('../views/admin/SchedulesView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'schedule:view' }
|
||||
},
|
||||
{
|
||||
path: 'after-sales',
|
||||
name: 'admin-after-sales',
|
||||
component: () => import('../views/admin/AfterSalesView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'after_sale:view' }
|
||||
},
|
||||
{
|
||||
path: 'inventory',
|
||||
name: 'admin-inventory',
|
||||
component: () => import('../views/admin/InventoryView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'inventory:view' }
|
||||
},
|
||||
{
|
||||
path: 'campaigns',
|
||||
name: 'admin-campaigns',
|
||||
component: () => import('../views/admin/CampaignsView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'campaign:view' }
|
||||
},
|
||||
{
|
||||
path: 'manage',
|
||||
name: 'admin-manage',
|
||||
component: () => import('../views/admin/ManageView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true }
|
||||
},
|
||||
{
|
||||
path: 'profile',
|
||||
name: 'admin-profile',
|
||||
component: () => import('../views/admin/ProfileView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true }
|
||||
},
|
||||
{
|
||||
path: 'tags',
|
||||
name: 'admin-tags',
|
||||
component: () => import('../views/admin/TagsView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'tag:view' }
|
||||
},
|
||||
{
|
||||
path: 'nail-artists',
|
||||
name: 'admin-nail-artists',
|
||||
component: () => import('../views/admin/NailArtistsView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'nail_artist:view' }
|
||||
},
|
||||
{
|
||||
path: 'messages',
|
||||
name: 'admin-messages',
|
||||
component: () => import('../views/admin/SystemMessagesView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'message:view' }
|
||||
},
|
||||
{
|
||||
path: 'announcements',
|
||||
name: 'admin-announcements',
|
||||
component: () => import('../views/admin/AnnouncementsView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'announcement:view' }
|
||||
},
|
||||
{
|
||||
path: 'vip-recharge-plans',
|
||||
name: 'admin-vip-recharge-plans',
|
||||
component: () => import('../views/admin/VipRechargePlansView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'user:vip:manage' }
|
||||
},
|
||||
{
|
||||
path: 'messagehub-push-configs',
|
||||
name: 'admin-messagehub-push-configs',
|
||||
component: () => import('../views/admin/MessageHubPushConfigsView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'messagehub:config:manage' }
|
||||
},
|
||||
{
|
||||
path: 'legal-agreements',
|
||||
name: 'admin-legal-agreements',
|
||||
component: () => import('../views/admin/LegalAgreementsView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'legal_agreement:manage' }
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
path: '/:pathMatch(.*)*',
|
||||
name: 'not-found',
|
||||
component: () => import('../views/NotFoundView.vue'),
|
||||
meta: { requiresAuth: false, hideNav: true, isAdmin: false }
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
router.beforeEach(async (to) => {
|
||||
const isAdminRoute = Boolean(to.meta.isAdmin)
|
||||
const requiresAuth = Boolean(to.meta.requiresAuth)
|
||||
|
||||
if (isAdminRoute) {
|
||||
const snapshot = getAdminBootstrapSnapshot()
|
||||
|
||||
if (to.path === '/admin/login') {
|
||||
if (!snapshot.token || !snapshot.userInfo) {
|
||||
return true
|
||||
}
|
||||
|
||||
const state = await ensureAdminAuthBootstrap()
|
||||
return state === 'ready' ? resolveAdminLandingPath() : true
|
||||
}
|
||||
|
||||
if (requiresAuth && (!snapshot.token || !snapshot.userInfo)) {
|
||||
clearAdminBootstrapSession()
|
||||
return '/admin/login'
|
||||
}
|
||||
|
||||
const bootstrapState = await ensureAdminAuthBootstrap()
|
||||
if (bootstrapState !== 'ready') {
|
||||
return '/admin/login'
|
||||
}
|
||||
|
||||
if (!canAccessAdminRoute(to.path, to.meta.permissionCode as string | undefined)) {
|
||||
return resolveAdminLandingPath()
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
const token = localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')
|
||||
|
||||
if (requiresAuth && !token) {
|
||||
return '/'
|
||||
}
|
||||
|
||||
if (to.path === '/' && token) {
|
||||
return '/home'
|
||||
}
|
||||
|
||||
if (requiresAuth && token) {
|
||||
const userInfo = localStorage.getItem('userInfo')
|
||||
if (!userInfo) {
|
||||
localStorage.removeItem('accessToken')
|
||||
localStorage.removeItem('refreshToken')
|
||||
sessionStorage.removeItem('accessToken')
|
||||
return '/'
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
})
|
||||
|
||||
export default router
|
||||
@@ -1,514 +0,0 @@
|
||||
<template>
|
||||
<div class="admin-login">
|
||||
<div class="login-container">
|
||||
<div class="login-header">
|
||||
<h1>后台管理系统</h1>
|
||||
<p>欢迎回来,请登录您的账户</p>
|
||||
</div>
|
||||
|
||||
<a-card class="login-card">
|
||||
<a-form
|
||||
ref="formRef"
|
||||
:model="formState"
|
||||
:rules="formRules"
|
||||
layout="vertical"
|
||||
@finish="handleLogin"
|
||||
>
|
||||
<a-alert
|
||||
v-if="loginShopMessage"
|
||||
:type="allowShoplessLogin || hasAvailableShops ? 'info' : 'warning'"
|
||||
show-icon
|
||||
:message="loginShopMessage"
|
||||
style="margin-bottom: 16px"
|
||||
/>
|
||||
|
||||
<a-form-item label="用户名" name="account">
|
||||
<a-input
|
||||
v-model:value="formState.account"
|
||||
size="large"
|
||||
placeholder="请输入用户名"
|
||||
:prefix-icon="UserOutlined"
|
||||
@input="handleAccountInput"
|
||||
/>
|
||||
</a-form-item>
|
||||
|
||||
<a-form-item label="密码" name="password">
|
||||
<a-input-password
|
||||
v-model:value="formState.password"
|
||||
size="large"
|
||||
placeholder="请输入密码"
|
||||
:prefix-icon="LockOutlined"
|
||||
@pressEnter="handleLogin"
|
||||
/>
|
||||
</a-form-item>
|
||||
|
||||
<a-form-item v-if="hasAvailableShops || !allowShoplessLogin" label="登录店铺" name="shopId">
|
||||
<a-select
|
||||
v-model:value="formState.shopId"
|
||||
size="large"
|
||||
:placeholder="shopPlaceholder"
|
||||
:loading="shopLoading"
|
||||
:options="shopOptions"
|
||||
:disabled="shopLoading || (!hasAvailableShops && !allowShoplessLogin)"
|
||||
show-search
|
||||
:filter-option="filterShopOption"
|
||||
/>
|
||||
</a-form-item>
|
||||
|
||||
<a-form-item>
|
||||
<a-button
|
||||
type="primary"
|
||||
size="large"
|
||||
html-type="submit"
|
||||
:loading="loading"
|
||||
block
|
||||
>
|
||||
登录
|
||||
</a-button>
|
||||
</a-form-item>
|
||||
</a-form>
|
||||
|
||||
<div class="login-footer">
|
||||
<a @click="goToFrontend">返回前台</a>
|
||||
</div>
|
||||
</a-card>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* AdminLoginView page script.
|
||||
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
|
||||
*/
|
||||
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { message } from 'ant-design-vue'
|
||||
import type { FormInstance } from 'ant-design-vue'
|
||||
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue'
|
||||
/**
|
||||
* Purpose: LoginShopSelectionResponse supports AdminLoginView.vue by holding or executing the login shop selection response page or API role.
|
||||
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
import { adminAuthApi, type LoginShopSelectionResponse } from '@/api/admin'
|
||||
import { ACCOUNT_REGEX, ACCOUNT_RULE_MESSAGE, sanitizeAccountInput } from '@/utils/account'
|
||||
import type { IdType } from '@/utils/id'
|
||||
import { usePermission } from '@/utils/permission'
|
||||
import { runWithGlobalLoading } from '@/utils/action-loading'
|
||||
import { resolveAdminLandingPath } from '@/utils/admin-auth-bootstrap'
|
||||
|
||||
/**
|
||||
* Purpose: router supports AdminLoginView.vue by holding or executing the router page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const router = useRouter()
|
||||
/**
|
||||
* Purpose: formRef supports AdminLoginView.vue by holding or executing the form ref page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const formRef = ref<FormInstance>()
|
||||
/** loading is a reactive state variable used by the template and event handlers. */
|
||||
const loading = ref(false)
|
||||
/** shopLoading is a reactive state variable used by the template and event handlers. */
|
||||
const shopLoading = ref(false)
|
||||
/**
|
||||
* Purpose: shops supports AdminLoginView.vue by holding or executing the shops page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const shops = ref<Array<{ id: IdType; shopName: string }>>([])
|
||||
/** allowShoplessLogin is a reactive state variable used by the template and event handlers. */
|
||||
const allowShoplessLogin = ref(false)
|
||||
/** loginShopMessage is a reactive state variable used by the template and event handlers. */
|
||||
const loginShopMessage = ref('')
|
||||
const { loadUserPermissions } = usePermission()
|
||||
|
||||
/**
|
||||
* Purpose: formState supports AdminLoginView.vue by holding or executing the form state page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const formState = reactive({
|
||||
account: '',
|
||||
password: '',
|
||||
shopId: undefined as string | undefined
|
||||
})
|
||||
let loginShopTimer: number | undefined
|
||||
|
||||
/** handleAccountInput is a local helper used by this page script. */
|
||||
const handleAccountInput = () => {
|
||||
const normalized = sanitizeAccountInput(formState.account)
|
||||
if (normalized !== formState.account) {
|
||||
formState.account = normalized
|
||||
}
|
||||
}
|
||||
|
||||
/** getShopIdValue is a local helper used by this page script. */
|
||||
const getShopIdValue = (shop: { id: IdType; shopName: string }) => String(shop.id ?? '')
|
||||
/** getShopLabel is a local helper used by this page script. */
|
||||
const getShopLabel = (shop: { id: IdType; shopName: string }) => String(shop.shopName || `店铺 ${shop.id}`)
|
||||
|
||||
/** shopOptions is a reactive state variable used by the template and event handlers. */
|
||||
const shopOptions = computed(() =>
|
||||
shops.value.map(shop => ({
|
||||
label: getShopLabel(shop),
|
||||
value: getShopIdValue(shop)
|
||||
}))
|
||||
)
|
||||
/** hasAvailableShops is a reactive state variable used by the template and event handlers. */
|
||||
const hasAvailableShops = computed(() => shopOptions.value.length > 0)
|
||||
/** shouldRequireShop is a reactive state variable used by the template and event handlers. */
|
||||
const shouldRequireShop = computed(() => hasAvailableShops.value && !allowShoplessLogin.value)
|
||||
/** shopPlaceholder is a reactive state variable used by the template and event handlers. */
|
||||
const shopPlaceholder = computed(() => {
|
||||
if (shopLoading.value) {
|
||||
return '正在加载可登录店铺'
|
||||
}
|
||||
if (hasAvailableShops.value) {
|
||||
return allowShoplessLogin.value ? '可选择本次登录店铺,留空进入平台总览' : '请选择登录店铺'
|
||||
}
|
||||
if (allowShoplessLogin.value) {
|
||||
return '当前无需选择店铺'
|
||||
}
|
||||
return '请先输入账号'
|
||||
})
|
||||
|
||||
/**
|
||||
* Purpose: formRules supports AdminLoginView.vue by holding or executing the form rules page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const formRules = {
|
||||
account: [
|
||||
{ required: true, message: '请输入用户名', trigger: 'blur' },
|
||||
{ pattern: ACCOUNT_REGEX, message: ACCOUNT_RULE_MESSAGE, trigger: 'blur' }
|
||||
],
|
||||
password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
|
||||
shopId: [{
|
||||
validator: async () => {
|
||||
if (!shouldRequireShop.value || formState.shopId) {
|
||||
return Promise.resolve()
|
||||
}
|
||||
return Promise.reject(new Error('请选择登录店铺'))
|
||||
},
|
||||
trigger: 'change'
|
||||
}]
|
||||
} as any
|
||||
|
||||
/** filterShopOption is a local helper used by this page script. */
|
||||
const filterShopOption = (input: string, option: { label?: string | number } | undefined) =>
|
||||
String(option?.label ?? '').toLowerCase().includes(input.toLowerCase())
|
||||
|
||||
/** isLoginShopPrefetchUnsupported is a local helper used by this page script. */
|
||||
const isLoginShopPrefetchUnsupported = (error: unknown) => {
|
||||
const status = (error as any)?.response?.status
|
||||
return status === 404
|
||||
}
|
||||
|
||||
/** resetLoginShopTimer is a local helper used by this page script. */
|
||||
const resetLoginShopTimer = () => {
|
||||
if (loginShopTimer !== undefined) {
|
||||
window.clearTimeout(loginShopTimer)
|
||||
loginShopTimer = undefined
|
||||
}
|
||||
}
|
||||
|
||||
/** restoreLoginShop is a local helper used by this page script. */
|
||||
const restoreLoginShop = () => {
|
||||
const cached = localStorage.getItem('adminUserInfo')
|
||||
if (!cached) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(cached)
|
||||
if (parsed?.type === 4) {
|
||||
return
|
||||
}
|
||||
if (parsed?.shopId) {
|
||||
formState.shopId = String(parsed.shopId)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('恢复后台登录店铺失败:', error)
|
||||
}
|
||||
}
|
||||
|
||||
/** applyLoginShopSelection is a local helper used by this page script. */
|
||||
const applyLoginShopSelection = (selection?: LoginShopSelectionResponse | null) => {
|
||||
shops.value = selection?.shops || []
|
||||
allowShoplessLogin.value = Boolean(selection?.allowShoplessLogin)
|
||||
loginShopMessage.value = selection?.message || ''
|
||||
|
||||
if (!shops.value.length) {
|
||||
formState.shopId = undefined
|
||||
return
|
||||
}
|
||||
|
||||
const matchedShop = shops.value.find(shop => getShopIdValue(shop) === formState.shopId)
|
||||
if (matchedShop) {
|
||||
return
|
||||
}
|
||||
|
||||
if (!allowShoplessLogin.value && shops.value.length === 1) {
|
||||
formState.shopId = getShopIdValue(shops.value[0]!)
|
||||
return
|
||||
}
|
||||
|
||||
formState.shopId = undefined
|
||||
}
|
||||
|
||||
/** loadLoginShops is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
||||
const loadLoginShops = async (account = formState.account) => {
|
||||
const trimmedAccount = account.trim()
|
||||
if (!trimmedAccount) {
|
||||
applyLoginShopSelection(null)
|
||||
return
|
||||
}
|
||||
|
||||
shopLoading.value = true
|
||||
try {
|
||||
const selection = await adminAuthApi.getLoginShops(trimmedAccount) as unknown as LoginShopSelectionResponse
|
||||
if (formState.account.trim() === trimmedAccount) {
|
||||
applyLoginShopSelection(selection)
|
||||
}
|
||||
} catch (error) {
|
||||
if (formState.account.trim() === trimmedAccount) {
|
||||
if (isLoginShopPrefetchUnsupported(error)) {
|
||||
applyLoginShopSelection({
|
||||
allowShoplessLogin: true,
|
||||
message: '可直接登录;如账号绑定多家门店,登录后可在个人中心切换当前门店。',
|
||||
shops: []
|
||||
})
|
||||
} else {
|
||||
applyLoginShopSelection(null)
|
||||
loginShopMessage.value = '登录店铺加载失败,请稍后重试'
|
||||
}
|
||||
}
|
||||
if (!isLoginShopPrefetchUnsupported(error)) {
|
||||
console.error('获取登录店铺列表失败:', error)
|
||||
}
|
||||
} finally {
|
||||
shopLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** handleLogin is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
||||
const handleLogin = async () => {
|
||||
try {
|
||||
await formRef.value?.validate()
|
||||
loading.value = true
|
||||
|
||||
const res = await runWithGlobalLoading(() => adminAuthApi.login({
|
||||
account: formState.account,
|
||||
password: formState.password,
|
||||
shopId: formState.shopId
|
||||
}))
|
||||
|
||||
|
||||
const { accessToken, refreshToken, userInfo } = res as any
|
||||
|
||||
localStorage.setItem('adminAccessToken', accessToken)
|
||||
localStorage.setItem('adminRefreshToken', refreshToken)
|
||||
localStorage.setItem('adminUserInfo', JSON.stringify(userInfo))
|
||||
sessionStorage.setItem('adminAccessToken', accessToken)
|
||||
sessionStorage.setItem('adminRefreshToken', refreshToken)
|
||||
|
||||
|
||||
message.success('登录成功')
|
||||
|
||||
await runWithGlobalLoading(() => loadUserPermissions())
|
||||
|
||||
const landingPath = resolveAdminLandingPath()
|
||||
router.push(landingPath).catch(err => {
|
||||
console.error('跳转到后台默认页面失败:', err)
|
||||
window.location.href = landingPath
|
||||
})
|
||||
} catch (error: any) {
|
||||
console.error('登录失败:', error)
|
||||
message.error(error.message || '登录失败,请检查用户名和密码')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
restoreLoginShop()
|
||||
})
|
||||
|
||||
watch(
|
||||
() => formState.account,
|
||||
value => {
|
||||
resetLoginShopTimer()
|
||||
const trimmedAccount = value.trim()
|
||||
if (!trimmedAccount) {
|
||||
applyLoginShopSelection(null)
|
||||
return
|
||||
}
|
||||
loginShopTimer = window.setTimeout(() => {
|
||||
loginShopTimer = undefined
|
||||
void loadLoginShops(trimmedAccount)
|
||||
}, 400)
|
||||
}
|
||||
)
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
resetLoginShopTimer()
|
||||
})
|
||||
|
||||
/** goToFrontend is a local helper used by this page script. */
|
||||
const goToFrontend = () => {
|
||||
localStorage.removeItem('adminAccessToken')
|
||||
localStorage.removeItem('adminRefreshToken')
|
||||
localStorage.removeItem('adminUserInfo')
|
||||
localStorage.removeItem('userPermissions')
|
||||
sessionStorage.removeItem('adminAccessToken')
|
||||
sessionStorage.removeItem('adminRefreshToken')
|
||||
|
||||
setTimeout(() => {
|
||||
window.location.href = '/'
|
||||
}, 100)
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.admin-login {
|
||||
min-height: 100dvh;
|
||||
background:
|
||||
linear-gradient(color-mix(in srgb, var(--theme-page-bg) 74%, transparent), color-mix(in srgb, var(--theme-page-bg) 90%, transparent)),
|
||||
var(--theme-background-image),
|
||||
linear-gradient(
|
||||
160deg,
|
||||
var(--theme-primary) 0%,
|
||||
var(--theme-accent) 58%,
|
||||
color-mix(in srgb, var(--theme-accent) 78%, var(--text-primary)) 100%
|
||||
);
|
||||
background-size: cover, cover, auto;
|
||||
background-position: center top;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: max(24px, env(safe-area-inset-top)) 24px max(24px, env(safe-area-inset-bottom));
|
||||
}
|
||||
|
||||
.login-container {
|
||||
width: 100%;
|
||||
max-width: 440px;
|
||||
}
|
||||
|
||||
.login-header {
|
||||
text-align: center;
|
||||
margin-bottom: 28px;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.login-header h1 {
|
||||
font-size: clamp(23px, 3.2vw, 28px);
|
||||
font-weight: 700;
|
||||
margin: 0 0 8px 0;
|
||||
}
|
||||
|
||||
.login-header p {
|
||||
font-size: 14px;
|
||||
line-height: 1.7;
|
||||
opacity: 0.82;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.login-card {
|
||||
border-radius: 24px;
|
||||
border: 1px solid var(--theme-border);
|
||||
box-shadow: var(--theme-button-shadow);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.login-footer {
|
||||
text-align: center;
|
||||
margin-top: 18px;
|
||||
}
|
||||
|
||||
.login-footer a {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 36px;
|
||||
padding: 0 14px;
|
||||
border-radius: 999px;
|
||||
color: var(--theme-primary);
|
||||
background: var(--theme-primary-soft);
|
||||
text-decoration: none;
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
box-shadow: 0 8px 20px color-mix(in srgb, var(--theme-primary) 18%, transparent);
|
||||
}
|
||||
|
||||
.login-footer a:hover {
|
||||
color: var(--theme-accent);
|
||||
background: var(--theme-card-bg);
|
||||
}
|
||||
|
||||
.login-card :deep(.ant-card-body) {
|
||||
background: var(--theme-card-bg);
|
||||
}
|
||||
|
||||
.login-card :deep(.ant-btn-primary) {
|
||||
border-color: transparent;
|
||||
background: var(--theme-gradient);
|
||||
box-shadow: var(--theme-button-shadow);
|
||||
}
|
||||
|
||||
.login-card :deep(.ant-btn-primary:hover),
|
||||
.login-card :deep(.ant-btn-primary:focus) {
|
||||
border-color: transparent;
|
||||
background: linear-gradient(135deg, var(--theme-accent) 0%, var(--theme-secondary) 100%);
|
||||
}
|
||||
|
||||
.login-card :deep(.ant-input:hover),
|
||||
.login-card :deep(.ant-input-affix-wrapper:hover),
|
||||
.login-card :deep(.ant-select:not(.ant-select-disabled):hover .ant-select-selector) {
|
||||
border-color: var(--theme-primary);
|
||||
}
|
||||
|
||||
.login-card :deep(.ant-input:focus),
|
||||
.login-card :deep(.ant-input-affix-wrapper-focused),
|
||||
.login-card :deep(.ant-select-focused .ant-select-selector) {
|
||||
border-color: var(--theme-primary);
|
||||
box-shadow: var(--theme-focus-shadow);
|
||||
}
|
||||
|
||||
@media (max-width: 960px) {
|
||||
.admin-login {
|
||||
align-items: flex-start;
|
||||
justify-content: stretch;
|
||||
padding: calc(22px + env(safe-area-inset-top)) 14px calc(18px + env(safe-area-inset-bottom));
|
||||
}
|
||||
|
||||
.login-container {
|
||||
max-width: none;
|
||||
}
|
||||
|
||||
.login-header {
|
||||
text-align: left;
|
||||
margin-bottom: 18px;
|
||||
padding: 0 4px;
|
||||
}
|
||||
|
||||
.login-header h1 {
|
||||
max-width: 8em;
|
||||
}
|
||||
|
||||
.login-card {
|
||||
border-radius: 26px;
|
||||
}
|
||||
|
||||
.login-card :deep(.ant-card-body) {
|
||||
padding: 20px 18px 18px;
|
||||
}
|
||||
|
||||
.login-card :deep(.ant-form-item) {
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
|
||||
.login-card :deep(.ant-btn-lg),
|
||||
.login-card :deep(.ant-input-affix-wrapper-lg),
|
||||
.login-card :deep(.ant-input-lg),
|
||||
.login-card :deep(.ant-select-single.ant-select-lg .ant-select-selector) {
|
||||
min-height: 48px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,708 +0,0 @@
|
||||
<template>
|
||||
<div class="nail-artists">
|
||||
<a-page-header v-if="!isMobile" title="美甲师管理" sub-title="管理美甲师详细信息" />
|
||||
|
||||
<section v-else class="admin-page-intro">
|
||||
<span class="admin-page-intro__eyebrow">经营</span>
|
||||
<h1 class="admin-page-intro__title">美甲师管理</h1>
|
||||
<p class="admin-page-intro__subtitle">
|
||||
把状态、技能和作品挂载关系收成单列卡片,手机端可以直接查看和编辑。
|
||||
</p>
|
||||
<div class="admin-page-intro__meta">
|
||||
<span class="admin-page-chip">美甲师 {{ nailArtistList.length }}</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<a-card :bordered="false">
|
||||
<template #title v-if="isMobile">
|
||||
美甲师列表
|
||||
</template>
|
||||
<template #extra>
|
||||
<div class="admin-toolbar" :class="{ 'admin-toolbar--stacked': isMobile }">
|
||||
<a-input-search
|
||||
v-model:value="searchText"
|
||||
placeholder="搜索美甲师姓名"
|
||||
:style="isMobile ? { width: '100%' } : { width: '250px' }"
|
||||
@search="handleSearch"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<a-table
|
||||
v-if="!isMobile"
|
||||
:columns="columns"
|
||||
:data-source="nailArtistList"
|
||||
:loading="loading"
|
||||
:pagination="pagination"
|
||||
@change="handleTableChange"
|
||||
row-key="userId"
|
||||
:scroll="{ x: 'max-content' }"
|
||||
>
|
||||
<template #bodyCell="{ column, record }">
|
||||
<template v-if="column.key === 'status'">
|
||||
<a-tag :color="getStatusColor(record.status)">
|
||||
{{ getStatusText(record.status) }}
|
||||
</a-tag>
|
||||
</template>
|
||||
<template v-else-if="column.key === 'userTypeName'">
|
||||
<a-tag :color="record.userType === 2 ? 'gold' : 'blue'">
|
||||
{{ record.userTypeName || (record.userType === 2 ? '店长' : '美甲师') }}
|
||||
</a-tag>
|
||||
</template>
|
||||
<template v-else-if="column.key === 'participateProduction'">
|
||||
<a-tag :color="record.participateProduction === 1 ? 'green' : 'default'">
|
||||
{{ record.participateProduction === 1 ? '参与制作' : '不参与' }}
|
||||
</a-tag>
|
||||
</template>
|
||||
<template v-else-if="column.key === 'workTime'">
|
||||
{{ formatWorkTime(record) }}
|
||||
</template>
|
||||
<template v-else-if="column.key === 'actions'">
|
||||
<a-space>
|
||||
<a-button v-if="hasPermission('nail_artist:view')" type="link" size="small" @click="showViewModal(record)">
|
||||
查看
|
||||
</a-button>
|
||||
<a-button v-if="hasPermission('nail_artist:edit')" type="link" size="small" @click="showEditModal(record)">
|
||||
编辑
|
||||
</a-button>
|
||||
</a-space>
|
||||
</template>
|
||||
</template>
|
||||
</a-table>
|
||||
|
||||
<AdminMobileCardList v-else :items="nailArtistList" item-key="userId" empty-description="暂无美甲师数据">
|
||||
<template #item="{ item }">
|
||||
<article class="admin-mobile-card">
|
||||
<div class="admin-mobile-card__head">
|
||||
<div class="admin-mobile-card__body">
|
||||
<div class="admin-mobile-card__title">{{ item.nickname }}</div>
|
||||
<div class="admin-mobile-card__subtitle">{{ item.shopName || '未绑定店铺' }}</div>
|
||||
</div>
|
||||
<a-tag :color="getStatusColor(item.status)">{{ getStatusText(item.status) }}</a-tag>
|
||||
</div>
|
||||
<div class="admin-mobile-card__rows">
|
||||
<div class="admin-mobile-card__row">
|
||||
<span>身份</span>
|
||||
<strong>{{ item.identity || '--' }}</strong>
|
||||
</div>
|
||||
<div class="admin-mobile-card__row">
|
||||
<span>从业年限</span>
|
||||
<strong>{{ item.experience ?? '--' }}</strong>
|
||||
</div>
|
||||
<div class="admin-mobile-card__row">
|
||||
<span>评分</span>
|
||||
<strong>{{ item.rating || '--' }}</strong>
|
||||
</div>
|
||||
</div>
|
||||
<div class="admin-mobile-card__actions">
|
||||
<a-button v-if="hasPermission('nail_artist:view')" size="small" @click="showViewModal(item)">查看</a-button>
|
||||
<a-button v-if="hasPermission('nail_artist:edit')" size="small" @click="showEditModal(item)">编辑</a-button>
|
||||
</div>
|
||||
</article>
|
||||
</template>
|
||||
</AdminMobileCardList>
|
||||
</a-card>
|
||||
|
||||
<!-- 编辑美甲师信息模态框 -->
|
||||
<AdminResponsiveModal
|
||||
v-model:open="modalVisible"
|
||||
title="编辑美甲师信息"
|
||||
@ok="handleModalOk"
|
||||
@cancel="handleModalCancel"
|
||||
:confirmLoading="modalLoading"
|
||||
:desktop-width="800"
|
||||
>
|
||||
<DraftActions
|
||||
:saved-at="draftSavedAt"
|
||||
@save="handleSaveDraft"
|
||||
@clear="handleClearDraft"
|
||||
/>
|
||||
<a-form
|
||||
ref="formRef"
|
||||
:model="formState"
|
||||
:rules="formRules"
|
||||
:label-col="{ span: 6 }"
|
||||
:wrapper-col="{ span: 16 }"
|
||||
>
|
||||
<a-form-item label="美甲师姓名" name="nickname">
|
||||
<a-input v-model:value="formState.nickname" :disabled="true" />
|
||||
</a-form-item>
|
||||
<a-form-item label="身份" name="identity">
|
||||
<a-input
|
||||
v-model:value="formState.identity"
|
||||
placeholder="请输入身份"
|
||||
:disabled="!isShopOwner"
|
||||
/>
|
||||
</a-form-item>
|
||||
<a-form-item label="从业年限" name="experience">
|
||||
<a-input-number
|
||||
v-model:value="formState.experience"
|
||||
:min="0"
|
||||
placeholder="请输入从业年限"
|
||||
:disabled="!isShopOwner"
|
||||
/>
|
||||
</a-form-item>
|
||||
<a-form-item label="技能标签" name="skills">
|
||||
<a-select
|
||||
v-model:value="formState.skills"
|
||||
mode="multiple"
|
||||
placeholder="请选择技能标签"
|
||||
:loading="tagLoading"
|
||||
>
|
||||
<a-select-option
|
||||
v-for="tag in tagList"
|
||||
:key="tag.id"
|
||||
:value="tag.id.toString()"
|
||||
>
|
||||
{{ tag.tagName }}
|
||||
</a-select-option>
|
||||
</a-select>
|
||||
</a-form-item>
|
||||
<a-form-item label="状态" name="status">
|
||||
<a-select
|
||||
v-model:value="formState.status"
|
||||
placeholder="请选择状态"
|
||||
:disabled="!isShopOwner"
|
||||
>
|
||||
<a-select-option :value="1">营业中</a-select-option>
|
||||
<a-select-option :value="0">休息中</a-select-option>
|
||||
</a-select>
|
||||
</a-form-item>
|
||||
<a-form-item label="参与制作" name="participateProduction">
|
||||
<a-switch
|
||||
v-model:checked="formState.participateProduction"
|
||||
:checked-value="1"
|
||||
:un-checked-value="0"
|
||||
:disabled="!isShopOwner"
|
||||
/>
|
||||
</a-form-item>
|
||||
<a-form-item label="工作时间">
|
||||
<a-input v-model:value="formState.workStartTime" type="time" placeholder="开始" />
|
||||
<span class="time-separator">至</span>
|
||||
<a-input v-model:value="formState.workEndTime" type="time" placeholder="结束" />
|
||||
</a-form-item>
|
||||
<a-form-item label="作品" name="portfolio">
|
||||
<a-select
|
||||
v-model:value="formState.portfolio"
|
||||
mode="multiple"
|
||||
placeholder="请选择作品作品"
|
||||
:loading="productLoading"
|
||||
>
|
||||
<a-select-option
|
||||
v-for="product in productList"
|
||||
:key="product.id"
|
||||
:value="product.id.toString()"
|
||||
>
|
||||
{{ product.title }}
|
||||
</a-select-option>
|
||||
</a-select>
|
||||
</a-form-item>
|
||||
<a-form-item label="评分">
|
||||
<a-input v-model:value="formState.rating" :disabled="true" />
|
||||
</a-form-item>
|
||||
</a-form>
|
||||
</AdminResponsiveModal>
|
||||
|
||||
<!-- 查看美甲师详情模态框 -->
|
||||
<AdminResponsiveModal
|
||||
v-model:open="viewModalVisible"
|
||||
title="查看美甲师详情"
|
||||
:footer="null"
|
||||
@cancel="handleViewModalCancel"
|
||||
:desktop-width="600"
|
||||
>
|
||||
<a-form
|
||||
:model="viewFormState"
|
||||
:label-col="{ span: 6 }"
|
||||
:wrapper-col="{ span: 16 }"
|
||||
>
|
||||
<a-form-item label="美甲师姓名">
|
||||
<a-input v-model:value="viewFormState.nickname" :disabled="true" />
|
||||
</a-form-item>
|
||||
<a-form-item label="所属店铺">
|
||||
<a-input v-model:value="viewFormState.shopName" :disabled="true" />
|
||||
</a-form-item>
|
||||
<a-form-item label="身份">
|
||||
<a-input v-model:value="viewFormState.identity" :disabled="true" />
|
||||
</a-form-item>
|
||||
<a-form-item label="从业年限">
|
||||
<a-input v-model:value="viewFormState.experience" :disabled="true" />
|
||||
</a-form-item>
|
||||
<a-form-item label="技能标签">
|
||||
<a-input v-model:value="viewFormState.skillsText" :disabled="true" />
|
||||
</a-form-item>
|
||||
<a-form-item label="状态">
|
||||
<a-input v-model:value="viewFormState.statusText" :disabled="true" />
|
||||
</a-form-item>
|
||||
<a-form-item label="人员类型">
|
||||
<a-input v-model:value="viewFormState.userTypeName" :disabled="true" />
|
||||
</a-form-item>
|
||||
<a-form-item label="工作时间">
|
||||
<a-input v-model:value="viewFormState.workTime" :disabled="true" />
|
||||
</a-form-item>
|
||||
<a-form-item label="评分">
|
||||
<a-input v-model:value="viewFormState.rating" :disabled="true" />
|
||||
</a-form-item>
|
||||
<a-form-item label="作品">
|
||||
<a-input v-model:value="viewFormState.portfolioText" :disabled="true" />
|
||||
</a-form-item>
|
||||
</a-form>
|
||||
</AdminResponsiveModal>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* NailArtistsView page script.
|
||||
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
|
||||
*/
|
||||
import { ref, reactive, onMounted } from 'vue'
|
||||
import { message } from 'ant-design-vue'
|
||||
import type { FormInstance } from 'ant-design-vue'
|
||||
import DraftActions from '@/components/DraftActions.vue'
|
||||
/**
|
||||
* Purpose: NailArtistInfoVO supports NailArtistsView.vue by holding or executing the nail artist info vo page or API role.
|
||||
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
import { adminNailArtistApi, type NailArtistInfoVO } from '@/api/admin'
|
||||
/**
|
||||
* Purpose: Tag supports NailArtistsView.vue by holding or executing the tag page or API role.
|
||||
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
import { adminTagApi, type Tag } from '@/api/admin'
|
||||
/**
|
||||
* Purpose: Product supports NailArtistsView.vue by holding or executing the product page or API role.
|
||||
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
import { adminProductApi, type Product } from '@/api/admin'
|
||||
import { buildDraftStorageKey, clearDraftRecord, loadDraftRecord, saveDraftRecord } from '@/utils/form-draft'
|
||||
import { usePermission } from '@/utils/permission'
|
||||
import { runWithGlobalLoading } from '@/utils/action-loading'
|
||||
import { useAdminViewport } from '@/composables/useAdminViewport'
|
||||
import AdminMobileCardList from '@/components/admin/AdminMobileCardList.vue'
|
||||
import AdminResponsiveModal from '@/components/admin/AdminResponsiveModal.vue'
|
||||
|
||||
const { hasPermission, loadUserPermissions } = usePermission()
|
||||
const { isMobile } = useAdminViewport()
|
||||
|
||||
/** getCurrentUserInfo is a local helper used by this page script. */
|
||||
const getCurrentUserInfo = () => {
|
||||
try {
|
||||
const userInfoStr = localStorage.getItem('adminUserInfo')
|
||||
if (userInfoStr) {
|
||||
const userInfo = JSON.parse(userInfoStr)
|
||||
isAdmin.value = userInfo.type === 4
|
||||
isShopOwner.value = userInfo.type === 2
|
||||
return userInfo
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('获取当前用户信息失败', error)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** loading is a reactive state variable used by the template and event handlers. */
|
||||
const loading = ref(false)
|
||||
/** tagLoading is a reactive state variable used by the template and event handlers. */
|
||||
const tagLoading = ref(false)
|
||||
/** productLoading is a reactive state variable used by the template and event handlers. */
|
||||
const productLoading = ref(false)
|
||||
/** searchText is a reactive state variable used by the template and event handlers. */
|
||||
const searchText = ref('')
|
||||
/**
|
||||
* Purpose: nailArtistList supports NailArtistsView.vue by holding or executing the nail artist list page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const nailArtistList = ref<NailArtistInfoVO[]>([])
|
||||
/**
|
||||
* Purpose: tagList supports NailArtistsView.vue by holding or executing the tag list page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const tagList = ref<Tag[]>([])
|
||||
/**
|
||||
* Purpose: productList supports NailArtistsView.vue by holding or executing the product list page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const productList = ref<Product[]>([])
|
||||
/** modalVisible is a reactive state variable used by the template and event handlers. */
|
||||
const modalVisible = ref(false)
|
||||
/** modalLoading is a reactive state variable used by the template and event handlers. */
|
||||
const modalLoading = ref(false)
|
||||
/** viewModalVisible is a reactive state variable used by the template and event handlers. */
|
||||
const viewModalVisible = ref(false)
|
||||
/** isAdmin is a reactive state variable used by the template and event handlers. */
|
||||
const isAdmin = ref(false)
|
||||
/** isShopOwner is a reactive state variable used by the template and event handlers. */
|
||||
const isShopOwner = ref(false)
|
||||
/**
|
||||
* Purpose: formRef supports NailArtistsView.vue by holding or executing the form ref page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const formRef = ref<FormInstance>()
|
||||
/**
|
||||
* Purpose: currentNailArtist supports NailArtistsView.vue by holding or executing the current nail artist page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const currentNailArtist = ref<NailArtistInfoVO | null>(null)
|
||||
/**
|
||||
* Purpose: currentUserInfo supports NailArtistsView.vue by holding or executing the current user info page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const currentUserInfo = getCurrentUserInfo()
|
||||
/**
|
||||
* Purpose: draftSavedAt supports NailArtistsView.vue by holding or executing the draft saved at page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const draftSavedAt = ref<number | null>(null)
|
||||
|
||||
/**
|
||||
* Purpose: viewFormState supports NailArtistsView.vue by holding or executing the view form state page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const viewFormState = reactive({
|
||||
nickname: '',
|
||||
shopName: '',
|
||||
identity: '',
|
||||
experience: '',
|
||||
skillsText: '',
|
||||
statusText: '',
|
||||
userTypeName: '',
|
||||
workTime: '',
|
||||
rating: '',
|
||||
portfolioText: ''
|
||||
})
|
||||
|
||||
/**
|
||||
* Purpose: pagination supports NailArtistsView.vue by holding or executing the pagination page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const pagination = reactive({
|
||||
current: 1,
|
||||
pageSize: 10,
|
||||
total: 0,
|
||||
showSizeChanger: true,
|
||||
showQuickJumper: true,
|
||||
showTotal: (total: number) => `共 ${total} 条`
|
||||
})
|
||||
|
||||
/**
|
||||
* Purpose: formState supports NailArtistsView.vue by holding or executing the form state page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const formState = reactive({
|
||||
userId: 0,
|
||||
identity: '',
|
||||
experience: 0,
|
||||
skills: [] as string[],
|
||||
rating: 0,
|
||||
status: 1,
|
||||
participateProduction: 1,
|
||||
workStartTime: '',
|
||||
workEndTime: '',
|
||||
portfolio: [] as string[],
|
||||
nickname: ''
|
||||
})
|
||||
|
||||
/** getDraftKey is a local helper used by this page script. */
|
||||
const getDraftKey = () => buildDraftStorageKey('admin-nail-artists', 'edit', currentNailArtist.value?.userId ?? formState.userId ?? 'unknown')
|
||||
|
||||
/** buildDraftPayload is a local helper used by this page script. */
|
||||
const buildDraftPayload = () => ({
|
||||
identity: formState.identity,
|
||||
experience: formState.experience,
|
||||
skills: [...formState.skills],
|
||||
status: formState.status,
|
||||
participateProduction: formState.participateProduction,
|
||||
workStartTime: formState.workStartTime,
|
||||
workEndTime: formState.workEndTime,
|
||||
portfolio: [...formState.portfolio]
|
||||
})
|
||||
|
||||
/** restoreDraft is a local helper used by this page script. */
|
||||
const restoreDraft = () => {
|
||||
const draft = loadDraftRecord<ReturnType<typeof buildDraftPayload>>(getDraftKey())
|
||||
if (!draft) {
|
||||
draftSavedAt.value = null
|
||||
return
|
||||
}
|
||||
Object.assign(formState, {
|
||||
identity: draft.payload.identity ?? formState.identity,
|
||||
experience: typeof draft.payload.experience === 'number' ? draft.payload.experience : formState.experience,
|
||||
skills: Array.isArray(draft.payload.skills) ? draft.payload.skills : formState.skills,
|
||||
status: typeof draft.payload.status === 'number'
|
||||
? (draft.payload.status === 0 ? 0 : 1)
|
||||
: formState.status,
|
||||
participateProduction: typeof draft.payload.participateProduction === 'number'
|
||||
? (draft.payload.participateProduction === 1 ? 1 : 0)
|
||||
: formState.participateProduction,
|
||||
workStartTime: draft.payload.workStartTime ?? formState.workStartTime,
|
||||
workEndTime: draft.payload.workEndTime ?? formState.workEndTime,
|
||||
portfolio: Array.isArray(draft.payload.portfolio) ? draft.payload.portfolio : formState.portfolio
|
||||
})
|
||||
draftSavedAt.value = draft.savedAt
|
||||
message.success('已恢复暂存内容')
|
||||
}
|
||||
|
||||
/** handleSaveDraft is a local helper used by this page script. */
|
||||
const handleSaveDraft = () => {
|
||||
const draft = saveDraftRecord(getDraftKey(), buildDraftPayload())
|
||||
draftSavedAt.value = draft.savedAt
|
||||
message.success('已暂存到本地')
|
||||
}
|
||||
|
||||
/** handleClearDraft is a local helper used by this page script. */
|
||||
const handleClearDraft = (showMessage = true) => {
|
||||
clearDraftRecord(getDraftKey())
|
||||
draftSavedAt.value = null
|
||||
if (showMessage) {
|
||||
message.success('已清除暂存')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: formRules supports NailArtistsView.vue by holding or executing the form rules page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const formRules = {
|
||||
identity: [{ required: true, message: '请输入身份', trigger: 'blur' }],
|
||||
experience: [{ required: true, message: '请输入从业年限', trigger: 'blur' }],
|
||||
skills: [{ required: true, message: '请选择技能标签', trigger: 'change' }],
|
||||
status: [{ required: true, message: '请选择状态', trigger: 'change' }],
|
||||
portfolio: [{ required: true, message: '请选择作品作品', trigger: 'change' }]
|
||||
} as any
|
||||
|
||||
/**
|
||||
* Purpose: columns supports NailArtistsView.vue by holding or executing the columns page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const columns = [
|
||||
{ title: '美甲师姓名', dataIndex: 'nickname', key: 'nickname' },
|
||||
{ title: '所属店铺', dataIndex: 'shopName', key: 'shopName' },
|
||||
{ title: '人员类型', key: 'userTypeName', width: 110 },
|
||||
{ title: '参与制作', key: 'participateProduction', width: 120 },
|
||||
{ title: '工作时间', key: 'workTime', width: 150 },
|
||||
{ title: '身份', dataIndex: 'identity', key: 'identity' },
|
||||
{ title: '从业年限', dataIndex: 'experience', key: 'experience' },
|
||||
{ title: '评分', dataIndex: 'rating', key: 'rating' },
|
||||
{ title: '状态', key: 'status', width: 100 },
|
||||
{ title: '操作', key: 'actions', width: 150, fixed: 'right' as const }
|
||||
]
|
||||
|
||||
/** getStatusText is a local helper used by this page script. */
|
||||
const getStatusText = (status: number) => {
|
||||
return status === 1 ? '营业中' : '休息中'
|
||||
}
|
||||
|
||||
/** getStatusColor is a local helper used by this page script. */
|
||||
const getStatusColor = (status: number) => {
|
||||
return status === 1 ? 'green' : 'default'
|
||||
}
|
||||
|
||||
/** formatWorkTime is a local helper used by this page script. */
|
||||
const formatWorkTime = (record: Partial<NailArtistInfoVO>) => {
|
||||
const start = record.workStartTime ? String(record.workStartTime).slice(0, 5) : ''
|
||||
const end = record.workEndTime ? String(record.workEndTime).slice(0, 5) : ''
|
||||
return start && end ? `${start} - ${end}` : '--'
|
||||
}
|
||||
|
||||
/** normalizeTime is a local helper used by this page script. */
|
||||
const normalizeTime = (value?: string) => value ? (String(value).length === 5 ? `${value}:00` : String(value)) : undefined
|
||||
|
||||
/** fetchTagList is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
||||
const fetchTagList = async () => {
|
||||
tagLoading.value = true
|
||||
try {
|
||||
const res = await adminTagApi.listAllTags() as unknown as Tag[]
|
||||
tagList.value = res || []
|
||||
} catch (error) {
|
||||
console.error('获取标签列表失败:', error)
|
||||
} finally {
|
||||
tagLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** fetchProductList is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
||||
const fetchProductList = async () => {
|
||||
productLoading.value = true
|
||||
try {
|
||||
const params: any = {
|
||||
page: 1,
|
||||
size: 1000
|
||||
}
|
||||
if (currentUserInfo && currentUserInfo.type !== 4 && currentUserInfo.shopId) {
|
||||
params.shopId = currentUserInfo.shopId
|
||||
}
|
||||
const res = await adminProductApi.listProducts(params) as unknown as { list: Product[] }
|
||||
productList.value = res.list || []
|
||||
} catch (error) {
|
||||
console.error('获取作品列表失败:', error)
|
||||
} finally {
|
||||
productLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** fetchNailArtistList is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
||||
const fetchNailArtistList = async () => {
|
||||
loading.value = true
|
||||
try {
|
||||
const res = await adminNailArtistApi.listNailArtists() as unknown as NailArtistInfoVO[]
|
||||
let filteredList = res || []
|
||||
|
||||
// 按搜索词过滤
|
||||
if (searchText.value) {
|
||||
filteredList = filteredList.filter((item: NailArtistInfoVO) =>
|
||||
item.nickname?.includes(searchText.value)
|
||||
)
|
||||
}
|
||||
|
||||
nailArtistList.value = filteredList
|
||||
pagination.total = filteredList.length || 0
|
||||
} catch (error) {
|
||||
message.error('获取美甲师列表失败')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** handleSearch is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
||||
const handleSearch = async () => {
|
||||
pagination.current = 1
|
||||
await runWithGlobalLoading(() => fetchNailArtistList())
|
||||
}
|
||||
|
||||
/** handleTableChange is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
||||
const handleTableChange = async (pag: any) => {
|
||||
pagination.current = pag.current
|
||||
pagination.pageSize = pag.pageSize
|
||||
await runWithGlobalLoading(() => fetchNailArtistList())
|
||||
}
|
||||
|
||||
/** showEditModal is a local helper used by this page script. */
|
||||
const showEditModal = (record: Record<string, any>) => {
|
||||
currentNailArtist.value = record as NailArtistInfoVO
|
||||
const lockedFields = {
|
||||
userId: record.userId,
|
||||
rating: record.rating || 0,
|
||||
nickname: record.nickname || ''
|
||||
}
|
||||
Object.assign(formState, {
|
||||
identity: record.identity || '',
|
||||
experience: record.experience || 0,
|
||||
skills: record.skills ? record.skills.split(',').filter(Boolean) : [],
|
||||
status: record.status || 1,
|
||||
participateProduction: record.participateProduction ?? (record.userType === 3 ? 1 : 0),
|
||||
workStartTime: record.workStartTime || '',
|
||||
workEndTime: record.workEndTime || '',
|
||||
portfolio: record.portfolio ? record.portfolio.split(',').filter(Boolean) : [],
|
||||
...lockedFields
|
||||
})
|
||||
restoreDraft()
|
||||
Object.assign(formState, lockedFields)
|
||||
modalVisible.value = true
|
||||
}
|
||||
|
||||
/** showViewModal is a local helper used by this page script. */
|
||||
const showViewModal = (record: Record<string, any>) => {
|
||||
const nailArtist = record as NailArtistInfoVO
|
||||
// 构建技能标签文本
|
||||
const skillsArray = nailArtist.skills ? nailArtist.skills.split(',').filter(Boolean) : []
|
||||
const skillsText = skillsArray.map(skillId => {
|
||||
const tag = tagList.value.find(t => t.id.toString() === skillId)
|
||||
return tag ? tag.tagName : skillId
|
||||
}).join(', ')
|
||||
|
||||
// 构建作品文本
|
||||
const portfolioArray = nailArtist.portfolio ? nailArtist.portfolio.split(',').filter(Boolean) : []
|
||||
const portfolioText = portfolioArray.map(productId => {
|
||||
const product = productList.value.find(p => p.id.toString() === productId)
|
||||
return product ? product.title : productId
|
||||
}).join(', ')
|
||||
|
||||
Object.assign(viewFormState, {
|
||||
nickname: nailArtist.nickname || '',
|
||||
shopName: nailArtist.shopName || '',
|
||||
identity: nailArtist.identity || '',
|
||||
experience: (nailArtist.experience || 0).toString(),
|
||||
skillsText: skillsText,
|
||||
statusText: getStatusText(nailArtist.status || 1),
|
||||
userTypeName: nailArtist.userTypeName || (nailArtist.userType === 2 ? '店长' : '美甲师'),
|
||||
workTime: formatWorkTime(nailArtist),
|
||||
rating: (nailArtist.rating || 0).toString(),
|
||||
portfolioText: portfolioText
|
||||
})
|
||||
viewModalVisible.value = true
|
||||
}
|
||||
|
||||
/** handleViewModalCancel is a local helper used by this page script. */
|
||||
const handleViewModalCancel = () => {
|
||||
viewModalVisible.value = false
|
||||
}
|
||||
|
||||
/** handleModalOk is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
||||
const handleModalOk = async () => {
|
||||
try {
|
||||
await formRef.value?.validate()
|
||||
|
||||
const targetUserId = currentNailArtist.value?.userId ?? formState.userId
|
||||
if (!targetUserId) {
|
||||
message.error('未获取到当前美甲师信息,请关闭弹窗后重试')
|
||||
return
|
||||
}
|
||||
|
||||
modalLoading.value = true
|
||||
|
||||
await runWithGlobalLoading(async () => {
|
||||
// 准备提交数据
|
||||
const submitData = {
|
||||
userId: targetUserId,
|
||||
identity: formState.identity,
|
||||
experience: formState.experience,
|
||||
rating: formState.rating,
|
||||
status: formState.status,
|
||||
participateProduction: formState.participateProduction,
|
||||
workStartTime: normalizeTime(formState.workStartTime),
|
||||
workEndTime: normalizeTime(formState.workEndTime),
|
||||
skills: formState.skills.join(','),
|
||||
portfolio: formState.portfolio.join(',')
|
||||
}
|
||||
|
||||
await adminNailArtistApi.saveNailArtistInfo(submitData)
|
||||
message.success('保存成功')
|
||||
|
||||
handleClearDraft(false)
|
||||
modalVisible.value = false
|
||||
await fetchNailArtistList()
|
||||
})
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
const errorMessage = (error as Error)?.message
|
||||
if (errorMessage) {
|
||||
message.error(errorMessage)
|
||||
return
|
||||
}
|
||||
message.error('操作失败')
|
||||
} finally {
|
||||
modalLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** handleModalCancel is a local helper used by this page script. */
|
||||
const handleModalCancel = () => {
|
||||
modalVisible.value = false
|
||||
currentNailArtist.value = null
|
||||
formRef.value?.resetFields()
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await loadUserPermissions()
|
||||
fetchTagList()
|
||||
fetchProductList()
|
||||
fetchNailArtistList()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.nail-artists {
|
||||
padding: 0;
|
||||
}
|
||||
</style>
|
||||
@@ -1,835 +0,0 @@
|
||||
<template>
|
||||
<div class="permissions">
|
||||
<a-page-header v-if="!isMobile" title="权限管理" sub-title="管理系统权限和用户权限分配" />
|
||||
|
||||
<section v-else class="admin-page-intro">
|
||||
<span class="admin-page-intro__eyebrow">经营</span>
|
||||
<h1 class="admin-page-intro__title">权限管理</h1>
|
||||
<p class="admin-page-intro__subtitle">
|
||||
手机端拆成“权限列表”和“用户权限”两段流程,先选人再分配,避免保留桌面双栏布局。
|
||||
</p>
|
||||
<div class="admin-page-intro__meta">
|
||||
<span class="admin-page-chip">权限 {{ permissionList.length }}</span>
|
||||
<span class="admin-page-chip">用户 {{ filteredUserList.length }}</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<a-card :bordered="false">
|
||||
<a-tabs v-model:activeKey="activeTab">
|
||||
<a-tab-pane key="permissions" tab="权限列表">
|
||||
<div style="margin-bottom: 16px;" :style="isMobile ? {} : { textAlign: 'right' }">
|
||||
<a-button v-if="!isMobile && hasPermission('permission:create')" type="primary" @click="showAddPermissionModal">
|
||||
<template #icon>
|
||||
<PlusOutlined />
|
||||
</template>
|
||||
新增权限
|
||||
</a-button>
|
||||
</div>
|
||||
|
||||
<a-table
|
||||
v-if="!isMobile"
|
||||
:columns="permissionColumns"
|
||||
:data-source="permissionList"
|
||||
:loading="loading"
|
||||
:pagination="permissionPagination"
|
||||
:scroll="{ x: 'max-content' }"
|
||||
@change="handlePermissionTableChange"
|
||||
row-key="id"
|
||||
>
|
||||
<template #bodyCell="{ column, record }">
|
||||
<template v-if="column.key === 'permissionGroup'">
|
||||
<a-tag color="purple">{{ record.permissionGroup }}</a-tag>
|
||||
</template>
|
||||
<template v-else-if="column.key === 'permissionCode'">
|
||||
<div style="max-width: 220px;">
|
||||
<TableEllipsisText :text="record.permissionCode" />
|
||||
</div>
|
||||
</template>
|
||||
<template v-else-if="column.key === 'permissionName'">
|
||||
<div style="max-width: 180px;">
|
||||
<TableEllipsisText :text="record.permissionName" />
|
||||
</div>
|
||||
</template>
|
||||
<template v-else-if="column.key === 'description'">
|
||||
<div style="max-width: 320px;">
|
||||
<TableEllipsisText :text="record.description" :lines="2" />
|
||||
</div>
|
||||
</template>
|
||||
<template v-else-if="column.key === 'actions'">
|
||||
<a-space>
|
||||
<a-button v-if="hasPermission('permission:edit')" type="link" size="small" @click="showEditPermissionModal(record)">
|
||||
编辑
|
||||
</a-button>
|
||||
<a-popconfirm
|
||||
v-if="hasPermission('permission:delete')"
|
||||
title="确定要删除这个权限吗?"
|
||||
@confirm="handleDeletePermission(record)"
|
||||
>
|
||||
<a-button type="link" size="small" danger>
|
||||
删除
|
||||
</a-button>
|
||||
</a-popconfirm>
|
||||
</a-space>
|
||||
</template>
|
||||
</template>
|
||||
</a-table>
|
||||
|
||||
<AdminMobileCardList v-else :items="permissionList" empty-description="暂无权限数据">
|
||||
<template #item="{ item }">
|
||||
<article class="admin-mobile-card">
|
||||
<div class="admin-mobile-card__head">
|
||||
<div class="admin-mobile-card__body">
|
||||
<div class="admin-mobile-card__title">{{ item.permissionName }}</div>
|
||||
<div class="admin-mobile-card__subtitle">{{ item.permissionCode }}</div>
|
||||
</div>
|
||||
<a-tag color="purple">{{ item.permissionGroup }}</a-tag>
|
||||
</div>
|
||||
<div class="admin-mobile-card__description">{{ item.description }}</div>
|
||||
<div class="admin-mobile-card__rows">
|
||||
<div class="admin-mobile-card__row">
|
||||
<span>创建时间</span>
|
||||
<strong>{{ item.createTime }}</strong>
|
||||
</div>
|
||||
</div>
|
||||
<div class="admin-mobile-card__actions">
|
||||
<a-button v-if="hasPermission('permission:edit')" size="small" @click="showEditPermissionModal(item)">编辑</a-button>
|
||||
<a-button v-if="hasPermission('permission:delete')" size="small" danger @click="handleDeletePermission(item)">删除</a-button>
|
||||
</div>
|
||||
</article>
|
||||
</template>
|
||||
</AdminMobileCardList>
|
||||
</a-tab-pane>
|
||||
|
||||
<a-tab-pane v-if="hasPermission('permission:assign')" key="user-permissions" tab="用户权限分配">
|
||||
<template v-if="!isMobile">
|
||||
<a-row :gutter="16">
|
||||
<a-col :span="8">
|
||||
<a-card title="选择用户" :bordered="false">
|
||||
<a-input-search
|
||||
v-model:value="userSearchText"
|
||||
placeholder="搜索用户"
|
||||
style="margin-bottom: 16px"
|
||||
@search="handleUserSearch"
|
||||
/>
|
||||
<a-list
|
||||
:data-source="filteredUserList"
|
||||
:loading="userLoading"
|
||||
item-layout="horizontal"
|
||||
size="small"
|
||||
>
|
||||
<template #renderItem="{ item }">
|
||||
<a-list-item
|
||||
:class="{ selected: sameId(selectedUser?.id, item.id) }"
|
||||
style="cursor: pointer;"
|
||||
@click="selectUser(item)"
|
||||
>
|
||||
<a-list-item-meta>
|
||||
<template #avatar>
|
||||
<a-avatar :src="item.avatar || DEFAULT_AVATAR" />
|
||||
</template>
|
||||
<template #title>{{ item.nickname }}</template>
|
||||
<template #description>{{ item.account }} - {{ getUserTypeText(item.type) }}</template>
|
||||
</a-list-item-meta>
|
||||
</a-list-item>
|
||||
</template>
|
||||
</a-list>
|
||||
</a-card>
|
||||
</a-col>
|
||||
<a-col :span="16">
|
||||
<a-card
|
||||
title="分配权限"
|
||||
:bordered="false"
|
||||
>
|
||||
<template #extra>
|
||||
<a-button v-if="selectedUser && hasPermission('permission:assign')" type="primary" @click="handleSaveUserPermissions">
|
||||
保存权限
|
||||
</a-button>
|
||||
</template>
|
||||
<template v-if="selectedUser">
|
||||
<a-alert
|
||||
:message="`当前用户: ${selectedUser.nickname}`"
|
||||
:description="`用户类型: ${getUserTypeText(selectedUser.type)}`"
|
||||
type="info"
|
||||
show-icon
|
||||
style="margin-bottom: 16px"
|
||||
/>
|
||||
<a-alert
|
||||
v-if="disabledPermissionCount > 0"
|
||||
:message="`有 ${disabledPermissionCount} 项权限不在该角色可分配范围内,已禁止选择`"
|
||||
type="warning"
|
||||
show-icon
|
||||
style="margin-bottom: 16px"
|
||||
/>
|
||||
|
||||
<a-spin :spinning="assignLoading">
|
||||
<a-checkbox-group v-model:value="selectedPermissions">
|
||||
<a-collapse v-model:activeKey="activeCollapseKeys">
|
||||
<a-collapse-panel
|
||||
v-for="(permissions, group) in groupedPermissions"
|
||||
:key="group"
|
||||
:header="group"
|
||||
>
|
||||
<a-space direction="vertical" style="width: 100%">
|
||||
<a-checkbox
|
||||
v-for="permission in permissions"
|
||||
:key="permission.id"
|
||||
:value="permission.id"
|
||||
:disabled="isPermissionDisabled(permission)"
|
||||
>
|
||||
{{ permission.permissionName }}
|
||||
<span style="color: var(--text-secondary); font-size: 12px; margin-left: 8px;">
|
||||
({{ permission.permissionCode }})
|
||||
</span>
|
||||
<span
|
||||
v-if="isPermissionDisabled(permission)"
|
||||
style="color: #ff4d4f; font-size: 12px; margin-left: 8px;"
|
||||
>
|
||||
不可分配
|
||||
</span>
|
||||
</a-checkbox>
|
||||
</a-space>
|
||||
</a-collapse-panel>
|
||||
</a-collapse>
|
||||
</a-checkbox-group>
|
||||
</a-spin>
|
||||
</template>
|
||||
<a-empty v-else description="请先选择一个用户" />
|
||||
</a-card>
|
||||
</a-col>
|
||||
</a-row>
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<div class="mobile-permission-flow">
|
||||
<template v-if="mobilePermissionStep === 'users' || !selectedUser">
|
||||
<a-input-search
|
||||
v-model:value="userSearchText"
|
||||
placeholder="搜索用户"
|
||||
style="margin-bottom: 16px"
|
||||
@search="handleUserSearch"
|
||||
/>
|
||||
<AdminMobileCardList :items="filteredUserList" empty-description="暂无可分配权限的用户">
|
||||
<template #item="{ item }">
|
||||
<article class="admin-mobile-card" @click="selectUser(item)">
|
||||
<div class="admin-mobile-card__head">
|
||||
<div class="mobile-user-pick">
|
||||
<a-avatar :src="item.avatar || DEFAULT_AVATAR" />
|
||||
<div class="admin-mobile-card__body">
|
||||
<div class="admin-mobile-card__title">{{ item.nickname }}</div>
|
||||
<div class="admin-mobile-card__subtitle">{{ item.account }} · {{ getUserTypeText(item.type) }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<span class="admin-mobile-card__badge">选择</span>
|
||||
</div>
|
||||
</article>
|
||||
</template>
|
||||
</AdminMobileCardList>
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<div class="mobile-assign-actions">
|
||||
<a-button @click="mobilePermissionStep = 'users'">返回选用户</a-button>
|
||||
<a-button type="primary" @click="handleSaveUserPermissions">保存权限</a-button>
|
||||
</div>
|
||||
|
||||
<a-alert
|
||||
:message="`当前用户: ${selectedUser.nickname}`"
|
||||
:description="`用户类型: ${getUserTypeText(selectedUser.type)}`"
|
||||
type="info"
|
||||
show-icon
|
||||
style="margin-bottom: 16px"
|
||||
/>
|
||||
<a-alert
|
||||
v-if="disabledPermissionCount > 0"
|
||||
:message="`有 ${disabledPermissionCount} 项权限不在该角色可分配范围内,已禁用`"
|
||||
type="warning"
|
||||
show-icon
|
||||
style="margin-bottom: 16px"
|
||||
/>
|
||||
|
||||
<a-spin :spinning="assignLoading">
|
||||
<a-checkbox-group v-model:value="selectedPermissions" style="width: 100%">
|
||||
<a-collapse v-model:activeKey="activeCollapseKeys">
|
||||
<a-collapse-panel
|
||||
v-for="(permissions, group) in groupedPermissions"
|
||||
:key="group"
|
||||
:header="group"
|
||||
>
|
||||
<a-space direction="vertical" style="width: 100%">
|
||||
<a-checkbox
|
||||
v-for="permission in permissions"
|
||||
:key="permission.id"
|
||||
:value="permission.id"
|
||||
:disabled="isPermissionDisabled(permission)"
|
||||
>
|
||||
{{ permission.permissionName }}
|
||||
<span style="color: var(--text-secondary); font-size: 12px; margin-left: 8px;">
|
||||
({{ permission.permissionCode }})
|
||||
</span>
|
||||
</a-checkbox>
|
||||
</a-space>
|
||||
</a-collapse-panel>
|
||||
</a-collapse>
|
||||
</a-checkbox-group>
|
||||
</a-spin>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
</a-tab-pane>
|
||||
</a-tabs>
|
||||
</a-card>
|
||||
|
||||
<AdminResponsiveModal
|
||||
v-model:open="permissionModalVisible"
|
||||
:title="isEditPermission ? '编辑权限' : '新增权限'"
|
||||
@ok="handlePermissionModalOk"
|
||||
@cancel="handlePermissionModalCancel"
|
||||
:confirmLoading="permissionModalLoading"
|
||||
>
|
||||
<DraftActions
|
||||
:saved-at="draftSavedAt"
|
||||
@save="handleSaveDraft"
|
||||
@clear="handleClearDraft"
|
||||
/>
|
||||
<a-form
|
||||
ref="permissionFormRef"
|
||||
:model="permissionFormState"
|
||||
:rules="permissionFormRules"
|
||||
:label-col="{ span: 6 }"
|
||||
:wrapper-col="{ span: 16 }"
|
||||
>
|
||||
<a-form-item label="权限编码" name="permissionCode">
|
||||
<a-input v-model:value="permissionFormState.permissionCode" placeholder="例如:product:add" />
|
||||
</a-form-item>
|
||||
<a-form-item label="权限名称" name="permissionName">
|
||||
<a-input v-model:value="permissionFormState.permissionName" placeholder="例如:添加作品" />
|
||||
</a-form-item>
|
||||
<a-form-item label="权限分组" name="permissionGroup">
|
||||
<a-select v-model:value="permissionFormState.permissionGroup" placeholder="请选择权限分组">
|
||||
<a-select-option value="作品管理">作品管理</a-select-option>
|
||||
<a-select-option value="店铺管理">店铺管理</a-select-option>
|
||||
<a-select-option value="用户管理">用户管理</a-select-option>
|
||||
<a-select-option value="权限管理">权限管理</a-select-option>
|
||||
</a-select>
|
||||
</a-form-item>
|
||||
<a-form-item label="权限描述" name="description">
|
||||
<a-textarea
|
||||
v-model:value="permissionFormState.description"
|
||||
placeholder="请输入权限描述"
|
||||
:rows="3"
|
||||
/>
|
||||
</a-form-item>
|
||||
</a-form>
|
||||
</AdminResponsiveModal>
|
||||
|
||||
<AdminMobileFab
|
||||
:visible="isMobile && activeTab === 'permissions' && hasPermission('permission:create') && !permissionModalVisible"
|
||||
label="新增权限"
|
||||
@click="showAddPermissionModal"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* PermissionsView page script.
|
||||
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
|
||||
*/
|
||||
import { ref, reactive, computed, onMounted, watch } from 'vue'
|
||||
import { message } from 'ant-design-vue'
|
||||
import type { FormInstance } from 'ant-design-vue'
|
||||
import type { Rule } from 'ant-design-vue/es/form'
|
||||
import { PlusOutlined } from '@ant-design/icons-vue'
|
||||
import DraftActions from '@/components/DraftActions.vue'
|
||||
import TableEllipsisText from '@/components/TableEllipsisText.vue'
|
||||
import { DEFAULT_AVATAR } from '@/constants'
|
||||
/**
|
||||
* Purpose: UserVO supports PermissionsView.vue by holding or executing the user vo page or API role.
|
||||
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
import { userApi, type UserVO } from '@/api/admin'
|
||||
/**
|
||||
* Purpose: PermissionVO supports PermissionsView.vue by holding or executing the permission vo page or API role.
|
||||
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
import { permissionApi, type PermissionVO } from '@/api/permission'
|
||||
import { buildDraftStorageKey, clearDraftRecord, loadDraftRecord, saveDraftRecord } from '@/utils/form-draft'
|
||||
import { usePermission } from '@/utils/permission'
|
||||
import type { IdType } from '@/utils/id'
|
||||
import { sameId } from '@/utils/id'
|
||||
import { runWithGlobalLoading } from '@/utils/action-loading'
|
||||
import { useAdminViewport } from '@/composables/useAdminViewport'
|
||||
import AdminMobileCardList from '@/components/admin/AdminMobileCardList.vue'
|
||||
import AdminMobileFab from '@/components/admin/AdminMobileFab.vue'
|
||||
import AdminResponsiveModal from '@/components/admin/AdminResponsiveModal.vue'
|
||||
|
||||
const { hasPermission, loadUserPermissions } = usePermission()
|
||||
const { isMobile } = useAdminViewport()
|
||||
|
||||
/** activeTab is a reactive state variable used by the template and event handlers. */
|
||||
const activeTab = ref('permissions')
|
||||
/** loading is a reactive state variable used by the template and event handlers. */
|
||||
const loading = ref(false)
|
||||
/**
|
||||
* Purpose: permissionList supports PermissionsView.vue by holding or executing the permission list page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const permissionList = ref<PermissionVO[]>([])
|
||||
/** permissionModalVisible is a reactive state variable used by the template and event handlers. */
|
||||
const permissionModalVisible = ref(false)
|
||||
/** permissionModalLoading is a reactive state variable used by the template and event handlers. */
|
||||
const permissionModalLoading = ref(false)
|
||||
/** isEditPermission is a reactive state variable used by the template and event handlers. */
|
||||
const isEditPermission = ref(false)
|
||||
/**
|
||||
* Purpose: permissionFormRef supports PermissionsView.vue by holding or executing the permission form ref page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const permissionFormRef = ref<FormInstance>()
|
||||
/**
|
||||
* Purpose: currentPermission supports PermissionsView.vue by holding or executing the current permission page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const currentPermission = ref<PermissionVO | null>(null)
|
||||
/**
|
||||
* Purpose: draftSavedAt supports PermissionsView.vue by holding or executing the draft saved at page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const draftSavedAt = ref<number | null>(null)
|
||||
|
||||
/**
|
||||
* Purpose: permissionPagination supports PermissionsView.vue by holding or executing the permission pagination page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const permissionPagination = reactive({
|
||||
current: 1,
|
||||
pageSize: 20,
|
||||
total: 0,
|
||||
showSizeChanger: true,
|
||||
showQuickJumper: true,
|
||||
showTotal: (total: number) => `共 ${total} 条`
|
||||
})
|
||||
|
||||
/**
|
||||
* Purpose: permissionFormState supports PermissionsView.vue by holding or executing the permission form state page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const permissionFormState = reactive({
|
||||
permissionCode: '',
|
||||
permissionName: '',
|
||||
permissionGroup: '',
|
||||
description: ''
|
||||
})
|
||||
|
||||
/** getDraftKey is a local helper used by this page script. */
|
||||
const getDraftKey = () => buildDraftStorageKey('admin-permissions', isEditPermission.value ? 'edit' : 'create', currentPermission.value?.id ?? 'new')
|
||||
|
||||
/** buildDraftPayload is a local helper used by this page script. */
|
||||
const buildDraftPayload = () => ({
|
||||
permissionCode: permissionFormState.permissionCode,
|
||||
permissionName: permissionFormState.permissionName,
|
||||
permissionGroup: permissionFormState.permissionGroup,
|
||||
description: permissionFormState.description
|
||||
})
|
||||
|
||||
/** restoreDraft is a local helper used by this page script. */
|
||||
const restoreDraft = () => {
|
||||
const draft = loadDraftRecord<ReturnType<typeof buildDraftPayload>>(getDraftKey())
|
||||
if (!draft) {
|
||||
draftSavedAt.value = null
|
||||
return
|
||||
}
|
||||
Object.assign(permissionFormState, draft.payload)
|
||||
draftSavedAt.value = draft.savedAt
|
||||
message.success('已恢复暂存内容')
|
||||
}
|
||||
|
||||
/** handleSaveDraft is a local helper used by this page script. */
|
||||
const handleSaveDraft = () => {
|
||||
const draft = saveDraftRecord(getDraftKey(), buildDraftPayload())
|
||||
draftSavedAt.value = draft.savedAt
|
||||
message.success('已暂存到本地')
|
||||
}
|
||||
|
||||
/** handleClearDraft is a local helper used by this page script. */
|
||||
const handleClearDraft = (showMessage = true) => {
|
||||
clearDraftRecord(getDraftKey())
|
||||
draftSavedAt.value = null
|
||||
if (showMessage) {
|
||||
message.success('已清除暂存')
|
||||
}
|
||||
}
|
||||
|
||||
const permissionFormRules: Record<string, Rule[]> = {
|
||||
permissionCode: [{ required: true, message: '请输入权限编码', trigger: 'blur' }],
|
||||
permissionName: [{ required: true, message: '请输入权限名称', trigger: 'blur' }],
|
||||
permissionGroup: [{ required: true, message: '请选择权限分组', trigger: 'change' }],
|
||||
description: [{ required: true, message: '请输入权限描述', trigger: 'blur' }]
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: permissionColumns supports PermissionsView.vue by holding or executing the permission columns page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const permissionColumns = [
|
||||
{ title: '权限编码', dataIndex: 'permissionCode', key: 'permissionCode' },
|
||||
{ title: '权限名称', dataIndex: 'permissionName', key: 'permissionName' },
|
||||
{ title: '权限分组', key: 'permissionGroup', width: 120 },
|
||||
{ title: '权限描述', dataIndex: 'description', key: 'description' },
|
||||
{ title: '创建时间', dataIndex: 'createTime', key: 'createTime' },
|
||||
{ title: '操作', key: 'actions', width: 150, fixed: 'right' as const }
|
||||
]
|
||||
|
||||
/** userLoading is a reactive state variable used by the template and event handlers. */
|
||||
const userLoading = ref(false)
|
||||
/** userSearchText is a reactive state variable used by the template and event handlers. */
|
||||
const userSearchText = ref('')
|
||||
/**
|
||||
* Purpose: userList supports PermissionsView.vue by holding or executing the user list page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const userList = ref<UserVO[]>([])
|
||||
/**
|
||||
* Purpose: selectedUser supports PermissionsView.vue by holding or executing the selected user page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const selectedUser = ref<UserVO | null>(null)
|
||||
/** assignLoading is a reactive state variable used by the template and event handlers. */
|
||||
const assignLoading = ref(false)
|
||||
/**
|
||||
* Purpose: selectedPermissions supports PermissionsView.vue by holding or executing the selected permissions page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const selectedPermissions = ref<IdType[]>([])
|
||||
/**
|
||||
* Purpose: assignablePermissionIds supports PermissionsView.vue by holding or executing the assignable permission ids page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const assignablePermissionIds = ref<IdType[]>([])
|
||||
/**
|
||||
* Purpose: activeCollapseKeys supports PermissionsView.vue by holding or executing the active collapse keys page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const activeCollapseKeys = ref<string[]>(['作品管理', '店铺管理', '用户管理', '权限管理'])
|
||||
/**
|
||||
* Purpose: currentLoginUser supports PermissionsView.vue by holding or executing the current login user page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const currentLoginUser = ref<UserVO | null>(null)
|
||||
/**
|
||||
* Purpose: mobilePermissionStep supports PermissionsView.vue by holding or executing the mobile permission step page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const mobilePermissionStep = ref<'users' | 'assign'>('users')
|
||||
|
||||
// 权限 ID 同样可能以字符串形式返回,所以这里统一转成字符串集合做包含判断。
|
||||
/** assignablePermissionIdSet is a reactive state variable used by the template and event handlers. */
|
||||
const assignablePermissionIdSet = computed(() => new Set(assignablePermissionIds.value.map(id => String(id))))
|
||||
/** disabledPermissionCount is a reactive state variable used by the template and event handlers. */
|
||||
const disabledPermissionCount = computed(() =>
|
||||
permissionList.value.filter(permission => !assignablePermissionIdSet.value.has(String(permission.id))).length
|
||||
)
|
||||
|
||||
/** groupedPermissions is a reactive state variable used by the template and event handlers. */
|
||||
const groupedPermissions = computed(() => {
|
||||
const groups: Record<string, PermissionVO[]> = {}
|
||||
permissionList.value.forEach(p => {
|
||||
const groupName = p.permissionGroup
|
||||
if (!groups[groupName]) {
|
||||
groups[groupName] = []
|
||||
}
|
||||
groups[groupName]!.push(p)
|
||||
})
|
||||
return groups
|
||||
})
|
||||
|
||||
/** getUserTypeText is a local helper used by this page script. */
|
||||
const getUserTypeText = (type: number) => {
|
||||
const map: Record<number, string> = {
|
||||
0: '用户',
|
||||
2: '店长',
|
||||
3: '美甲师',
|
||||
4: '管理员'
|
||||
}
|
||||
return map[type] || '未知'
|
||||
}
|
||||
|
||||
/** filteredUserList is a reactive state variable used by the template and event handlers. */
|
||||
const filteredUserList = computed(() => {
|
||||
if (!currentLoginUser.value) return []
|
||||
|
||||
const currentUserId = currentLoginUser.value.id
|
||||
|
||||
// 管理员可以看到所有用户(除了普通用户和自己)
|
||||
if (currentLoginUser.value.type === 4) {
|
||||
return userList.value.filter(user => user.type !== 0 && !sameId(user.id, currentUserId))
|
||||
}
|
||||
|
||||
// 店长只能看到美甲师(除了自己)
|
||||
if (currentLoginUser.value.type === 2) {
|
||||
return userList.value.filter(user => user.type === 3 && !sameId(user.id, currentUserId))
|
||||
}
|
||||
|
||||
// 其他用户类型(如美甲师)不能管理权限
|
||||
return []
|
||||
})
|
||||
|
||||
/** isPermissionDisabled is a local helper used by this page script. */
|
||||
const isPermissionDisabled = (permission: PermissionVO) => {
|
||||
if (!selectedUser.value) {
|
||||
return true
|
||||
}
|
||||
return !assignablePermissionIdSet.value.has(String(permission.id))
|
||||
}
|
||||
|
||||
/** resolveRequestErrorMessage is a local helper used by this page script. */
|
||||
const resolveRequestErrorMessage = (error: any, fallback: string) => {
|
||||
return error?.response?.data?.message || error?.message || fallback
|
||||
}
|
||||
|
||||
/** fetchCurrentUser is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
||||
const fetchCurrentUser = async () => {
|
||||
try {
|
||||
// 尝试从API获取用户信息
|
||||
try {
|
||||
const res = await userApi.getUserInfo()
|
||||
currentLoginUser.value = res as unknown as UserVO
|
||||
} catch (apiError) {
|
||||
// 如果API调用失败,尝试从本地存储获取
|
||||
const userInfoStr = localStorage.getItem('adminUserInfo')
|
||||
if (userInfoStr) {
|
||||
try {
|
||||
const userInfo = JSON.parse(userInfoStr)
|
||||
currentLoginUser.value = userInfo as UserVO
|
||||
} catch (parseError) {
|
||||
console.error('解析本地存储的用户信息失败:', parseError)
|
||||
}
|
||||
} else {
|
||||
console.error('获取当前用户信息失败,本地存储也没有用户信息')
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取当前用户信息失败:', error)
|
||||
}
|
||||
}
|
||||
|
||||
/** fetchPermissionList is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
||||
const fetchPermissionList = async () => {
|
||||
loading.value = true
|
||||
try {
|
||||
const res = await permissionApi.listAllPermissions() as unknown as PermissionVO[]
|
||||
permissionList.value = res || []
|
||||
permissionPagination.total = res?.length || 0
|
||||
} catch (error) {
|
||||
message.error('获取权限列表失败')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** fetchUserList is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
||||
const fetchUserList = async () => {
|
||||
userLoading.value = true
|
||||
try {
|
||||
const params: any = {
|
||||
page: 1,
|
||||
size: 100,
|
||||
keyword: userSearchText.value
|
||||
}
|
||||
|
||||
// 如果当前用户不是管理员,只获取当前店铺的用户
|
||||
if (currentLoginUser.value && currentLoginUser.value.type !== 4 && currentLoginUser.value.shopId) {
|
||||
params.shopId = currentLoginUser.value.shopId
|
||||
}
|
||||
|
||||
const res = await userApi.listUsers(params) as unknown as { list: UserVO[] }
|
||||
userList.value = res.list || []
|
||||
} catch (error) {
|
||||
message.error('获取用户列表失败')
|
||||
} finally {
|
||||
userLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** handlePermissionTableChange is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
||||
const handlePermissionTableChange = async (pag: any) => {
|
||||
permissionPagination.current = pag.current
|
||||
permissionPagination.pageSize = pag.pageSize
|
||||
await runWithGlobalLoading(() => fetchPermissionList())
|
||||
}
|
||||
|
||||
/** handleUserSearch is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
||||
const handleUserSearch = async () => {
|
||||
await runWithGlobalLoading(() => fetchUserList())
|
||||
}
|
||||
|
||||
/** selectUser is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
||||
const selectUser = async (user: UserVO) => {
|
||||
selectedUser.value = user
|
||||
assignLoading.value = true
|
||||
try {
|
||||
await runWithGlobalLoading(async () => {
|
||||
// 已分配权限和“当前角色允许分配的权限”需要分开拿,前端只保留交集,避免保存时越权。
|
||||
const [assignedPermissions, allowedIds] = await Promise.all([
|
||||
permissionApi.getUserPermissions(user.id) as unknown as Promise<PermissionVO[]>,
|
||||
permissionApi.getAssignablePermissionIds(user.id) as unknown as Promise<IdType[]>
|
||||
])
|
||||
assignablePermissionIds.value = allowedIds || []
|
||||
const allowedIdSet = new Set(assignablePermissionIds.value.map(id => String(id)))
|
||||
/** assignedIds is a local helper used by this page script. */
|
||||
const assignedIds = (assignedPermissions || []).map((p: PermissionVO) => p.id)
|
||||
selectedPermissions.value = assignedIds.filter(id => allowedIdSet.has(String(id)))
|
||||
const trimmedCount = assignedIds.length - selectedPermissions.value.length
|
||||
if (trimmedCount > 0) {
|
||||
message.warning(`已自动排除 ${trimmedCount} 项超出当前角色允许范围的权限`)
|
||||
}
|
||||
})
|
||||
} catch (error: any) {
|
||||
message.error(resolveRequestErrorMessage(error, '获取用户权限失败'))
|
||||
assignablePermissionIds.value = []
|
||||
selectedPermissions.value = []
|
||||
} finally {
|
||||
assignLoading.value = false
|
||||
if (isMobile.value) {
|
||||
mobilePermissionStep.value = 'assign'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** handleSaveUserPermissions is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
||||
const handleSaveUserPermissions = async () => {
|
||||
if (!selectedUser.value) return
|
||||
const userId = selectedUser.value.id
|
||||
try {
|
||||
await runWithGlobalLoading(async () => {
|
||||
await permissionApi.assignUserPermissions(userId, selectedPermissions.value)
|
||||
message.success('权限保存成功')
|
||||
// 重新加载当前用户的权限
|
||||
await loadUserPermissions()
|
||||
})
|
||||
} catch (error: any) {
|
||||
message.error(resolveRequestErrorMessage(error, '权限保存失败'))
|
||||
}
|
||||
}
|
||||
|
||||
/** showAddPermissionModal is a local helper used by this page script. */
|
||||
const showAddPermissionModal = () => {
|
||||
isEditPermission.value = false
|
||||
currentPermission.value = null
|
||||
Object.assign(permissionFormState, {
|
||||
permissionCode: '',
|
||||
permissionName: '',
|
||||
permissionGroup: '',
|
||||
description: ''
|
||||
})
|
||||
restoreDraft()
|
||||
permissionModalVisible.value = true
|
||||
}
|
||||
|
||||
/** showEditPermissionModal is a local helper used by this page script. */
|
||||
const showEditPermissionModal = (record: Record<string, any>) => {
|
||||
isEditPermission.value = true
|
||||
currentPermission.value = record as PermissionVO
|
||||
Object.assign(permissionFormState, {
|
||||
permissionCode: record.permissionCode,
|
||||
permissionName: record.permissionName,
|
||||
permissionGroup: record.permissionGroup,
|
||||
description: record.description
|
||||
})
|
||||
restoreDraft()
|
||||
permissionModalVisible.value = true
|
||||
}
|
||||
|
||||
/** handlePermissionModalOk is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
||||
const handlePermissionModalOk = async () => {
|
||||
try {
|
||||
await permissionFormRef.value?.validate()
|
||||
permissionModalLoading.value = true
|
||||
|
||||
await runWithGlobalLoading(async () => {
|
||||
if (isEditPermission.value && currentPermission.value) {
|
||||
await permissionApi.updatePermission(currentPermission.value.id, permissionFormState)
|
||||
message.success('更新成功')
|
||||
} else {
|
||||
await permissionApi.createPermission(permissionFormState)
|
||||
message.success('创建成功')
|
||||
}
|
||||
|
||||
handleClearDraft(false)
|
||||
permissionModalVisible.value = false
|
||||
await fetchPermissionList()
|
||||
})
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
} finally {
|
||||
permissionModalLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** handlePermissionModalCancel is a local helper used by this page script. */
|
||||
const handlePermissionModalCancel = () => {
|
||||
permissionModalVisible.value = false
|
||||
permissionFormRef.value?.resetFields()
|
||||
}
|
||||
|
||||
/** handleDeletePermission is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
||||
const handleDeletePermission = async (record: Record<string, any>) => {
|
||||
try {
|
||||
await runWithGlobalLoading(async () => {
|
||||
await permissionApi.deletePermission((record as PermissionVO).id)
|
||||
message.success('删除成功')
|
||||
await fetchPermissionList()
|
||||
})
|
||||
} catch (error) {
|
||||
message.error('删除失败')
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await fetchCurrentUser()
|
||||
await loadUserPermissions()
|
||||
fetchPermissionList()
|
||||
// 确保在获取当前用户信息后再获取用户列表
|
||||
setTimeout(() => {
|
||||
fetchUserList()
|
||||
}, 100)
|
||||
})
|
||||
|
||||
watch(
|
||||
() => activeTab.value,
|
||||
value => {
|
||||
if (value !== 'user-permissions') {
|
||||
mobilePermissionStep.value = 'users'
|
||||
}
|
||||
}
|
||||
)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.permissions {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.selected {
|
||||
background: var(--theme-primary-soft) !important;
|
||||
border-left: 3px solid var(--theme-primary);
|
||||
}
|
||||
|
||||
.mobile-permission-flow {
|
||||
display: grid;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.mobile-user-pick {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.mobile-assign-actions {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
}
|
||||
</style>
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,662 +0,0 @@
|
||||
<template>
|
||||
<div class="tags">
|
||||
<a-page-header v-if="!isMobile" title="标签管理" sub-title="管理系统标签" />
|
||||
|
||||
<section v-else class="admin-page-intro">
|
||||
<span class="admin-page-intro__eyebrow">经营</span>
|
||||
<h1 class="admin-page-intro__title">标签管理</h1>
|
||||
<div class="admin-page-intro__meta">
|
||||
<span class="admin-page-chip">标签 {{ tagList.length }}</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<a-card :bordered="false">
|
||||
<template #title v-if="isMobile">
|
||||
标签列表
|
||||
</template>
|
||||
<template #extra>
|
||||
<div class="admin-toolbar" :class="{ 'admin-toolbar--stacked': isMobile }">
|
||||
<a-input-search
|
||||
v-model:value="searchText"
|
||||
placeholder="搜索标签名称"
|
||||
:style="isMobile ? { width: '100%' } : { width: '250px' }"
|
||||
@search="handleSearch"
|
||||
/>
|
||||
<a-button v-if="!isMobile && hasPermission('tag:create')" type="primary" @click="showAddModal">
|
||||
<template #icon>
|
||||
<PlusOutlined />
|
||||
</template>
|
||||
新增标签
|
||||
</a-button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<a-table
|
||||
v-if="!isMobile"
|
||||
:columns="columns"
|
||||
:data-source="tagList"
|
||||
:loading="loading"
|
||||
:pagination="pagination"
|
||||
@change="handleTableChange"
|
||||
row-key="id"
|
||||
:scroll="{ x: 'max-content' }"
|
||||
>
|
||||
<template #bodyCell="{ column, record }">
|
||||
<template v-if="column.key === 'color'">
|
||||
<span
|
||||
class="tag-preview"
|
||||
:style="{
|
||||
backgroundColor: record.bgColor,
|
||||
color: record.textColor,
|
||||
borderColor: record.borderColor
|
||||
}"
|
||||
>
|
||||
{{ record.tagName }}
|
||||
</span>
|
||||
</template>
|
||||
<template v-else-if="column.key === 'shop'">
|
||||
<span>{{ record.shopName || getShopName(record.shopId) }}</span>
|
||||
</template>
|
||||
<template v-else-if="column.key === 'actions'">
|
||||
<a-space>
|
||||
<a-button v-if="hasPermission('tag:view')" type="link" size="small" @click="showViewModal(record)">
|
||||
查看
|
||||
</a-button>
|
||||
<a-button v-if="hasPermission('tag:edit')" type="link" size="small" @click="showEditModal(record)">
|
||||
编辑
|
||||
</a-button>
|
||||
<a-button v-if="hasPermission('tag:delete')" type="link" size="small" danger @click="handleDelete(record)">
|
||||
删除
|
||||
</a-button>
|
||||
</a-space>
|
||||
</template>
|
||||
</template>
|
||||
</a-table>
|
||||
|
||||
<AdminMobileCardList v-else :items="tagList" empty-description="暂无标签数据">
|
||||
<template #item="{ item }">
|
||||
<article class="admin-mobile-card">
|
||||
<div class="admin-mobile-card__head">
|
||||
<div class="admin-mobile-card__body">
|
||||
<div class="admin-mobile-card__title">{{ item.tagName }}</div>
|
||||
<div class="admin-mobile-card__subtitle">{{ item.shopName || getShopName(item.shopId) || '未关联店铺' }}</div>
|
||||
</div>
|
||||
<span
|
||||
class="tag-preview"
|
||||
:style="{ backgroundColor: item.bgColor, color: item.textColor, borderColor: item.borderColor }"
|
||||
>
|
||||
{{ item.tagName }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="admin-mobile-card__rows">
|
||||
<div class="admin-mobile-card__row">
|
||||
<span>创建时间</span>
|
||||
<strong>{{ item.createTime || '--' }}</strong>
|
||||
</div>
|
||||
</div>
|
||||
<div class="admin-mobile-card__actions">
|
||||
<a-button v-if="hasPermission('tag:view')" size="small" @click="showViewModal(item)">查看</a-button>
|
||||
<a-button v-if="hasPermission('tag:edit')" size="small" @click="showEditModal(item)">编辑</a-button>
|
||||
<a-button v-if="hasPermission('tag:delete')" size="small" danger @click="handleDelete(item)">删除</a-button>
|
||||
</div>
|
||||
</article>
|
||||
</template>
|
||||
</AdminMobileCardList>
|
||||
</a-card>
|
||||
|
||||
<AdminResponsiveModal
|
||||
v-model:open="modalVisible"
|
||||
:title="isEdit ? '编辑标签' : '新增标签'"
|
||||
@ok="handleModalOk"
|
||||
@cancel="handleModalCancel"
|
||||
:confirmLoading="modalLoading"
|
||||
:desktop-width="600"
|
||||
>
|
||||
<DraftActions
|
||||
:saved-at="draftSavedAt"
|
||||
@save="handleSaveDraft"
|
||||
@clear="handleClearDraft"
|
||||
/>
|
||||
<a-form
|
||||
ref="formRef"
|
||||
:model="formState"
|
||||
:rules="formRules"
|
||||
:label-col="{ span: 6 }"
|
||||
:wrapper-col="{ span: 16 }"
|
||||
>
|
||||
<a-form-item label="标签名称" name="tagName">
|
||||
<a-input v-model:value="formState.tagName" placeholder="请输入标签名称" />
|
||||
</a-form-item>
|
||||
<a-form-item label="所属店铺" name="shopId">
|
||||
<a-select
|
||||
v-model:value="formState.shopId"
|
||||
placeholder="请选择所属店铺"
|
||||
style="width: 100%"
|
||||
:loading="loadingShops"
|
||||
:disabled="getCurrentUserInfo()?.type === 2"
|
||||
>
|
||||
<a-select-option
|
||||
v-if="shops.length === 0"
|
||||
disabled
|
||||
value=""
|
||||
>
|
||||
暂无店铺数据
|
||||
</a-select-option>
|
||||
<a-select-option
|
||||
v-for="shop in shops"
|
||||
:key="shop.id"
|
||||
:value="shop.id"
|
||||
>
|
||||
{{ shop.shopName }}
|
||||
</a-select-option>
|
||||
</a-select>
|
||||
</a-form-item>
|
||||
<a-form-item label="文字颜色" name="textColor">
|
||||
<el-color-picker v-model="formState.textColor" />
|
||||
</a-form-item>
|
||||
<a-form-item label="背景颜色" name="bgColor">
|
||||
<el-color-picker v-model="formState.bgColor" />
|
||||
</a-form-item>
|
||||
<a-form-item label="边框颜色" name="borderColor">
|
||||
<el-color-picker v-model="formState.borderColor" />
|
||||
</a-form-item>
|
||||
<a-form-item label="场景分组" name="sceneGroup">
|
||||
<a-input v-model:value="formState.sceneGroup" placeholder="如:风格、场合、季节" />
|
||||
</a-form-item>
|
||||
<a-form-item label="前台名称" name="displayName">
|
||||
<a-input v-model:value="formState.displayName" placeholder="留空则使用标签名称" />
|
||||
</a-form-item>
|
||||
<a-form-item label="前台排序" name="sortOrder">
|
||||
<a-input-number v-model:value="formState.sortOrder" :min="0" style="width: 100%" />
|
||||
</a-form-item>
|
||||
<a-form-item label="前台展示" name="frontVisible">
|
||||
<a-switch v-model:checked="formState.frontVisible" :checked-value="1" :un-checked-value="0" />
|
||||
</a-form-item>
|
||||
<a-form-item label="预览">
|
||||
<span
|
||||
class="tag-preview"
|
||||
:style="{
|
||||
backgroundColor: formState.bgColor,
|
||||
color: formState.textColor,
|
||||
borderColor: formState.borderColor
|
||||
}"
|
||||
>
|
||||
{{ formState.tagName }}
|
||||
</span>
|
||||
</a-form-item>
|
||||
</a-form>
|
||||
</AdminResponsiveModal>
|
||||
|
||||
<!-- 查看标签详情模态框 -->
|
||||
<AdminResponsiveModal
|
||||
v-model:open="viewModalVisible"
|
||||
title="查看标签详情"
|
||||
:footer="null"
|
||||
@cancel="handleViewModalCancel"
|
||||
:desktop-width="600"
|
||||
>
|
||||
<a-form
|
||||
:model="viewFormState"
|
||||
:label-col="{ span: 6 }"
|
||||
:wrapper-col="{ span: 16 }"
|
||||
>
|
||||
<a-form-item label="标签名称">
|
||||
<a-input v-model:value="viewFormState.tagName" :disabled="true" />
|
||||
</a-form-item>
|
||||
<a-form-item label="所属店铺">
|
||||
<a-select v-model:value="viewFormState.shopId" :disabled="true">
|
||||
<a-select-option
|
||||
v-for="shop in shops"
|
||||
:key="shop.id"
|
||||
:value="shop.id"
|
||||
>
|
||||
{{ shop.shopName }}
|
||||
</a-select-option>
|
||||
</a-select>
|
||||
</a-form-item>
|
||||
<a-form-item label="文字颜色">
|
||||
<el-color-picker v-model="viewFormState.textColor" disabled />
|
||||
</a-form-item>
|
||||
<a-form-item label="背景颜色">
|
||||
<el-color-picker v-model="viewFormState.bgColor" disabled />
|
||||
</a-form-item>
|
||||
<a-form-item label="边框颜色">
|
||||
<el-color-picker v-model="viewFormState.borderColor" disabled />
|
||||
</a-form-item>
|
||||
<a-form-item label="场景分组">
|
||||
<a-input v-model:value="viewFormState.sceneGroup" :disabled="true" />
|
||||
</a-form-item>
|
||||
<a-form-item label="前台名称">
|
||||
<a-input v-model:value="viewFormState.displayName" :disabled="true" />
|
||||
</a-form-item>
|
||||
<a-form-item label="前台排序">
|
||||
<a-input-number v-model:value="viewFormState.sortOrder" :disabled="true" style="width: 100%" />
|
||||
</a-form-item>
|
||||
<a-form-item label="前台展示">
|
||||
<a-switch v-model:checked="viewFormState.frontVisible" :checked-value="1" :un-checked-value="0" disabled />
|
||||
</a-form-item>
|
||||
<a-form-item label="预览">
|
||||
<span
|
||||
class="tag-preview"
|
||||
:style="{
|
||||
backgroundColor: viewFormState.bgColor,
|
||||
color: viewFormState.textColor,
|
||||
borderColor: viewFormState.borderColor
|
||||
}"
|
||||
>
|
||||
{{ viewFormState.tagName }}
|
||||
</span>
|
||||
</a-form-item>
|
||||
</a-form>
|
||||
</AdminResponsiveModal>
|
||||
|
||||
<AdminMobileFab
|
||||
:visible="isMobile && hasPermission('tag:create') && !modalVisible && !viewModalVisible"
|
||||
label="新增标签"
|
||||
@click="showAddModal"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* TagsView page script.
|
||||
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
|
||||
*/
|
||||
import { ref, reactive, onMounted } from 'vue'
|
||||
import { message, Modal } from 'ant-design-vue'
|
||||
import type { FormInstance } from 'ant-design-vue'
|
||||
import { PlusOutlined } from '@ant-design/icons-vue'
|
||||
import DraftActions from '@/components/DraftActions.vue'
|
||||
/**
|
||||
* Purpose: Shop supports TagsView.vue by holding or executing the shop page or API role.
|
||||
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
import { adminTagApi, adminShopApi, type Shop } from '@/api/admin'
|
||||
import { buildDraftStorageKey, clearDraftRecord, loadDraftRecord, saveDraftRecord } from '@/utils/form-draft'
|
||||
import type { IdType } from '@/utils/id'
|
||||
import { usePermission } from '@/utils/permission'
|
||||
import { runWithGlobalLoading } from '@/utils/action-loading'
|
||||
import { useAdminViewport } from '@/composables/useAdminViewport'
|
||||
import AdminMobileCardList from '@/components/admin/AdminMobileCardList.vue'
|
||||
import AdminMobileFab from '@/components/admin/AdminMobileFab.vue'
|
||||
import AdminResponsiveModal from '@/components/admin/AdminResponsiveModal.vue'
|
||||
|
||||
const { hasPermission, loadUserPermissions } = usePermission()
|
||||
const { isMobile } = useAdminViewport()
|
||||
|
||||
/** getCurrentUserInfo is a local helper used by this page script. */
|
||||
const getCurrentUserInfo = () => {
|
||||
try {
|
||||
const userInfoStr = localStorage.getItem('adminUserInfo')
|
||||
if (userInfoStr) {
|
||||
const userInfo = JSON.parse(userInfoStr)
|
||||
return userInfo
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取当前用户信息失败', error)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** loading is a reactive state variable used by the template and event handlers. */
|
||||
const loading = ref(false)
|
||||
/** modalVisible is a reactive state variable used by the template and event handlers. */
|
||||
const modalVisible = ref(false)
|
||||
/** viewModalVisible is a reactive state variable used by the template and event handlers. */
|
||||
const viewModalVisible = ref(false)
|
||||
/** modalLoading is a reactive state variable used by the template and event handlers. */
|
||||
const modalLoading = ref(false)
|
||||
/** isEdit is a reactive state variable used by the template and event handlers. */
|
||||
const isEdit = ref(false)
|
||||
/** searchText is a reactive state variable used by the template and event handlers. */
|
||||
const searchText = ref('')
|
||||
/**
|
||||
* Purpose: formRef supports TagsView.vue by holding or executing the form ref page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const formRef = ref<FormInstance>()
|
||||
/**
|
||||
* Purpose: currentTag supports TagsView.vue by holding or executing the current tag page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const currentTag = ref<any>(null)
|
||||
/**
|
||||
* Purpose: draftSavedAt supports TagsView.vue by holding or executing the draft saved at page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const draftSavedAt = ref<number | null>(null)
|
||||
|
||||
// 查看标签相关状态
|
||||
const viewFormState = reactive({
|
||||
tagName: '',
|
||||
shopId: undefined as number | undefined,
|
||||
textColor: '#333333',
|
||||
bgColor: '#FFFFFF',
|
||||
borderColor: '#E5E5E5',
|
||||
sceneGroup: '',
|
||||
displayName: '',
|
||||
sortOrder: 100,
|
||||
frontVisible: 1
|
||||
})
|
||||
|
||||
/**
|
||||
* Purpose: tagList supports TagsView.vue by holding or executing the tag list page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const tagList = ref<any[]>([])
|
||||
/**
|
||||
* Purpose: shops supports TagsView.vue by holding or executing the shops page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const shops = ref<Shop[]>([])
|
||||
/** loadingShops is a reactive state variable used by the template and event handlers. */
|
||||
const loadingShops = ref(false)
|
||||
|
||||
/**
|
||||
* Purpose: pagination supports TagsView.vue by holding or executing the pagination page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const pagination = reactive({
|
||||
current: 1,
|
||||
pageSize: 10,
|
||||
total: 0,
|
||||
showSizeChanger: true,
|
||||
showQuickJumper: true,
|
||||
showTotal: (total: number) => `共 ${total} 条`
|
||||
})
|
||||
|
||||
/**
|
||||
* Purpose: formState supports TagsView.vue by holding or executing the form state page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const formState = reactive({
|
||||
tagName: '',
|
||||
shopId: undefined as number | undefined,
|
||||
textColor: '#333333',
|
||||
bgColor: '#FFFFFF',
|
||||
borderColor: '#E5E5E5',
|
||||
sceneGroup: '',
|
||||
displayName: '',
|
||||
sortOrder: 100,
|
||||
frontVisible: 1
|
||||
})
|
||||
|
||||
/** getDraftKey is a local helper used by this page script. */
|
||||
const getDraftKey = () => buildDraftStorageKey('admin-tags', isEdit.value ? 'edit' : 'create', currentTag.value?.id ?? 'new')
|
||||
|
||||
/** buildDraftPayload is a local helper used by this page script. */
|
||||
const buildDraftPayload = () => ({
|
||||
tagName: formState.tagName,
|
||||
shopId: formState.shopId,
|
||||
textColor: formState.textColor,
|
||||
bgColor: formState.bgColor,
|
||||
borderColor: formState.borderColor,
|
||||
sceneGroup: formState.sceneGroup,
|
||||
displayName: formState.displayName,
|
||||
sortOrder: formState.sortOrder,
|
||||
frontVisible: formState.frontVisible
|
||||
})
|
||||
|
||||
/** restoreDraft is a local helper used by this page script. */
|
||||
const restoreDraft = () => {
|
||||
const draft = loadDraftRecord<ReturnType<typeof buildDraftPayload>>(getDraftKey())
|
||||
if (!draft) {
|
||||
draftSavedAt.value = null
|
||||
return
|
||||
}
|
||||
Object.assign(formState, draft.payload)
|
||||
draftSavedAt.value = draft.savedAt
|
||||
message.success('已恢复暂存内容')
|
||||
}
|
||||
|
||||
/** handleSaveDraft is a local helper used by this page script. */
|
||||
const handleSaveDraft = () => {
|
||||
const draft = saveDraftRecord(getDraftKey(), buildDraftPayload())
|
||||
draftSavedAt.value = draft.savedAt
|
||||
message.success('已暂存到本地')
|
||||
}
|
||||
|
||||
/** handleClearDraft is a local helper used by this page script. */
|
||||
const handleClearDraft = (showMessage = true) => {
|
||||
clearDraftRecord(getDraftKey())
|
||||
draftSavedAt.value = null
|
||||
if (showMessage) {
|
||||
message.success('已清除暂存')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: formRules supports TagsView.vue by holding or executing the form rules page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const formRules = {
|
||||
tagName: [{ required: true, message: '请输入标签名称', trigger: 'blur' }],
|
||||
shopId: [{ required: true, message: '请选择所属店铺', trigger: 'change' }]
|
||||
} as any
|
||||
|
||||
/**
|
||||
* Purpose: columns supports TagsView.vue by holding or executing the columns page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const columns = [
|
||||
{ title: '标签名称', dataIndex: 'tagName', key: 'tagName' },
|
||||
{ title: '所属店铺', key: 'shop', width: 150 },
|
||||
{ title: '预览', key: 'color', width: 150 },
|
||||
{ title: '文字颜色', dataIndex: 'textColor', key: 'textColor', width: 120 },
|
||||
{ title: '背景颜色', dataIndex: 'bgColor', key: 'bgColor', width: 120 },
|
||||
{ title: '边框颜色', dataIndex: 'borderColor', key: 'borderColor', width: 120 },
|
||||
{ title: '场景分组', dataIndex: 'sceneGroup', key: 'sceneGroup', width: 120 },
|
||||
{ title: '前台名称', dataIndex: 'displayName', key: 'displayName', width: 120 },
|
||||
{ title: '创建时间', dataIndex: 'createTime', key: 'createTime' },
|
||||
{ title: '操作', key: 'actions', width: 150, fixed: 'right' as const }
|
||||
]
|
||||
|
||||
/** fetchTags is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
||||
const fetchTags = async () => {
|
||||
loading.value = true
|
||||
try {
|
||||
const currentUser = getCurrentUserInfo()
|
||||
const shopId = (currentUser && currentUser.shopId) ? currentUser.shopId : undefined
|
||||
let tags
|
||||
if (shopId) {
|
||||
tags = await adminTagApi.listTagsByShopId(shopId) as unknown as any[]
|
||||
} else {
|
||||
tags = await adminTagApi.listAllTags() as unknown as any[]
|
||||
}
|
||||
tagList.value = tags || []
|
||||
pagination.total = tagList.value.length
|
||||
} catch (error) {
|
||||
console.error('获取标签列表失败:', error)
|
||||
message.error('获取标签列表失败')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** fetchShops is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
||||
const fetchShops = async () => {
|
||||
loadingShops.value = true
|
||||
try {
|
||||
const res = await adminShopApi.listAllShops() as unknown as any[]
|
||||
shops.value = res || []
|
||||
} catch (error) {
|
||||
console.error('获取店铺列表失败:', error)
|
||||
} finally {
|
||||
loadingShops.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** normalizeShopIdValue is a local helper used by this page script. */
|
||||
const normalizeShopIdValue = (value: string | number | undefined | null) => {
|
||||
if (value === undefined || value === null || value === '') {
|
||||
return ''
|
||||
}
|
||||
return String(value)
|
||||
}
|
||||
|
||||
/** getShopName is a local helper used by this page script. */
|
||||
const getShopName = (shopId: IdType | undefined) => {
|
||||
const normalizedShopId = normalizeShopIdValue(shopId)
|
||||
const shop = shops.value.find(s => normalizeShopIdValue(s.id) === normalizedShopId)
|
||||
return shop ? shop.shopName : '未知店铺'
|
||||
}
|
||||
|
||||
/** handleSearch is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
||||
const handleSearch = async () => {
|
||||
pagination.current = 1
|
||||
await runWithGlobalLoading(() => fetchTags())
|
||||
}
|
||||
|
||||
/** handleTableChange is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
||||
const handleTableChange = async (pag: any) => {
|
||||
pagination.current = pag.current
|
||||
pagination.pageSize = pag.pageSize
|
||||
await runWithGlobalLoading(() => fetchTags())
|
||||
}
|
||||
|
||||
/** showAddModal is a local helper used by this page script. */
|
||||
const showAddModal = () => {
|
||||
isEdit.value = false
|
||||
currentTag.value = null
|
||||
const currentUser = getCurrentUserInfo()
|
||||
const shopId = (currentUser && currentUser.shopId) ? currentUser.shopId : undefined
|
||||
Object.assign(formState, {
|
||||
tagName: '',
|
||||
shopId: shopId,
|
||||
textColor: '#333333',
|
||||
bgColor: '#FFFFFF',
|
||||
borderColor: '#E5E5E5',
|
||||
sceneGroup: '',
|
||||
displayName: '',
|
||||
sortOrder: 100,
|
||||
frontVisible: 1
|
||||
})
|
||||
restoreDraft()
|
||||
modalVisible.value = true
|
||||
}
|
||||
|
||||
/** showEditModal is a local helper used by this page script. */
|
||||
const showEditModal = (record: any) => {
|
||||
isEdit.value = true
|
||||
currentTag.value = record
|
||||
Object.assign(formState, {
|
||||
tagName: record.tagName,
|
||||
shopId: record.shopId,
|
||||
textColor: record.textColor,
|
||||
bgColor: record.bgColor,
|
||||
borderColor: record.borderColor,
|
||||
sceneGroup: record.sceneGroup || '',
|
||||
displayName: record.displayName || '',
|
||||
sortOrder: record.sortOrder ?? 100,
|
||||
frontVisible: record.frontVisible ?? 1
|
||||
})
|
||||
restoreDraft()
|
||||
modalVisible.value = true
|
||||
}
|
||||
|
||||
/** showViewModal is a local helper used by this page script. */
|
||||
const showViewModal = (record: any) => {
|
||||
Object.assign(viewFormState, {
|
||||
tagName: record.tagName,
|
||||
shopId: record.shopId,
|
||||
textColor: record.textColor,
|
||||
bgColor: record.bgColor,
|
||||
borderColor: record.borderColor,
|
||||
sceneGroup: record.sceneGroup || '',
|
||||
displayName: record.displayName || '',
|
||||
sortOrder: record.sortOrder ?? 100,
|
||||
frontVisible: record.frontVisible ?? 1
|
||||
})
|
||||
viewModalVisible.value = true
|
||||
}
|
||||
|
||||
/** handleViewModalCancel is a local helper used by this page script. */
|
||||
const handleViewModalCancel = () => {
|
||||
viewModalVisible.value = false
|
||||
}
|
||||
|
||||
/** handleModalOk is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
||||
const handleModalOk = async () => {
|
||||
try {
|
||||
await formRef.value?.validate()
|
||||
modalLoading.value = true
|
||||
|
||||
await runWithGlobalLoading(async () => {
|
||||
const requestData = {
|
||||
tagName: formState.tagName,
|
||||
shopId: formState.shopId,
|
||||
textColor: formState.textColor,
|
||||
bgColor: formState.bgColor,
|
||||
borderColor: formState.borderColor,
|
||||
sceneGroup: formState.sceneGroup,
|
||||
displayName: formState.displayName,
|
||||
sortOrder: formState.sortOrder,
|
||||
frontVisible: formState.frontVisible
|
||||
}
|
||||
|
||||
if (isEdit.value && currentTag.value) {
|
||||
await adminTagApi.updateTag(currentTag.value.id, requestData)
|
||||
message.success('更新成功')
|
||||
} else {
|
||||
await adminTagApi.createTag(requestData)
|
||||
message.success('创建成功')
|
||||
}
|
||||
|
||||
handleClearDraft(false)
|
||||
modalVisible.value = false
|
||||
await fetchTags()
|
||||
})
|
||||
} catch (error: any) {
|
||||
console.error('Error:', error)
|
||||
message.error(error?.message || (isEdit.value ? '更新失败' : '创建失败'))
|
||||
} finally {
|
||||
modalLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** handleModalCancel is a local helper used by this page script. */
|
||||
const handleModalCancel = () => {
|
||||
modalVisible.value = false
|
||||
formRef.value?.resetFields()
|
||||
}
|
||||
|
||||
/** handleDelete is a local helper used by this page script. */
|
||||
const handleDelete = (record: any) => {
|
||||
Modal.confirm({
|
||||
title: '确认删除',
|
||||
content: `确定要删除标签 ${record.tagName} 吗?`,
|
||||
onOk: async () => {
|
||||
try {
|
||||
await runWithGlobalLoading(async () => {
|
||||
await adminTagApi.deleteTag(record.id)
|
||||
message.success('删除成功')
|
||||
await fetchTags()
|
||||
})
|
||||
} catch (error) {
|
||||
message.error('删除失败')
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await loadUserPermissions()
|
||||
await fetchShops()
|
||||
await fetchTags()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.tags {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.tag-preview {
|
||||
display: inline-block;
|
||||
padding: 4px 12px;
|
||||
border-radius: 4px;
|
||||
border: 1px solid;
|
||||
font-size: 14px;
|
||||
}
|
||||
</style>
|
||||
-73
@@ -1,73 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.gateway.filter;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.gateway.config.GatewayConfig;
|
||||
import com.xiaowang.fingertipdesigner.gateway.filter.AuthGlobalFilter.AuthWhitelist;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.util.AntPathMatcher;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class AuthGlobalFilterWhitelistTest {
|
||||
|
||||
private final AntPathMatcher pathMatcher = new AntPathMatcher();
|
||||
|
||||
@Test
|
||||
void effectiveWhitelistCoversPublicCommentListAndRejectsOrderApi() {
|
||||
GatewayConfig config = new GatewayConfig();
|
||||
config.setWhitelist(List.of("/api/user/login"));
|
||||
|
||||
List<String> patterns = AuthWhitelist.effectivePatterns(config);
|
||||
|
||||
assertThat(matches(patterns, "/api/comment/list/product/1")).isTrue();
|
||||
assertThat(matches(patterns, "/api/order/list")).isFalse();
|
||||
assertThat(matches(patterns, "/api/admin/user/list")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultWhitelistIncludesOnlyExpectedPublicBusinessAreas() {
|
||||
assertThat(AuthWhitelist.defaultPatterns())
|
||||
.contains(
|
||||
"/api/user/login",
|
||||
"/api/comment/list/product/**",
|
||||
"/api/admin/auth/login",
|
||||
"/admin/auth/login",
|
||||
"/api/nail-artist/profile/**",
|
||||
"/api/nail-artist/*/availability",
|
||||
"/api/nail-artist/*/reviews",
|
||||
"/api/shop/list"
|
||||
)
|
||||
.doesNotContain("/api/order/**", "/api/shop/delete/**", "/api/permission/**");
|
||||
}
|
||||
|
||||
@Test
|
||||
void directAdminLoginCompatibilityPathIsWhitelisted() {
|
||||
assertThat(matches(AuthWhitelist.defaultPatterns(), "/admin/auth/login")).isTrue();
|
||||
assertThat(matches(AuthWhitelist.defaultPatterns(), "/admin/auth/login-shops/1")).isTrue();
|
||||
assertThat(matches(AuthWhitelist.defaultPatterns(), "/admin/auth/refresh")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void applicationRoutesDirectAdminAuthCompatibilityPath() throws Exception {
|
||||
String yaml = new String(new ClassPathResource("application.yaml").getInputStream().readAllBytes(), StandardCharsets.UTF_8);
|
||||
|
||||
assertThat(yaml).contains("Path=/admin/auth/**");
|
||||
}
|
||||
|
||||
@Test
|
||||
void applicationRoutesManagerApiThroughAdminRoute() throws Exception {
|
||||
String yaml = new String(new ClassPathResource("application.yaml").getInputStream().readAllBytes(), StandardCharsets.UTF_8);
|
||||
|
||||
assertThat(yaml)
|
||||
.contains("Path=/api/admin/**")
|
||||
.contains("RewritePath=/api/admin/(?<remaining>.*), /admin/${remaining}");
|
||||
assertThat(matches(AuthWhitelist.defaultPatterns(), "/api/admin/manager/planning/calendar")).isFalse();
|
||||
}
|
||||
|
||||
private boolean matches(List<String> patterns, String path) {
|
||||
return patterns.stream().anyMatch(pattern -> pathMatcher.match(pattern, path));
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
/**
|
||||
* Purpose: request sends authenticated admin mini-program calls through the shared request wrapper.
|
||||
* Usage: keep after-sale endpoints aligned with /admin/after-sale on the backend.
|
||||
*/
|
||||
const request = require('../utils/request')
|
||||
|
||||
module.exports = {
|
||||
listAfterSales(params) {
|
||||
return request({
|
||||
url: '/after-sale/list',
|
||||
params
|
||||
})
|
||||
},
|
||||
|
||||
approveAfterSale(id, data) {
|
||||
return request({
|
||||
url: `/after-sale/${id}/approve`,
|
||||
method: 'PUT',
|
||||
data: data || {}
|
||||
})
|
||||
},
|
||||
|
||||
rejectAfterSale(id, data) {
|
||||
return request({
|
||||
url: `/after-sale/${id}/reject`,
|
||||
method: 'PUT',
|
||||
data: data || {}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
/**
|
||||
* Purpose: request sends authenticated admin mini-program calls through the shared request wrapper.
|
||||
* Usage: keep schedule endpoints aligned with /admin/artist-schedule on the backend.
|
||||
*/
|
||||
const request = require('../utils/request')
|
||||
|
||||
module.exports = {
|
||||
listSchedules(params) {
|
||||
return request({
|
||||
url: '/artist-schedule/list',
|
||||
params
|
||||
})
|
||||
},
|
||||
|
||||
saveSchedule(data) {
|
||||
return request({
|
||||
url: '/artist-schedule/save',
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
/**
|
||||
* Purpose: request supports auth.js by holding or executing the request page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const request = require('../utils/request')
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* Purpose: login supports auth.js by holding or executing the login page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
login(data) {
|
||||
return request({
|
||||
url: '/auth/login',
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: getLoginShops supports auth.js by holding or executing the get login shops page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
getLoginShops(account) {
|
||||
return request({
|
||||
url: `/auth/login-shops/${encodeURIComponent(account)}`
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: switchShop supports auth.js by holding or executing the switch shop page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
switchShop(shopId) {
|
||||
return request({
|
||||
url: '/auth/switch-shop',
|
||||
method: 'POST',
|
||||
data: {
|
||||
shopId: shopId || undefined
|
||||
}
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: refreshToken supports auth.js by holding or executing the refresh token page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
refreshToken(refreshToken) {
|
||||
return request({
|
||||
url: '/auth/refresh',
|
||||
method: 'POST',
|
||||
data: {
|
||||
refreshToken
|
||||
}
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: logout supports auth.js by holding or executing the logout page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
logout() {
|
||||
return request({
|
||||
url: '/auth/logout',
|
||||
method: 'POST'
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
/**
|
||||
* Purpose: request sends authenticated admin mini-program calls through the shared request wrapper.
|
||||
* Usage: keep campaign endpoints aligned with /admin/campaign on the backend.
|
||||
*/
|
||||
const request = require('../utils/request')
|
||||
|
||||
module.exports = {
|
||||
listCampaigns(params) {
|
||||
return request({
|
||||
url: '/campaign/list',
|
||||
params
|
||||
})
|
||||
},
|
||||
|
||||
saveCampaign(data) {
|
||||
return request({
|
||||
url: '/campaign/save',
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
/**
|
||||
* Purpose: request supports comment.js by holding or executing the request page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const request = require('../utils/request')
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* Purpose: listComments supports comment.js by holding or executing the list comments page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
listComments(params) {
|
||||
return request({
|
||||
url: '/comment/list',
|
||||
params
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: deleteComment supports comment.js by holding or executing the delete comment page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
deleteComment(id) {
|
||||
return request({
|
||||
url: `/comment/delete/${id}`,
|
||||
method: 'DELETE'
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
/**
|
||||
* Purpose: request supports coupon.js by holding or executing the request page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const request = require('../utils/request')
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* Purpose: listCoupons supports coupon.js by holding or executing the list coupons page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
listCoupons(params) {
|
||||
return request({
|
||||
url: '/coupon/list',
|
||||
params
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: listAllCoupons supports coupon.js by holding or executing the list all coupons page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
listAllCoupons(shopId) {
|
||||
return request({
|
||||
url: '/coupon/list/all',
|
||||
params: shopId ? { shopId } : undefined
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: getCouponDetail supports coupon.js by holding or executing the get coupon detail page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
getCouponDetail(id) {
|
||||
return request({
|
||||
url: `/coupon/detail/${id}`
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: createCoupon supports coupon.js by holding or executing the create coupon page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
createCoupon(data) {
|
||||
return request({
|
||||
url: '/coupon/create',
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: updateCoupon supports coupon.js by holding or executing the update coupon page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
updateCoupon(id, data) {
|
||||
return request({
|
||||
url: `/coupon/update/${id}`,
|
||||
method: 'PUT',
|
||||
data
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: deleteCoupon supports coupon.js by holding or executing the delete coupon page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
deleteCoupon(id) {
|
||||
return request({
|
||||
url: `/coupon/delete/${id}`,
|
||||
method: 'DELETE'
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: assignCoupon supports coupon.js by holding or executing the assign coupon page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
assignCoupon(data) {
|
||||
return request({
|
||||
url: '/coupon/assign',
|
||||
method: 'POST',
|
||||
params: data,
|
||||
data: {}
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: distributeCoupon supports coupon.js by holding or executing the distribute coupon page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
distributeCoupon(data) {
|
||||
return request({
|
||||
url: '/coupon/distribute',
|
||||
method: 'POST',
|
||||
params: data,
|
||||
data: {}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
/**
|
||||
* Purpose: request supports dashboard.js by holding or executing the request page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const request = require('../utils/request')
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* Purpose: getStats supports dashboard.js by holding or executing the get stats page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
getStats() {
|
||||
return request({
|
||||
url: '/dashboard/stats'
|
||||
})
|
||||
},
|
||||
|
||||
getAnalytics() {
|
||||
return request({
|
||||
url: '/dashboard/analytics'
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,148 +0,0 @@
|
||||
/**
|
||||
* Purpose: request supports file.js by holding or executing the request page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const request = require('../utils/request')
|
||||
/**
|
||||
* Purpose: actionGuard supports file.js by holding or executing the action guard page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const actionGuard = require('../utils/action-guard')
|
||||
const { ADMIN_API_BASE_URL, REQUEST_TIMEOUT } = require('../utils/config')
|
||||
|
||||
/**
|
||||
* Purpose: normalizeUploadResponse supports file.js by holding or executing the normalize upload response page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function normalizeUploadResponse(response) {
|
||||
if (!response) {
|
||||
throw new Error('上传失败')
|
||||
}
|
||||
|
||||
if (response.statusCode === 401) {
|
||||
throw new Error('登录已过期,请重新登录')
|
||||
}
|
||||
|
||||
if (response.statusCode >= 400) {
|
||||
throw new Error('上传失败')
|
||||
}
|
||||
|
||||
let payload = response.data
|
||||
if (typeof payload === 'string') {
|
||||
try {
|
||||
payload = JSON.parse(payload)
|
||||
} catch (error) {}
|
||||
}
|
||||
|
||||
if (payload && typeof payload === 'object' && Object.prototype.hasOwnProperty.call(payload, 'code')) {
|
||||
if (payload.code === 200) {
|
||||
return payload.data
|
||||
}
|
||||
throw new Error(payload.message || '上传失败')
|
||||
}
|
||||
|
||||
return payload
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* Purpose: initChunkUpload supports file.js by holding or executing the init chunk upload page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
initChunkUpload(data) {
|
||||
return request({
|
||||
url: '/object-storage-file/upload/init',
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: uploadChunkFile supports file.js by holding or executing the upload chunk file page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
uploadChunkFile(options) {
|
||||
const signedHeaders = request.buildSignatureHeaders({
|
||||
url: '/object-storage-file/upload/chunk',
|
||||
method: 'POST',
|
||||
formData: {
|
||||
uploadId: String(options.uploadId),
|
||||
chunkIndex: String(options.chunkIndex),
|
||||
totalChunks: String(options.totalChunks)
|
||||
}
|
||||
})
|
||||
|
||||
return actionGuard.run(
|
||||
null,
|
||||
`POST:/object-storage-file/upload/chunk:${String(options.uploadId)}:${String(options.chunkIndex)}`,
|
||||
() => new Promise((resolve, reject) => {
|
||||
const task = wx.uploadFile({
|
||||
url: `${ADMIN_API_BASE_URL}/object-storage-file/upload/chunk`,
|
||||
filePath: options.filePath,
|
||||
name: 'chunk',
|
||||
timeout: REQUEST_TIMEOUT,
|
||||
formData: {
|
||||
uploadId: String(options.uploadId),
|
||||
chunkIndex: String(options.chunkIndex),
|
||||
totalChunks: String(options.totalChunks)
|
||||
},
|
||||
header: signedHeaders,
|
||||
success: response => {
|
||||
try {
|
||||
resolve(normalizeUploadResponse(response))
|
||||
} catch (error) {
|
||||
reject(error)
|
||||
}
|
||||
},
|
||||
fail: error => {
|
||||
reject(new Error(error.errMsg || '上传分片失败'))
|
||||
}
|
||||
})
|
||||
|
||||
if (task && typeof task.onProgressUpdate === 'function' && typeof options.onProgress === 'function') {
|
||||
task.onProgressUpdate(progress => {
|
||||
options.onProgress(progress)
|
||||
})
|
||||
}
|
||||
}),
|
||||
{
|
||||
message: '上传处理中,请勿重复操作'
|
||||
}
|
||||
)
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: completeChunkUpload supports file.js by holding or executing the complete chunk upload page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
completeChunkUpload(uploadId) {
|
||||
return request({
|
||||
url: '/object-storage-file/upload/complete',
|
||||
method: 'POST',
|
||||
data: {
|
||||
uploadId
|
||||
}
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: cancelChunkUpload supports file.js by holding or executing the cancel chunk upload page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
cancelChunkUpload(uploadId) {
|
||||
return request({
|
||||
url: `/object-storage-file/upload/${uploadId}`,
|
||||
method: 'DELETE'
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: getSignedUrl supports file.js by holding or executing the get signed url page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
getSignedUrl(fileId) {
|
||||
return request({
|
||||
url: `/object-storage-file/get-signed-url/${fileId}`
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
/**
|
||||
* Purpose: request sends authenticated admin mini-program calls through the shared request wrapper.
|
||||
* Usage: keep inventory endpoints aligned with /admin/inventory on the backend.
|
||||
*/
|
||||
const request = require('../utils/request')
|
||||
|
||||
module.exports = {
|
||||
listItems(params) {
|
||||
return request({
|
||||
url: '/inventory/list',
|
||||
params
|
||||
})
|
||||
},
|
||||
|
||||
saveItem(data) {
|
||||
return request({
|
||||
url: '/inventory/save',
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
},
|
||||
|
||||
adjustStock(id, data) {
|
||||
return request({
|
||||
url: `/inventory/${id}/adjust`,
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
/**
|
||||
* Purpose: request supports nail-artist.js by holding or executing the request page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const request = require('../utils/request')
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* Purpose: listNailArtists supports nail-artist.js by holding or executing the list nail artists page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
listNailArtists() {
|
||||
return request({
|
||||
url: '/nail-artist/list'
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: getNailArtistInfo supports nail-artist.js by holding or executing the get nail artist info page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
getNailArtistInfo(userId) {
|
||||
return request({
|
||||
url: `/nail-artist/get/${userId}`
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: saveNailArtistInfo supports nail-artist.js by holding or executing the save nail artist info page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
saveNailArtistInfo(data) {
|
||||
return request({
|
||||
url: '/nail-artist/save',
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
/**
|
||||
* Purpose: request supports order.js by holding or executing the request page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const request = require('../utils/request')
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* Purpose: listOrders supports order.js by holding or executing the list orders page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
listOrders(params) {
|
||||
return request({
|
||||
url: '/order/list',
|
||||
params
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: getOrderDetail loads an authoritative admin-scoped order detail row.
|
||||
* Usage: call with the order id when opening the order detail page so direct page entry works.
|
||||
*/
|
||||
getOrderDetail(id) {
|
||||
return request({
|
||||
url: `/order/detail/${id}`
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: listOrderReviews supports order.js by holding or executing the list order reviews page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
listOrderReviews(orderId) {
|
||||
return request({
|
||||
url: `/order/${orderId}/reviews`
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: getArtistChangeOptions supports order.js by holding or executing the get artist change options page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
getArtistChangeOptions(orderId, orderItemId) {
|
||||
return request({
|
||||
url: `/order/${orderId}/artist-change/options`,
|
||||
params: {
|
||||
orderItemId
|
||||
}
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: requestArtistChange supports order.js by holding or executing the request artist change page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
requestArtistChange(data) {
|
||||
return request({
|
||||
url: '/order/artist-change/request',
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: listMyPendingArtistChangeRequests supports order.js by holding or executing the list my pending artist change requests page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
listMyPendingArtistChangeRequests() {
|
||||
return request({
|
||||
url: '/order/artist-change/my-pending'
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: updateOrderStatus supports order.js by holding or executing the update order status page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
updateOrderStatus(id, status) {
|
||||
return request({
|
||||
url: `/order/update-status/${id}`,
|
||||
method: 'PUT',
|
||||
params: {
|
||||
status
|
||||
},
|
||||
data: {}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
/**
|
||||
* Purpose: request sends authenticated admin mini-program calls through the shared request wrapper.
|
||||
* Usage: call manual payment operations only after UI permission checks; backend remains authoritative.
|
||||
*/
|
||||
const request = require('../utils/request')
|
||||
|
||||
module.exports = {
|
||||
manualConfirmOrder(orderId, remark) {
|
||||
return request({
|
||||
url: `/payment/order/${orderId}/manual-confirm`,
|
||||
method: 'POST',
|
||||
params: {
|
||||
remark
|
||||
},
|
||||
data: {}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
/**
|
||||
* Purpose: request supports permission.js by holding or executing the request page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const request = require('../utils/request')
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* Purpose: getCurrentUserPermissions supports permission.js by holding or executing the get current user permissions page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
getCurrentUserPermissions() {
|
||||
return request({
|
||||
url: '/permission/user/current'
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: getUserPermissions supports permission.js by holding or executing the get user permissions page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
getUserPermissions(userId) {
|
||||
return request({
|
||||
url: `/permission/user/${userId}`
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: getAssignablePermissionIds supports permission.js by holding or executing the get assignable permission ids page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
getAssignablePermissionIds(userId) {
|
||||
return request({
|
||||
url: `/permission/assignable/${userId}`
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: listAllPermissions supports permission.js by holding or executing the list all permissions page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
listAllPermissions() {
|
||||
return request({
|
||||
url: '/permission/list/all'
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: createPermission supports permission.js by holding or executing the create permission page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
createPermission(data) {
|
||||
return request({
|
||||
url: '/permission/create',
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: updatePermission supports permission.js by holding or executing the update permission page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
updatePermission(id, data) {
|
||||
return request({
|
||||
url: `/permission/update/${id}`,
|
||||
method: 'PUT',
|
||||
data
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: deletePermission supports permission.js by holding or executing the delete permission page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
deletePermission(id) {
|
||||
return request({
|
||||
url: `/permission/delete/${id}`,
|
||||
method: 'DELETE'
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: assignUserPermissions supports permission.js by holding or executing the assign user permissions page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
assignUserPermissions(userId, permissionIds) {
|
||||
return request({
|
||||
url: `/permission/assign/${userId}`,
|
||||
method: 'POST',
|
||||
data: {
|
||||
permissionIds
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
/**
|
||||
* Purpose: request supports product.js by holding or executing the request page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const request = require('../utils/request')
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* Purpose: listProducts supports product.js by holding or executing the list products page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
listProducts(params) {
|
||||
return request({
|
||||
url: '/product/list',
|
||||
params
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: listAllProducts supports product.js by holding or executing the list all products page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
listAllProducts() {
|
||||
return request({
|
||||
url: '/product/list/all'
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: createProduct supports product.js by holding or executing the create product page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
createProduct(data) {
|
||||
return request({
|
||||
url: '/product/create',
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: updateProduct supports product.js by holding or executing the update product page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
updateProduct(id, data) {
|
||||
return request({
|
||||
url: `/product/update/${id}`,
|
||||
method: 'PUT',
|
||||
data
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: deleteProduct supports product.js by holding or executing the delete product page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
deleteProduct(id) {
|
||||
return request({
|
||||
url: `/product/delete/${id}`,
|
||||
method: 'DELETE'
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
/**
|
||||
* Purpose: request sends signed admin mini-program requests to the backend audit API.
|
||||
* Usage: require this module from the audit page and call `listLogs` with filter params.
|
||||
*/
|
||||
const request = require('../utils/request')
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* Purpose: listLogs loads read-only security audit log rows for authorized administrators.
|
||||
* Usage: pass account, action, result, time range, page, and size filters, then render the returned page result.
|
||||
*/
|
||||
listLogs(params) {
|
||||
return request({
|
||||
url: '/security-audit/logs',
|
||||
params
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
/**
|
||||
* Purpose: request supports shop.js by holding or executing the request page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const request = require('../utils/request')
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* Purpose: listShops supports shop.js by holding or executing the list shops page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
listShops(params) {
|
||||
return request({
|
||||
url: '/shops/list',
|
||||
params
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: listAllShops supports shop.js by holding or executing the list all shops page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
listAllShops() {
|
||||
return request({
|
||||
url: '/shops/list/all'
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: getShop supports shop.js by holding or executing the get shop page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
getShop(id) {
|
||||
return request({
|
||||
url: `/shops/${id}`
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: createShop supports shop.js by holding or executing the create shop page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
createShop(data) {
|
||||
return request({
|
||||
url: '/shops/create',
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: updateShop supports shop.js by holding or executing the update shop page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
updateShop(id, data) {
|
||||
return request({
|
||||
url: `/shops/update/${id}`,
|
||||
method: 'PUT',
|
||||
data
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: updateShopStatus supports shop.js by holding or executing the update shop status page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
updateShopStatus(id, status) {
|
||||
return request({
|
||||
url: `/shops/status/${id}`,
|
||||
method: 'PUT',
|
||||
data: {
|
||||
status
|
||||
}
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: deleteShop supports shop.js by holding or executing the delete shop page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
deleteShop(id) {
|
||||
return request({
|
||||
url: `/shops/delete/${id}`,
|
||||
method: 'DELETE'
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
/**
|
||||
* Purpose: request sends signed admin mini-program calls to the backend system-message endpoints.
|
||||
* Usage: keep all system-message API wrappers in this module so pages do not build URLs by hand.
|
||||
*/
|
||||
const request = require('../utils/request')
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* Purpose: listMessages loads admin-visible system messages including popup and business navigation metadata.
|
||||
* Usage: call it from the system-message management page during initial load or refresh.
|
||||
*/
|
||||
listMessages() {
|
||||
return request({
|
||||
url: '/system-message/admin/list'
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: createMessage publishes a new system message to the selected target users.
|
||||
* Usage: pass validated form data with targetType, popupEnabled, and optional business fields.
|
||||
*/
|
||||
createMessage(data) {
|
||||
return request({
|
||||
url: '/system-message/admin/create',
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: revokeMessage withdraws a previously published message when the operator has delete permission.
|
||||
* Usage: call it with the message id after an explicit confirmation dialog.
|
||||
*/
|
||||
revokeMessage(id) {
|
||||
return request({
|
||||
url: `/system-message/admin/${id}/revoke`,
|
||||
method: 'PUT',
|
||||
data: {}
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: getTargetOptions loads shops and users that the current operator may target.
|
||||
* Usage: call it before showing the publish form so picker data is permission-scoped.
|
||||
*/
|
||||
getTargetOptions() {
|
||||
return request({
|
||||
url: '/system-message/admin/target-options'
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
/**
|
||||
* Purpose: request supports tag.js by holding or executing the request page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const request = require('../utils/request')
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* Purpose: listAllTags supports tag.js by holding or executing the list all tags page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
listAllTags() {
|
||||
return request({
|
||||
url: '/tag/list/all'
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: listTagsByShopId supports tag.js by holding or executing the list tags by shop id page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
listTagsByShopId(shopId) {
|
||||
return request({
|
||||
url: `/tag/list/by-shop/${shopId}`
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: getTagById supports tag.js by holding or executing the get tag by id page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
getTagById(id) {
|
||||
return request({
|
||||
url: `/tag/get/${id}`
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: createTag supports tag.js by holding or executing the create tag page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
createTag(data) {
|
||||
return request({
|
||||
url: '/tag/create',
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: updateTag supports tag.js by holding or executing the update tag page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
updateTag(id, data) {
|
||||
return request({
|
||||
url: `/tag/update/${id}`,
|
||||
method: 'PUT',
|
||||
data
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: deleteTag supports tag.js by holding or executing the delete tag page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
deleteTag(id) {
|
||||
return request({
|
||||
url: `/tag/delete/${id}`,
|
||||
method: 'DELETE'
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,176 +0,0 @@
|
||||
/**
|
||||
* Purpose: request supports user.js by holding or executing the request page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const request = require('../utils/request')
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* Purpose: listUsers supports user.js by holding or executing the list users page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
listUsers(params) {
|
||||
return request({
|
||||
url: '/user/list',
|
||||
params
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: listAllUsers supports user.js by holding or executing the list all users page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
listAllUsers() {
|
||||
return request({
|
||||
url: '/user/list/all'
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: listArtists supports user.js by holding or executing the list artists page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
listArtists(shopId) {
|
||||
return request({
|
||||
url: '/user/list/artists',
|
||||
params: shopId ? { shopId } : undefined
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: createUser supports user.js by holding or executing the create user page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
createUser(data) {
|
||||
return request({
|
||||
url: '/user/create',
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: updateUser supports user.js by holding or executing the update user page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
updateUser(id, data) {
|
||||
return request({
|
||||
url: `/user/update/${id}`,
|
||||
method: 'PUT',
|
||||
data
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: updateUserStatus supports user.js by holding or executing the update user status page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
updateUserStatus(id, status) {
|
||||
return request({
|
||||
url: `/user/status/${id}`,
|
||||
method: 'PUT',
|
||||
data: {
|
||||
status
|
||||
}
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: deleteUser supports user.js by holding or executing the delete user page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
deleteUser(id) {
|
||||
return request({
|
||||
url: `/user/delete/${id}`,
|
||||
method: 'DELETE'
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: unbindUser supports user.js by holding or executing the unbind user page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
unbindUser(id) {
|
||||
return request({
|
||||
url: `/user/unbind/${id}`,
|
||||
method: 'PUT',
|
||||
data: {}
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: resetPassword supports user.js by holding or executing the reset password page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
resetPassword(id) {
|
||||
return request({
|
||||
url: `/user/reset-password/${id}`,
|
||||
method: 'POST'
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: getCurrentUserInfo supports user.js by holding or executing the get current user info page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
getCurrentUserInfo() {
|
||||
return request({
|
||||
url: '/user/info'
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: getUserAsset supports user.js by holding or executing the get user asset page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
getUserAsset(id) {
|
||||
return request({
|
||||
url: `/user/${id}/asset`
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: getUserBalanceHistory supports user.js by holding or executing the get user balance history page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
getUserBalanceHistory(id) {
|
||||
return request({
|
||||
url: `/user/${id}/balance/history`
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: changeUserBalance supports user.js by holding or executing the change user balance page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
changeUserBalance(id, data) {
|
||||
return request({
|
||||
url: `/user/${id}/balance/change`,
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: overrideUserVip supports user.js by holding or executing the override user vip page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
overrideUserVip(id, data) {
|
||||
return request({
|
||||
url: `/user/${id}/vip/override`,
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: recalculateUserVip supports user.js by holding or executing the recalculate user vip page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
recalculateUserVip(id) {
|
||||
return request({
|
||||
url: `/user/${id}/vip/recalculate`,
|
||||
method: 'POST'
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,508 +0,0 @@
|
||||
page {
|
||||
min-height: 100%;
|
||||
background:
|
||||
radial-gradient(circle at top left, rgba(240, 126, 87, 0.18), transparent 30%),
|
||||
linear-gradient(180deg, #071417 0%, #0d2225 30%, #f5f0e8 30%, #f5f0e8 100%);
|
||||
color: #132024;
|
||||
font-size: 28rpx;
|
||||
}
|
||||
|
||||
view,
|
||||
text,
|
||||
button,
|
||||
input,
|
||||
textarea,
|
||||
scroll-view,
|
||||
swiper,
|
||||
swiper-item,
|
||||
picker,
|
||||
label,
|
||||
image,
|
||||
checkbox,
|
||||
checkbox-group {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
image {
|
||||
display: block;
|
||||
}
|
||||
|
||||
button {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
line-height: 1;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
button::after {
|
||||
border: 0;
|
||||
}
|
||||
|
||||
.page-shell {
|
||||
min-height: 100vh;
|
||||
padding-bottom: calc(env(safe-area-inset-bottom) + 36rpx);
|
||||
}
|
||||
|
||||
.page-stack {
|
||||
padding: 24rpx;
|
||||
}
|
||||
|
||||
.hero-panel {
|
||||
padding: 34rpx 30rpx;
|
||||
border-radius: 36rpx;
|
||||
background: linear-gradient(140deg, rgba(8, 21, 24, 0.96) 0%, rgba(20, 51, 52, 0.96) 100%);
|
||||
color: #f6efe7;
|
||||
box-shadow: 0 26rpx 64rpx rgba(7, 20, 23, 0.28);
|
||||
}
|
||||
|
||||
.hero-kicker {
|
||||
display: block;
|
||||
font-size: 22rpx;
|
||||
font-weight: 700;
|
||||
letter-spacing: 3rpx;
|
||||
color: #f7b296;
|
||||
}
|
||||
|
||||
.hero-title {
|
||||
display: block;
|
||||
margin-top: 16rpx;
|
||||
font-size: 48rpx;
|
||||
line-height: 1.2;
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
.hero-desc {
|
||||
display: block;
|
||||
margin-top: 16rpx;
|
||||
font-size: 24rpx;
|
||||
line-height: 1.8;
|
||||
color: rgba(246, 239, 231, 0.78);
|
||||
}
|
||||
|
||||
.surface-card {
|
||||
margin-top: 24rpx;
|
||||
padding: 28rpx;
|
||||
border-radius: 30rpx;
|
||||
background: rgba(255, 252, 247, 0.96);
|
||||
border: 1rpx solid rgba(19, 32, 36, 0.08);
|
||||
box-shadow: 0 18rpx 44rpx rgba(26, 39, 42, 0.08);
|
||||
}
|
||||
|
||||
.section-title {
|
||||
display: block;
|
||||
font-size: 34rpx;
|
||||
font-weight: 800;
|
||||
color: #132024;
|
||||
}
|
||||
|
||||
.section-desc {
|
||||
display: block;
|
||||
margin-top: 10rpx;
|
||||
font-size: 24rpx;
|
||||
line-height: 1.7;
|
||||
color: #60706d;
|
||||
}
|
||||
|
||||
.field-group {
|
||||
margin-top: 24rpx;
|
||||
}
|
||||
|
||||
.field-label {
|
||||
display: block;
|
||||
margin-bottom: 12rpx;
|
||||
font-size: 24rpx;
|
||||
font-weight: 700;
|
||||
color: #294248;
|
||||
}
|
||||
|
||||
.field-input,
|
||||
.field-picker,
|
||||
.field-textarea {
|
||||
width: 100%;
|
||||
min-height: 92rpx;
|
||||
padding: 0 24rpx;
|
||||
border-radius: 24rpx;
|
||||
background: #eef1ea;
|
||||
border: 1rpx solid rgba(19, 32, 36, 0.08);
|
||||
color: #132024;
|
||||
font-size: 28rpx;
|
||||
}
|
||||
|
||||
.field-picker {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.field-textarea {
|
||||
min-height: 200rpx;
|
||||
padding: 24rpx;
|
||||
}
|
||||
|
||||
.placeholder {
|
||||
color: #9eaaa5;
|
||||
}
|
||||
|
||||
.status-text {
|
||||
display: block;
|
||||
margin-top: 10rpx;
|
||||
font-size: 22rpx;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.status-text.success {
|
||||
color: #2d8d60;
|
||||
}
|
||||
|
||||
.status-text.error {
|
||||
color: #be4f3b;
|
||||
}
|
||||
|
||||
.status-text.warning {
|
||||
color: #a66817;
|
||||
}
|
||||
|
||||
.primary-btn,
|
||||
.secondary-btn,
|
||||
.danger-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
min-height: 88rpx;
|
||||
padding: 0 28rpx;
|
||||
border-radius: 999rpx;
|
||||
font-size: 28rpx;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.primary-btn {
|
||||
background: linear-gradient(135deg, #f8a37c 0%, #f07e57 100%);
|
||||
color: #fffaf4;
|
||||
}
|
||||
|
||||
.secondary-btn {
|
||||
background: rgba(8, 21, 24, 0.04);
|
||||
color: #173036;
|
||||
border: 1rpx solid rgba(8, 21, 24, 0.1);
|
||||
}
|
||||
|
||||
.danger-btn {
|
||||
background: rgba(190, 79, 59, 0.12);
|
||||
color: #b94432;
|
||||
}
|
||||
|
||||
.action-row {
|
||||
display: flex;
|
||||
gap: 16rpx;
|
||||
margin-top: 24rpx;
|
||||
}
|
||||
|
||||
.action-row .primary-btn,
|
||||
.action-row .secondary-btn,
|
||||
.action-row .danger-btn {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.badge-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 12rpx;
|
||||
margin-top: 18rpx;
|
||||
}
|
||||
|
||||
.badge,
|
||||
.soft-badge,
|
||||
.danger-badge,
|
||||
.success-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 48rpx;
|
||||
padding: 0 18rpx;
|
||||
border-radius: 999rpx;
|
||||
font-size: 22rpx;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.badge {
|
||||
background: rgba(240, 126, 87, 0.14);
|
||||
color: #d05f3d;
|
||||
}
|
||||
|
||||
.soft-badge {
|
||||
background: rgba(8, 21, 24, 0.06);
|
||||
color: #50625f;
|
||||
}
|
||||
|
||||
.danger-badge {
|
||||
background: rgba(190, 79, 59, 0.12);
|
||||
color: #b94432;
|
||||
}
|
||||
|
||||
.success-badge {
|
||||
background: rgba(45, 141, 96, 0.12);
|
||||
color: #2d8d60;
|
||||
}
|
||||
|
||||
.stats-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 16rpx;
|
||||
margin-top: 22rpx;
|
||||
}
|
||||
|
||||
.stat-card {
|
||||
padding: 24rpx;
|
||||
border-radius: 24rpx;
|
||||
background: rgba(8, 21, 24, 0.04);
|
||||
}
|
||||
|
||||
.stat-label {
|
||||
display: block;
|
||||
font-size: 22rpx;
|
||||
color: #667774;
|
||||
}
|
||||
|
||||
.stat-value {
|
||||
display: block;
|
||||
margin-top: 10rpx;
|
||||
font-size: 34rpx;
|
||||
font-weight: 800;
|
||||
color: #132024;
|
||||
}
|
||||
|
||||
.stat-note {
|
||||
display: block;
|
||||
margin-top: 8rpx;
|
||||
font-size: 22rpx;
|
||||
color: #7b8a87;
|
||||
}
|
||||
|
||||
.list-card {
|
||||
margin-top: 18rpx;
|
||||
padding: 24rpx;
|
||||
border-radius: 26rpx;
|
||||
background: #ffffff;
|
||||
border: 1rpx solid rgba(19, 32, 36, 0.08);
|
||||
}
|
||||
|
||||
.list-head {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16rpx;
|
||||
}
|
||||
|
||||
.list-title {
|
||||
display: block;
|
||||
font-size: 30rpx;
|
||||
line-height: 1.5;
|
||||
font-weight: 800;
|
||||
color: #132024;
|
||||
}
|
||||
|
||||
.list-subtitle {
|
||||
display: block;
|
||||
margin-top: 8rpx;
|
||||
font-size: 22rpx;
|
||||
color: #768582;
|
||||
}
|
||||
|
||||
.meta-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 12rpx 20rpx;
|
||||
margin-top: 22rpx;
|
||||
}
|
||||
|
||||
.meta-item {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.meta-label {
|
||||
display: block;
|
||||
font-size: 21rpx;
|
||||
color: #82918e;
|
||||
}
|
||||
|
||||
.meta-value {
|
||||
display: block;
|
||||
margin-top: 6rpx;
|
||||
font-size: 25rpx;
|
||||
color: #1b3035;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.list-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 12rpx;
|
||||
margin-top: 22rpx;
|
||||
}
|
||||
|
||||
.admin-bottom-nav {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
gap: 10rpx;
|
||||
margin-top: 24rpx;
|
||||
padding: 12rpx;
|
||||
border-radius: 28rpx;
|
||||
background: rgba(8, 21, 24, 0.08);
|
||||
}
|
||||
|
||||
.admin-bottom-link {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-width: 0;
|
||||
min-height: 68rpx;
|
||||
border-radius: 999rpx;
|
||||
color: #50625f;
|
||||
font-size: 24rpx;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.admin-bottom-link.active {
|
||||
background: rgba(240, 126, 87, 0.18);
|
||||
color: #c85b39;
|
||||
}
|
||||
|
||||
.mini-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-width: 132rpx;
|
||||
min-height: 62rpx;
|
||||
padding: 0 20rpx;
|
||||
border-radius: 999rpx;
|
||||
background: rgba(8, 21, 24, 0.05);
|
||||
color: #173036;
|
||||
font-size: 24rpx;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.mini-btn.primary {
|
||||
background: rgba(240, 126, 87, 0.14);
|
||||
color: #cf5e3c;
|
||||
}
|
||||
|
||||
.mini-btn.danger {
|
||||
background: rgba(190, 79, 59, 0.12);
|
||||
color: #b94432;
|
||||
}
|
||||
|
||||
.search-row,
|
||||
.filter-row {
|
||||
display: flex;
|
||||
gap: 14rpx;
|
||||
margin-top: 18rpx;
|
||||
}
|
||||
|
||||
.search-input {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.chip-row,
|
||||
.checkbox-grid {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 12rpx;
|
||||
margin-top: 18rpx;
|
||||
}
|
||||
|
||||
.chip-btn,
|
||||
.checkbox-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 60rpx;
|
||||
padding: 0 20rpx;
|
||||
border-radius: 999rpx;
|
||||
background: rgba(8, 21, 24, 0.05);
|
||||
color: #4d625f;
|
||||
font-size: 24rpx;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.chip-btn.active,
|
||||
.checkbox-chip.active {
|
||||
background: rgba(240, 126, 87, 0.16);
|
||||
color: #c85b39;
|
||||
}
|
||||
|
||||
.checkbox-chip.disabled {
|
||||
opacity: 0.45;
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
margin-top: 24rpx;
|
||||
padding: 72rpx 36rpx;
|
||||
border-radius: 30rpx;
|
||||
background: rgba(255, 252, 247, 0.8);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.empty-title {
|
||||
display: block;
|
||||
font-size: 34rpx;
|
||||
font-weight: 800;
|
||||
color: #132024;
|
||||
}
|
||||
|
||||
.empty-desc {
|
||||
display: block;
|
||||
margin-top: 14rpx;
|
||||
font-size: 24rpx;
|
||||
line-height: 1.8;
|
||||
color: #758582;
|
||||
}
|
||||
|
||||
.fab {
|
||||
position: fixed;
|
||||
right: 28rpx;
|
||||
bottom: calc(env(safe-area-inset-bottom) + 128rpx);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 112rpx;
|
||||
height: 112rpx;
|
||||
border-radius: 999rpx;
|
||||
background: linear-gradient(135deg, #f8a37c 0%, #f07e57 100%);
|
||||
color: #fffaf4;
|
||||
box-shadow: 0 22rpx 50rpx rgba(240, 126, 87, 0.3);
|
||||
font-size: 38rpx;
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
.hint-card {
|
||||
margin-top: 18rpx;
|
||||
padding: 20rpx 22rpx;
|
||||
border-radius: 24rpx;
|
||||
background: rgba(240, 126, 87, 0.12);
|
||||
color: #8f4d33;
|
||||
font-size: 24rpx;
|
||||
line-height: 1.75;
|
||||
}
|
||||
|
||||
.divider-line {
|
||||
width: 100%;
|
||||
height: 2rpx;
|
||||
margin: 18rpx 0;
|
||||
background: rgba(19, 32, 36, 0.08);
|
||||
}
|
||||
|
||||
.image-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 14rpx;
|
||||
margin-top: 18rpx;
|
||||
}
|
||||
|
||||
.image-chip {
|
||||
padding: 18rpx 14rpx;
|
||||
border-radius: 24rpx;
|
||||
background: rgba(8, 21, 24, 0.04);
|
||||
font-size: 22rpx;
|
||||
color: #50625f;
|
||||
line-height: 1.6;
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 688 B |
Binary file not shown.
|
Before Width: | Height: | Size: 585 B |
Binary file not shown.
|
Before Width: | Height: | Size: 979 B |
Binary file not shown.
|
Before Width: | Height: | Size: 950 B |
Binary file not shown.
|
Before Width: | Height: | Size: 780 B |
Binary file not shown.
|
Before Width: | Height: | Size: 793 B |
@@ -1,147 +0,0 @@
|
||||
Component({
|
||||
options: {
|
||||
multipleSlots: true // 在组件定义时的选项中启用多slot支持
|
||||
},
|
||||
/**
|
||||
* 组件的属性列表
|
||||
*/
|
||||
properties: {
|
||||
extClass: {
|
||||
type: String,
|
||||
value: ''
|
||||
},
|
||||
title: {
|
||||
type: String,
|
||||
value: ''
|
||||
},
|
||||
background: {
|
||||
type: String,
|
||||
value: ''
|
||||
},
|
||||
color: {
|
||||
type: String,
|
||||
value: ''
|
||||
},
|
||||
back: {
|
||||
type: Boolean,
|
||||
value: true
|
||||
},
|
||||
loading: {
|
||||
type: Boolean,
|
||||
value: false
|
||||
},
|
||||
homeButton: {
|
||||
type: Boolean,
|
||||
value: false,
|
||||
},
|
||||
animated: {
|
||||
// 显示隐藏的时候opacity动画效果
|
||||
type: Boolean,
|
||||
value: true
|
||||
},
|
||||
show: {
|
||||
// 显示隐藏导航,隐藏的时候navigation-bar的高度占位还在
|
||||
type: Boolean,
|
||||
value: true,
|
||||
observer: '_showChange'
|
||||
},
|
||||
// back为true的时候,返回的页面深度
|
||||
delta: {
|
||||
type: Number,
|
||||
value: 1
|
||||
},
|
||||
},
|
||||
/**
|
||||
* 组件的初始数据
|
||||
*/
|
||||
data: {
|
||||
/**
|
||||
* Purpose: displayStyle supports navigation-bar.js by holding or executing the display style page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
displayStyle: ''
|
||||
},
|
||||
/**
|
||||
* Purpose: lifetimes supports navigation-bar.js by holding or executing the lifetimes page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
lifetimes: {
|
||||
attached() {
|
||||
const rect = wx.getMenuButtonBoundingClientRect()
|
||||
const platform = (wx.getDeviceInfo() || wx.getSystemInfoSync()).platform
|
||||
const isAndroid = platform === 'android'
|
||||
const isDevtools = platform === 'devtools'
|
||||
const { windowWidth, safeArea: { top = 0, bottom = 0 } = {} } = wx.getWindowInfo() || wx.getSystemInfoSync()
|
||||
this.setData({
|
||||
/**
|
||||
* Purpose: ios supports navigation-bar.js by holding or executing the ios page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
ios: !isAndroid,
|
||||
/**
|
||||
* Purpose: innerPaddingRight supports navigation-bar.js by holding or executing the inner padding right page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
innerPaddingRight: `padding-right: ${windowWidth - rect.left}px`,
|
||||
/**
|
||||
* Purpose: leftWidth supports navigation-bar.js by holding or executing the left width page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
leftWidth: `width: ${windowWidth - rect.left}px`,
|
||||
/**
|
||||
* Purpose: safeAreaTop supports navigation-bar.js by holding or executing the safe area top page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
safeAreaTop: isDevtools || isAndroid ? `height: calc(var(--height) + ${top}px); padding-top: ${top}px` : ``
|
||||
})
|
||||
},
|
||||
},
|
||||
/**
|
||||
* 组件的方法列表
|
||||
*/
|
||||
methods: {
|
||||
_showChange(show) {
|
||||
const animated = this.data.animated
|
||||
let displayStyle = ''
|
||||
if (animated) {
|
||||
displayStyle = `opacity: ${show ? '1' : '0'
|
||||
};transition:opacity 0.5s;`
|
||||
} else {
|
||||
displayStyle = `display: ${show ? '' : 'none'}`
|
||||
}
|
||||
this.setData({
|
||||
displayStyle
|
||||
})
|
||||
},
|
||||
back() {
|
||||
const data = this.data
|
||||
const pages = getCurrentPages()
|
||||
if (data.delta && pages.length > data.delta) {
|
||||
wx.navigateBack({
|
||||
/**
|
||||
* Purpose: delta supports navigation-bar.js by holding or executing the delta page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
delta: data.delta
|
||||
})
|
||||
return
|
||||
}
|
||||
this.triggerEvent('back', { delta: data.delta }, {})
|
||||
},
|
||||
home() {
|
||||
wx.redirectTo({
|
||||
/**
|
||||
* Purpose: url supports navigation-bar.js by holding or executing the url page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
url: '/admin/pages/workbench/index',
|
||||
fail() {
|
||||
wx.reLaunch({
|
||||
url: '/admin/pages/workbench/index'
|
||||
})
|
||||
}
|
||||
})
|
||||
this.triggerEvent('home', {}, {})
|
||||
}
|
||||
},
|
||||
})
|
||||
@@ -1,64 +0,0 @@
|
||||
<view class="weui-navigation-bar {{extClass}}">
|
||||
<view class="weui-navigation-bar__inner {{ios ? 'ios' : 'android'}}" style="color: {{color}}; background: {{background}}; {{displayStyle}}; {{innerPaddingRight}}; {{safeAreaTop}};">
|
||||
|
||||
<!-- 左侧按钮 -->
|
||||
<view class='weui-navigation-bar__left' style="{{leftWidth}};">
|
||||
<block wx:if="{{back || homeButton}}">
|
||||
<!-- 返回上一页 -->
|
||||
<block wx:if="{{back}}">
|
||||
<view class="weui-navigation-bar__buttons weui-navigation-bar__buttons_goback">
|
||||
<view
|
||||
bindtap="back"
|
||||
class="weui-navigation-bar__btn_goback_wrapper"
|
||||
hover-class="weui-active"
|
||||
hover-stay-time="100"
|
||||
aria-role="button"
|
||||
aria-label="返回"
|
||||
>
|
||||
<view class="weui-navigation-bar__button weui-navigation-bar__btn_goback"></view>
|
||||
</view>
|
||||
</view>
|
||||
</block>
|
||||
<!-- 返回首页 -->
|
||||
<block wx:if="{{homeButton}}">
|
||||
<view class="weui-navigation-bar__buttons weui-navigation-bar__buttons_home">
|
||||
<view
|
||||
bindtap="home"
|
||||
class="weui-navigation-bar__btn_home_wrapper"
|
||||
hover-class="weui-active"
|
||||
aria-role="button"
|
||||
aria-label="首页"
|
||||
>
|
||||
<view class="weui-navigation-bar__button weui-navigation-bar__btn_home"></view>
|
||||
</view>
|
||||
</view>
|
||||
</block>
|
||||
</block>
|
||||
<block wx:else>
|
||||
<slot name="left"></slot>
|
||||
</block>
|
||||
</view>
|
||||
|
||||
<!-- 标题 -->
|
||||
<view class='weui-navigation-bar__center'>
|
||||
<view wx:if="{{loading}}" class="weui-navigation-bar__loading" aria-role="alert">
|
||||
<view
|
||||
class="weui-loading"
|
||||
aria-role="img"
|
||||
aria-label="加载中"
|
||||
></view>
|
||||
</view>
|
||||
<block wx:if="{{title}}">
|
||||
<text>{{title}}</text>
|
||||
</block>
|
||||
<block wx:else>
|
||||
<slot name="center"></slot>
|
||||
</block>
|
||||
</view>
|
||||
|
||||
<!-- 右侧留空 -->
|
||||
<view class='weui-navigation-bar__right'>
|
||||
<slot name="right"></slot>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
@@ -1,99 +0,0 @@
|
||||
.weui-navigation-bar {
|
||||
--weui-FG-0:rgba(0,0,0,.9);
|
||||
--height: 44px;
|
||||
--left: 16px;
|
||||
}
|
||||
.weui-navigation-bar .android {
|
||||
--height: 48px;
|
||||
}
|
||||
|
||||
.weui-navigation-bar {
|
||||
overflow: hidden;
|
||||
color: var(--weui-FG-0);
|
||||
flex: none;
|
||||
position: relative;
|
||||
z-index: 20;
|
||||
}
|
||||
|
||||
.weui-navigation-bar__inner {
|
||||
position: relative;
|
||||
top: 0;
|
||||
left: 0;
|
||||
z-index: 1;
|
||||
height: calc(var(--height) + env(safe-area-inset-top));
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding-top: env(safe-area-inset-top);
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.weui-navigation-bar__left {
|
||||
position: relative;
|
||||
padding-left: var(--left);
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: flex-start;
|
||||
height: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.weui-navigation-bar__btn_goback_wrapper {
|
||||
padding: 11px 18px 11px 16px;
|
||||
margin: -11px -18px -11px -16px;
|
||||
}
|
||||
|
||||
.weui-navigation-bar__btn_goback_wrapper.weui-active {
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
.weui-navigation-bar__btn_goback {
|
||||
font-size: 12px;
|
||||
width: 12px;
|
||||
height: 24px;
|
||||
-webkit-mask: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='24' viewBox='0 0 12 24'%3E %3Cpath fill-opacity='.9' fill-rule='evenodd' d='M10 19.438L8.955 20.5l-7.666-7.79a1.02 1.02 0 0 1 0-1.42L8.955 3.5 10 4.563 2.682 12 10 19.438z'/%3E%3C/svg%3E") no-repeat 50% 50%;
|
||||
mask: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='24' viewBox='0 0 12 24'%3E %3Cpath fill-opacity='.9' fill-rule='evenodd' d='M10 19.438L8.955 20.5l-7.666-7.79a1.02 1.02 0 0 1 0-1.42L8.955 3.5 10 4.563 2.682 12 10 19.438z'/%3E%3C/svg%3E") no-repeat 50% 50%;
|
||||
-webkit-mask-size: cover;
|
||||
mask-size: cover;
|
||||
background-color: currentColor;
|
||||
}
|
||||
|
||||
.weui-navigation-bar__center {
|
||||
font-size: 17px;
|
||||
text-align: center;
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-weight: bold;
|
||||
flex: 1;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.weui-navigation-bar__loading {
|
||||
margin-right: 4px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.weui-loading {
|
||||
font-size: 16px;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
display: block;
|
||||
background: transparent url("data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3Csvg width='80px' height='80px' viewBox='0 0 80 80' version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'%3E%3Ctitle%3Eloading%3C/title%3E%3Cdefs%3E%3ClinearGradient x1='94.0869141%25' y1='0%25' x2='94.0869141%25' y2='90.559082%25' id='linearGradient-1'%3E%3Cstop stop-color='%23606060' stop-opacity='0' offset='0%25'%3E%3C/stop%3E%3Cstop stop-color='%23606060' stop-opacity='0.3' offset='100%25'%3E%3C/stop%3E%3C/linearGradient%3E%3ClinearGradient x1='100%25' y1='8.67370605%25' x2='100%25' y2='90.6286621%25' id='linearGradient-2'%3E%3Cstop stop-color='%23606060' offset='0%25'%3E%3C/stop%3E%3Cstop stop-color='%23606060' stop-opacity='0.3' offset='100%25'%3E%3C/stop%3E%3C/linearGradient%3E%3C/defs%3E%3Cg stroke='none' stroke-width='1' fill='none' fill-rule='evenodd' opacity='0.9'%3E%3Cg%3E%3Cpath d='M40,0 C62.09139,0 80,17.90861 80,40 C80,62.09139 62.09139,80 40,80 L40,73 C58.2253967,73 73,58.2253967 73,40 C73,21.7746033 58.2253967,7 40,7 L40,0 Z' fill='url(%23linearGradient-1)'%3E%3C/path%3E%3Cpath d='M40,0 L40,7 C21.7746033,7 7,21.7746033 7,40 C7,58.2253967 21.7746033,73 40,73 L40,80 C17.90861,80 0,62.09139 0,40 C0,17.90861 17.90861,0 40,0 Z' fill='url(%23linearGradient-2)'%3E%3C/path%3E%3Ccircle id='Oval' fill='%23606060' cx='40.5' cy='3.5' r='3.5'%3E%3C/circle%3E%3C/g%3E%3C/g%3E%3C/svg%3E%0A") no-repeat;
|
||||
background-size: 100%;
|
||||
margin-left: 0;
|
||||
animation: loading linear infinite 1s;
|
||||
}
|
||||
|
||||
@keyframes loading {
|
||||
from {
|
||||
transform: rotate(0);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
@@ -1,166 +0,0 @@
|
||||
const afterSaleApi = require('../../api/after-sale')
|
||||
const navigation = require('../../utils/navigation')
|
||||
const permission = require('../../utils/permission')
|
||||
const format = require('../../utils/format')
|
||||
const { markDirty } = require('../../utils/page-state')
|
||||
|
||||
const STATUS_OPTIONS = [
|
||||
{ label: '全部', value: '' },
|
||||
{ label: '待处理', value: 'PENDING' },
|
||||
{ label: '已同意', value: 'APPROVED' },
|
||||
{ label: '已驳回', value: 'REJECTED' }
|
||||
]
|
||||
|
||||
function safeList(response) {
|
||||
if (Array.isArray(response && response.list)) {
|
||||
return response.list
|
||||
}
|
||||
if (Array.isArray(response && response.records)) {
|
||||
return response.records
|
||||
}
|
||||
return []
|
||||
}
|
||||
|
||||
function statusText(status) {
|
||||
if (status === 'PENDING') {
|
||||
return '待处理'
|
||||
}
|
||||
if (status === 'APPROVED') {
|
||||
return '已同意'
|
||||
}
|
||||
if (status === 'REJECTED') {
|
||||
return '已驳回'
|
||||
}
|
||||
return status || '--'
|
||||
}
|
||||
|
||||
Page({
|
||||
data: {
|
||||
loading: false,
|
||||
list: [],
|
||||
total: 0,
|
||||
status: 'PENDING',
|
||||
statusOptions: STATUS_OPTIONS,
|
||||
canAudit: false
|
||||
},
|
||||
|
||||
onShow() {
|
||||
if (!navigation.ensureLogin('进入售后处理')) {
|
||||
return
|
||||
}
|
||||
const permissionCodes = getApp().globalData.permissionCodes || []
|
||||
this.setData({
|
||||
canAudit: permission.hasPermission(permissionCodes, 'after_sale:audit')
|
||||
})
|
||||
this.loadAfterSales()
|
||||
},
|
||||
|
||||
onPullDownRefresh() {
|
||||
this.loadAfterSales().finally(() => {
|
||||
wx.stopPullDownRefresh()
|
||||
})
|
||||
},
|
||||
|
||||
async loadAfterSales() {
|
||||
this.setData({ loading: true })
|
||||
try {
|
||||
const response = await afterSaleApi.listAfterSales({
|
||||
page: 1,
|
||||
size: 20,
|
||||
status: this.data.status || undefined
|
||||
})
|
||||
this.setData({
|
||||
list: safeList(response).map(item => this.formatAfterSale(item)),
|
||||
total: Number(response && response.total) || 0
|
||||
})
|
||||
} catch (error) {
|
||||
wx.showToast({
|
||||
title: error.message || '售后加载失败',
|
||||
icon: 'none'
|
||||
})
|
||||
} finally {
|
||||
this.setData({ loading: false })
|
||||
}
|
||||
},
|
||||
|
||||
formatAfterSale(item) {
|
||||
return {
|
||||
...item,
|
||||
displayCreateTime: format.formatDateTime(item.createTime),
|
||||
displayAuditTime: format.formatDateTime(item.auditTime),
|
||||
displayRefundAmount: format.formatPrice(item.refundAmount),
|
||||
statusText: statusText(item.status)
|
||||
}
|
||||
},
|
||||
|
||||
handleStatusChange(event) {
|
||||
this.setData({
|
||||
status: event.currentTarget.dataset.status || ''
|
||||
})
|
||||
this.loadAfterSales()
|
||||
},
|
||||
|
||||
promptReason(title) {
|
||||
return new Promise(resolve => {
|
||||
wx.showModal({
|
||||
title,
|
||||
content: '可填写处理说明,留空也可以提交。',
|
||||
editable: true,
|
||||
placeholderText: '处理说明',
|
||||
confirmText: '提交',
|
||||
success: result => {
|
||||
if (!result.confirm) {
|
||||
resolve(null)
|
||||
return
|
||||
}
|
||||
resolve(String(result.content || '').trim())
|
||||
},
|
||||
fail: () => resolve(null)
|
||||
})
|
||||
})
|
||||
},
|
||||
|
||||
async handleAudit(event) {
|
||||
if (!this.data.canAudit) {
|
||||
wx.showToast({
|
||||
title: '当前账号没有处理售后权限',
|
||||
icon: 'none'
|
||||
})
|
||||
return
|
||||
}
|
||||
const id = event.currentTarget.dataset.id
|
||||
const action = event.currentTarget.dataset.action
|
||||
if (!id || !action) {
|
||||
return
|
||||
}
|
||||
const reason = await this.promptReason(action === 'approve' ? '同意售后' : '驳回售后')
|
||||
if (reason === null) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
const data = {
|
||||
auditReason: reason
|
||||
}
|
||||
if (action === 'approve') {
|
||||
await afterSaleApi.approveAfterSale(id, data)
|
||||
} else {
|
||||
await afterSaleApi.rejectAfterSale(id, data)
|
||||
}
|
||||
markDirty('admin-workbench')
|
||||
wx.showToast({
|
||||
title: '售后已处理',
|
||||
icon: 'none'
|
||||
})
|
||||
this.loadAfterSales()
|
||||
} catch (error) {
|
||||
wx.showToast({
|
||||
title: error.message || '售后处理失败',
|
||||
icon: 'none'
|
||||
})
|
||||
}
|
||||
},
|
||||
|
||||
handleBack() {
|
||||
navigation.goBack('/pages/manage/index')
|
||||
}
|
||||
})
|
||||
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"usingComponents": {
|
||||
"navigation-bar": "/admin/components/navigation-bar/navigation-bar"
|
||||
},
|
||||
"enablePullDownRefresh": true
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
<navigation-bar title="售后处理" back="{{true}}" bindback="handleBack" color="#f6efe7" background="#081518"></navigation-bar>
|
||||
|
||||
<view class="page-shell">
|
||||
<view class="page-stack">
|
||||
<view class="hero-panel">
|
||||
<text class="hero-kicker">After Sale</text>
|
||||
<text class="hero-title">售后处理</text>
|
||||
<text class="hero-desc">查看待处理退款/售后申请,在手机端完成同意或驳回的最小闭环。</text>
|
||||
</view>
|
||||
|
||||
<view class="surface-card">
|
||||
<text class="section-title">状态筛选</text>
|
||||
<view class="chip-row">
|
||||
<block wx:for="{{statusOptions}}" wx:key="value">
|
||||
<view class="chip-btn {{status === item.value ? 'active' : ''}}" data-status="{{item.value}}" bindtap="handleStatusChange">{{item.label}}</view>
|
||||
</block>
|
||||
</view>
|
||||
<text class="section-desc">共 {{total}} 条记录</text>
|
||||
</view>
|
||||
|
||||
<block wx:for="{{list}}" wx:key="id">
|
||||
<view class="list-card">
|
||||
<view class="list-head">
|
||||
<view>
|
||||
<text class="list-title">{{item.afterSaleNo || ('售后 #' + item.id)}}</text>
|
||||
<text class="list-subtitle">订单 {{item.orderId || '--'}} · {{item.displayCreateTime || '--'}}</text>
|
||||
</view>
|
||||
<text class="{{item.status === 'PENDING' ? 'badge' : 'soft-badge'}}">{{item.statusText}}</text>
|
||||
</view>
|
||||
<view class="meta-grid">
|
||||
<view class="meta-item">
|
||||
<text class="meta-label">类型</text>
|
||||
<text class="meta-value">{{item.type || '--'}}</text>
|
||||
</view>
|
||||
<view class="meta-item">
|
||||
<text class="meta-label">退款金额</text>
|
||||
<text class="meta-value">¥{{item.displayRefundAmount}}</text>
|
||||
</view>
|
||||
<view class="meta-item">
|
||||
<text class="meta-label">用户 ID</text>
|
||||
<text class="meta-value">{{item.userId || '--'}}</text>
|
||||
</view>
|
||||
<view class="meta-item">
|
||||
<text class="meta-label">审核时间</text>
|
||||
<text class="meta-value">{{item.displayAuditTime || '--'}}</text>
|
||||
</view>
|
||||
</view>
|
||||
<view wx:if="{{item.reason}}" class="hint-card">{{item.reason}}</view>
|
||||
<view wx:if="{{item.auditReason}}" class="hint-card">处理说明:{{item.auditReason}}</view>
|
||||
<view wx:if="{{item.status === 'PENDING'}}" class="list-actions">
|
||||
<view class="mini-btn primary" data-id="{{item.id}}" data-action="approve" bindtap="handleAudit">同意</view>
|
||||
<view class="mini-btn danger" data-id="{{item.id}}" data-action="reject" bindtap="handleAudit">驳回</view>
|
||||
</view>
|
||||
</view>
|
||||
</block>
|
||||
|
||||
<view wx:if="{{!list.length && !loading}}" class="empty-state">
|
||||
<text class="empty-title">暂无售后单</text>
|
||||
<text class="empty-desc">当前状态下没有需要展示的售后记录。</text>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
@@ -1,4 +0,0 @@
|
||||
@import "../../app.wxss";
|
||||
.page-shell {
|
||||
background: transparent;
|
||||
}
|
||||
@@ -1,728 +0,0 @@
|
||||
/**
|
||||
* Purpose: artistApi supports index.js by holding or executing the artist api page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const artistApi = require('../../api/nail-artist')
|
||||
/**
|
||||
* Purpose: userApi supports index.js by holding or executing the user api page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const userApi = require('../../api/user')
|
||||
/**
|
||||
* Purpose: tagApi supports index.js by holding or executing the tag api page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const tagApi = require('../../api/tag')
|
||||
/**
|
||||
* Purpose: productApi supports index.js by holding or executing the product api page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const productApi = require('../../api/product')
|
||||
/**
|
||||
* Purpose: shopApi supports index.js by holding or executing the shop api page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const shopApi = require('../../api/shop')
|
||||
/**
|
||||
* Purpose: navigation supports index.js by holding or executing the navigation page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const navigation = require('../../utils/navigation')
|
||||
/**
|
||||
* Purpose: format supports index.js by holding or executing the format page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const format = require('../../utils/format')
|
||||
const { getTempRecord, clearTempRecord } = require('../../utils/storage')
|
||||
|
||||
/**
|
||||
* Purpose: normalizeId supports index.js by holding or executing the normalize id page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function normalizeId(value) {
|
||||
return value === undefined || value === null ? '' : String(value)
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: buildCheckableList supports index.js by holding or executing the build checkable list page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function buildCheckableList(list, selectedIds, labelKey) {
|
||||
return (Array.isArray(list) ? list : []).map(item => ({
|
||||
...item,
|
||||
valueId: normalizeId(item.id),
|
||||
labelText: item[labelKey],
|
||||
checked: selectedIds.includes(normalizeId(item.id))
|
||||
}))
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: syncSelectedIds supports index.js by holding or executing the sync selected ids page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function syncSelectedIds(selectedIds, list) {
|
||||
const availableIds = new Set((Array.isArray(list) ? list : []).map(item => normalizeId(item.id)))
|
||||
return (Array.isArray(selectedIds) ? selectedIds : []).filter(id => availableIds.has(normalizeId(id)))
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: filterProductsByShop supports index.js by holding or executing the filter products by shop page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function filterProductsByShop(products, shopId) {
|
||||
const targetShopId = normalizeId(shopId)
|
||||
if (!targetShopId) {
|
||||
return []
|
||||
}
|
||||
|
||||
return (Array.isArray(products) ? products : []).filter(item => normalizeId(item.shopId) === targetShopId)
|
||||
}
|
||||
|
||||
Page({
|
||||
/**
|
||||
* Purpose: data supports index.js by holding or executing the data page or API role.
|
||||
* Usage: import, call, read, or update this page-data from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
data: {
|
||||
/**
|
||||
* Purpose: mode supports index.js by holding or executing the mode page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
mode: 'create',
|
||||
/**
|
||||
* Purpose: userId supports index.js by holding or executing the user id page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
userId: '',
|
||||
/**
|
||||
* Purpose: shops supports index.js by holding or executing the shops page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
shops: [],
|
||||
/**
|
||||
* Purpose: shopIndex supports index.js by holding or executing the shop index page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
shopIndex: 0,
|
||||
/**
|
||||
* Purpose: shopLabel supports index.js by holding or executing the shop label page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
shopLabel: '',
|
||||
/**
|
||||
* Purpose: statusOptions supports index.js by holding or executing the status options page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
statusOptions: ['营业中', '休息中'],
|
||||
/**
|
||||
* Purpose: statusIndex supports index.js by holding or executing the status index page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
statusIndex: 0,
|
||||
/**
|
||||
* Purpose: userForm supports index.js by holding or executing the user form page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
userForm: {
|
||||
/**
|
||||
* Purpose: nickname supports index.js by holding or executing the nickname page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
nickname: '',
|
||||
/**
|
||||
* Purpose: account supports index.js by holding or executing the account page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
account: '',
|
||||
/**
|
||||
* Purpose: phone supports index.js by holding or executing the phone page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
phone: '',
|
||||
/**
|
||||
* Purpose: password supports index.js by holding or executing the password page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
password: '',
|
||||
/**
|
||||
* Purpose: signature supports index.js by holding or executing the signature page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
signature: ''
|
||||
},
|
||||
/**
|
||||
* Purpose: artistForm supports index.js by holding or executing the artist form page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
artistForm: {
|
||||
/**
|
||||
* Purpose: identity supports index.js by holding or executing the identity page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
identity: '',
|
||||
/**
|
||||
* Purpose: experience supports index.js by holding or executing the experience page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
experience: '',
|
||||
/**
|
||||
* Purpose: rating supports index.js by holding or executing the rating page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
rating: '',
|
||||
/**
|
||||
* Purpose: portfolioText supports index.js by holding or executing the portfolio text page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
portfolioText: ''
|
||||
},
|
||||
/**
|
||||
* Purpose: tags supports index.js by holding or executing the tags page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
tags: [],
|
||||
/**
|
||||
* Purpose: products supports index.js by holding or executing the products page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
products: []
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: onLoad supports index.js by holding or executing the on load page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
onLoad(options) {
|
||||
const mode = options && options.mode ? options.mode : 'create'
|
||||
const currentArtist = getTempRecord('currentArtist', null)
|
||||
this.setData({
|
||||
mode,
|
||||
/**
|
||||
* Purpose: userId supports index.js by holding or executing the user id page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
userId: options && options.userId ? options.userId : ''
|
||||
})
|
||||
|
||||
this._selectedTagIds = []
|
||||
this._selectedProductIds = []
|
||||
this._allProducts = []
|
||||
|
||||
if (mode === 'edit' && currentArtist) {
|
||||
this._selectedTagIds = format.splitCsv(currentArtist.skills)
|
||||
this._selectedProductIds = format.splitCsv(currentArtist.portfolio)
|
||||
this._initialShopId = currentArtist.shopId
|
||||
this.setData({
|
||||
/**
|
||||
* Purpose: artistForm supports index.js by holding or executing the artist form page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
artistForm: {
|
||||
/**
|
||||
* Purpose: identity supports index.js by holding or executing the identity page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
identity: currentArtist.identity || '',
|
||||
/**
|
||||
* Purpose: experience supports index.js by holding or executing the experience page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
experience: currentArtist.experience || '',
|
||||
/**
|
||||
* Purpose: rating supports index.js by holding or executing the rating page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
rating: currentArtist.rating || '',
|
||||
/**
|
||||
* Purpose: portfolioText supports index.js by holding or executing the portfolio text page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
portfolioText: ''
|
||||
},
|
||||
/**
|
||||
* Purpose: userForm supports index.js by holding or executing the user form page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
userForm: {
|
||||
/**
|
||||
* Purpose: nickname supports index.js by holding or executing the nickname page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
nickname: currentArtist.nickname || '',
|
||||
/**
|
||||
* Purpose: account supports index.js by holding or executing the account page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
account: '',
|
||||
/**
|
||||
* Purpose: phone supports index.js by holding or executing the phone page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
phone: '',
|
||||
/**
|
||||
* Purpose: password supports index.js by holding or executing the password page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
password: '',
|
||||
/**
|
||||
* Purpose: signature supports index.js by holding or executing the signature page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
signature: currentArtist.signature || ''
|
||||
},
|
||||
/**
|
||||
* Purpose: statusIndex supports index.js by holding or executing the status index page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
statusIndex: Number(currentArtist.status) === 0 ? 1 : 0
|
||||
})
|
||||
}
|
||||
|
||||
this.loadDependencies()
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: onUnload supports index.js by holding or executing the on unload page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
onUnload() {
|
||||
clearTempRecord('currentArtist')
|
||||
},
|
||||
|
||||
async loadDependencies() {
|
||||
const app = getApp()
|
||||
const currentShop = app.globalData.currentShop
|
||||
const operator = app.globalData.userInfo || {}
|
||||
|
||||
try {
|
||||
const [shops, products, users] = await Promise.all([
|
||||
shopApi.listAllShops(),
|
||||
productApi.listAllProducts(),
|
||||
userApi.listAllUsers()
|
||||
])
|
||||
|
||||
let availableShops = Array.isArray(shops) ? shops : []
|
||||
if (Number(operator.type) !== 4 && currentShop) {
|
||||
availableShops = availableShops.filter(item => normalizeId(item.id) === normalizeId(currentShop.id))
|
||||
}
|
||||
|
||||
let shopIndex = 0
|
||||
if (this._initialShopId) {
|
||||
const index = availableShops.findIndex(item => normalizeId(item.id) === normalizeId(this._initialShopId))
|
||||
if (index >= 0) {
|
||||
shopIndex = index
|
||||
}
|
||||
}
|
||||
const selectedShop = availableShops[shopIndex]
|
||||
this._allProducts = Array.isArray(products) ? products : []
|
||||
|
||||
if (this.data.mode === 'edit') {
|
||||
const userRecord = (Array.isArray(users) ? users : []).find(item => normalizeId(item.id) === normalizeId(this.data.userId))
|
||||
if (userRecord) {
|
||||
this.setData({
|
||||
/**
|
||||
* Purpose: userForm supports index.js by holding or executing the user form page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
userForm: {
|
||||
/**
|
||||
* Purpose: nickname supports index.js by holding or executing the nickname page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
nickname: userRecord.nickname || '',
|
||||
/**
|
||||
* Purpose: account supports index.js by holding or executing the account page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
account: userRecord.account || '',
|
||||
/**
|
||||
* Purpose: phone supports index.js by holding or executing the phone page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
phone: userRecord.phone || '',
|
||||
/**
|
||||
* Purpose: password supports index.js by holding or executing the password page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
password: '',
|
||||
/**
|
||||
* Purpose: signature supports index.js by holding or executing the signature page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
signature: userRecord.signature || ''
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
this.setData({
|
||||
/**
|
||||
* Purpose: shops supports index.js by holding or executing the shops page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
shops: availableShops,
|
||||
shopIndex,
|
||||
/**
|
||||
* Purpose: shopLabel supports index.js by holding or executing the shop label page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
shopLabel: selectedShop ? selectedShop.shopName : ''
|
||||
})
|
||||
|
||||
await this.loadShopScopedOptions(selectedShop ? selectedShop.id : '')
|
||||
} catch (error) {
|
||||
wx.showToast({
|
||||
/**
|
||||
* Purpose: title supports index.js by holding or executing the title page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
title: error.message || '初始化美甲师表单失败',
|
||||
/**
|
||||
* Purpose: icon supports index.js by holding or executing the icon page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
icon: 'none'
|
||||
})
|
||||
}
|
||||
},
|
||||
|
||||
async loadShopScopedOptions(shopId) {
|
||||
if (!normalizeId(shopId)) {
|
||||
this._selectedTagIds = []
|
||||
this._selectedProductIds = []
|
||||
this.setData({
|
||||
/**
|
||||
* Purpose: tags supports index.js by holding or executing the tags page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
tags: [],
|
||||
/**
|
||||
* Purpose: products supports index.js by holding or executing the products page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
products: []
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const tagList = await tagApi.listTagsByShopId(shopId)
|
||||
const productList = filterProductsByShop(this._allProducts, shopId)
|
||||
this._selectedTagIds = syncSelectedIds(this._selectedTagIds, tagList)
|
||||
this._selectedProductIds = syncSelectedIds(this._selectedProductIds, productList)
|
||||
this.setData({
|
||||
/**
|
||||
* Purpose: tags supports index.js by holding or executing the tags page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
tags: buildCheckableList(tagList, this._selectedTagIds, 'tagName'),
|
||||
/**
|
||||
* Purpose: products supports index.js by holding or executing the products page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
products: buildCheckableList(productList, this._selectedProductIds, 'title')
|
||||
})
|
||||
} catch (error) {
|
||||
this.setData({
|
||||
/**
|
||||
* Purpose: tags supports index.js by holding or executing the tags page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
tags: [],
|
||||
/**
|
||||
* Purpose: products supports index.js by holding or executing the products page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
products: []
|
||||
})
|
||||
wx.showToast({
|
||||
/**
|
||||
* Purpose: title supports index.js by holding or executing the title page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
title: error.message || '店铺关联数据加载失败',
|
||||
/**
|
||||
* Purpose: icon supports index.js by holding or executing the icon page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
icon: 'none'
|
||||
})
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: handleUserInput supports index.js by holding or executing the handle user input page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
handleUserInput(event) {
|
||||
const field = event.currentTarget.dataset.field
|
||||
let value = event.detail.value
|
||||
|
||||
if (field === 'account') {
|
||||
value = String(value || '').replace(/[^A-Za-z0-9]/g, '')
|
||||
}
|
||||
if (field === 'phone') {
|
||||
value = String(value || '').replace(/[^\d]/g, '').slice(0, 11)
|
||||
}
|
||||
|
||||
this.setData({
|
||||
[`userForm.${field}`]: value
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: handleArtistInput supports index.js by holding or executing the handle artist input page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
handleArtistInput(event) {
|
||||
const field = event.currentTarget.dataset.field
|
||||
this.setData({
|
||||
[`artistForm.${field}`]: event.detail.value
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: handleShopChange supports index.js by holding or executing the handle shop change page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
handleShopChange(event) {
|
||||
const shopIndex = Number(event.detail.value)
|
||||
const selectedShop = this.data.shops[shopIndex]
|
||||
this.setData({
|
||||
shopIndex,
|
||||
/**
|
||||
* Purpose: shopLabel supports index.js by holding or executing the shop label page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
shopLabel: selectedShop ? selectedShop.shopName : ''
|
||||
})
|
||||
this.loadShopScopedOptions(selectedShop ? selectedShop.id : '')
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: handleStatusChange supports index.js by holding or executing the handle status change page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
handleStatusChange(event) {
|
||||
this.setData({
|
||||
/**
|
||||
* Purpose: statusIndex supports index.js by holding or executing the status index page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
statusIndex: Number(event.detail.value)
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: handleTagChange supports index.js by holding or executing the handle tag change page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
handleTagChange(event) {
|
||||
this._selectedTagIds = event.detail.value || []
|
||||
this.setData({
|
||||
/**
|
||||
* Purpose: tags supports index.js by holding or executing the tags page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
tags: this.data.tags.map(item => ({
|
||||
...item,
|
||||
/**
|
||||
* Purpose: checked supports index.js by holding or executing the checked page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
checked: this._selectedTagIds.includes(item.valueId)
|
||||
}))
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: handleProductChange supports index.js by holding or executing the handle product change page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
handleProductChange(event) {
|
||||
this._selectedProductIds = event.detail.value || []
|
||||
this.setData({
|
||||
/**
|
||||
* Purpose: products supports index.js by holding or executing the products page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
products: this.data.products.map(item => ({
|
||||
...item,
|
||||
/**
|
||||
* Purpose: checked supports index.js by holding or executing the checked page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
checked: this._selectedProductIds.includes(item.valueId)
|
||||
}))
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: validateForm supports index.js by holding or executing the validate form page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
validateForm() {
|
||||
if (!this.data.userForm.nickname) {
|
||||
return '请输入美甲师昵称'
|
||||
}
|
||||
if (!this.data.userForm.account) {
|
||||
return '请输入账号'
|
||||
}
|
||||
if (!this.data.userForm.phone || this.data.userForm.phone.length !== 11) {
|
||||
return '请输入 11 位手机号'
|
||||
}
|
||||
if (this.data.mode === 'create' && !this.data.userForm.password) {
|
||||
return '新增美甲师时必须设置密码'
|
||||
}
|
||||
if (!this.data.shops[this.data.shopIndex]) {
|
||||
return '请选择所属店铺'
|
||||
}
|
||||
return ''
|
||||
},
|
||||
|
||||
async handleSubmit() {
|
||||
const errorMessage = this.validateForm()
|
||||
if (errorMessage) {
|
||||
wx.showToast({
|
||||
/**
|
||||
* Purpose: title supports index.js by holding or executing the title page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
title: errorMessage,
|
||||
/**
|
||||
* Purpose: icon supports index.js by holding or executing the icon page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
icon: 'none'
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
const selectedShop = this.data.shops[this.data.shopIndex]
|
||||
const userPayload = {
|
||||
/**
|
||||
* Purpose: nickname supports index.js by holding or executing the nickname page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
nickname: this.data.userForm.nickname,
|
||||
/**
|
||||
* Purpose: account supports index.js by holding or executing the account page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
account: this.data.userForm.account,
|
||||
/**
|
||||
* Purpose: phone supports index.js by holding or executing the phone page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
phone: this.data.userForm.phone,
|
||||
/**
|
||||
* Purpose: signature supports index.js by holding or executing the signature page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
signature: this.data.userForm.signature || undefined,
|
||||
/**
|
||||
* Purpose: type supports index.js by holding or executing the type page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
type: 3,
|
||||
/**
|
||||
* Purpose: shopIds supports index.js by holding or executing the shop ids page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
shopIds: selectedShop ? [Number(selectedShop.id)] : []
|
||||
}
|
||||
|
||||
if (this.data.userForm.password) {
|
||||
userPayload.password = this.data.userForm.password
|
||||
}
|
||||
|
||||
try {
|
||||
let targetUserId = this.data.userId
|
||||
if (this.data.mode === 'edit') {
|
||||
await userApi.updateUser(targetUserId, userPayload)
|
||||
} else {
|
||||
targetUserId = await userApi.createUser(userPayload)
|
||||
}
|
||||
|
||||
await artistApi.saveNailArtistInfo({
|
||||
/**
|
||||
* Purpose: userId supports index.js by holding or executing the user id page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
userId: Number(targetUserId),
|
||||
/**
|
||||
* Purpose: identity supports index.js by holding or executing the identity page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
identity: this.data.artistForm.identity || undefined,
|
||||
/**
|
||||
* Purpose: experience supports index.js by holding or executing the experience page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
experience: this.data.artistForm.experience ? Number(this.data.artistForm.experience) : 0,
|
||||
/**
|
||||
* Purpose: skills supports index.js by holding or executing the skills page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
skills: this._selectedTagIds.join(',') || undefined,
|
||||
/**
|
||||
* Purpose: rating supports index.js by holding or executing the rating page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
rating: this.data.artistForm.rating ? Number(this.data.artistForm.rating) : 0,
|
||||
/**
|
||||
* Purpose: status supports index.js by holding or executing the status page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
status: this.data.statusIndex === 1 ? 0 : 1,
|
||||
/**
|
||||
* Purpose: portfolio supports index.js by holding or executing the portfolio page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
portfolio: this._selectedProductIds.join(',') || undefined,
|
||||
/**
|
||||
* Purpose: nickname supports index.js by holding or executing the nickname page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
nickname: this.data.userForm.nickname,
|
||||
/**
|
||||
* Purpose: shopId supports index.js by holding or executing the shop id page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
shopId: selectedShop ? Number(selectedShop.id) : undefined,
|
||||
/**
|
||||
* Purpose: signature supports index.js by holding or executing the signature page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
signature: this.data.userForm.signature || undefined
|
||||
})
|
||||
|
||||
wx.showToast({
|
||||
/**
|
||||
* Purpose: title supports index.js by holding or executing the title page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
title: this.data.mode === 'edit' ? '美甲师已更新' : '美甲师已创建',
|
||||
/**
|
||||
* Purpose: icon supports index.js by holding or executing the icon page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
icon: 'none'
|
||||
})
|
||||
navigation.goBack('/pages/artists/index')
|
||||
} catch (error) {
|
||||
wx.showToast({
|
||||
/**
|
||||
* Purpose: title supports index.js by holding or executing the title page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
title: error.message || '保存失败',
|
||||
/**
|
||||
* Purpose: icon supports index.js by holding or executing the icon page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
icon: 'none'
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -1,5 +0,0 @@
|
||||
{
|
||||
"usingComponents": {
|
||||
"navigation-bar": "/admin/components/navigation-bar/navigation-bar"
|
||||
}
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
<navigation-bar title="{{mode === 'edit' ? '编辑美甲师' : '新增美甲师'}}" back="{{true}}" color="#f6efe7" background="#081518"></navigation-bar>
|
||||
|
||||
<view class="page-shell">
|
||||
<view class="page-stack">
|
||||
<view class="surface-card">
|
||||
<text class="section-title">账号信息</text>
|
||||
<view class="field-group">
|
||||
<text class="field-label">昵称</text>
|
||||
<input class="field-input" value="{{userForm.nickname}}" data-field="nickname" bindinput="handleUserInput"></input>
|
||||
</view>
|
||||
<view class="field-group">
|
||||
<text class="field-label">账号</text>
|
||||
<input class="field-input" value="{{userForm.account}}" data-field="account" bindinput="handleUserInput"></input>
|
||||
</view>
|
||||
<view class="field-group">
|
||||
<text class="field-label">手机号</text>
|
||||
<input class="field-input" type="number" value="{{userForm.phone}}" data-field="phone" bindinput="handleUserInput"></input>
|
||||
</view>
|
||||
<view class="field-group">
|
||||
<text class="field-label">{{mode === 'edit' ? '密码(留空则不修改)' : '登录密码'}}</text>
|
||||
<input class="field-input" password value="{{userForm.password}}" data-field="password" bindinput="handleUserInput"></input>
|
||||
</view>
|
||||
<view class="field-group">
|
||||
<text class="field-label">签名</text>
|
||||
<textarea class="field-textarea" value="{{userForm.signature}}" data-field="signature" bindinput="handleUserInput"></textarea>
|
||||
</view>
|
||||
<view class="field-group">
|
||||
<text class="field-label">所属店铺</text>
|
||||
<picker mode="selector" range="{{shops}}" range-key="shopName" value="{{shopIndex}}" bindchange="handleShopChange">
|
||||
<view class="field-picker">{{shopLabel || '请选择店铺'}}</view>
|
||||
</picker>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<view class="surface-card">
|
||||
<text class="section-title">职业信息</text>
|
||||
<view class="field-group">
|
||||
<text class="field-label">身份标签</text>
|
||||
<input class="field-input" value="{{artistForm.identity}}" data-field="identity" bindinput="handleArtistInput"></input>
|
||||
</view>
|
||||
<view class="field-group">
|
||||
<text class="field-label">从业年限</text>
|
||||
<input class="field-input" type="number" value="{{artistForm.experience}}" data-field="experience" bindinput="handleArtistInput"></input>
|
||||
</view>
|
||||
<view class="field-group">
|
||||
<text class="field-label">评分</text>
|
||||
<input class="field-input" type="digit" value="{{artistForm.rating}}" data-field="rating" bindinput="handleArtistInput"></input>
|
||||
</view>
|
||||
<view class="field-group">
|
||||
<text class="field-label">营业状态</text>
|
||||
<picker mode="selector" range="{{statusOptions}}" value="{{statusIndex}}" bindchange="handleStatusChange">
|
||||
<view class="field-picker">{{statusOptions[statusIndex]}}</view>
|
||||
</picker>
|
||||
</view>
|
||||
<view class="field-group">
|
||||
<text class="field-label">擅长标签</text>
|
||||
<checkbox-group bindchange="handleTagChange">
|
||||
<block wx:for="{{tags}}" wx:key="id">
|
||||
<label class="checkbox-chip {{item.checked ? 'active' : ''}}">
|
||||
<checkbox value="{{item.valueId}}" checked="{{item.checked}}" />
|
||||
{{item.labelText}}
|
||||
</label>
|
||||
</block>
|
||||
</checkbox-group>
|
||||
</view>
|
||||
<view class="field-group">
|
||||
<text class="field-label">作品集</text>
|
||||
<checkbox-group bindchange="handleProductChange">
|
||||
<block wx:for="{{products}}" wx:key="id">
|
||||
<label class="checkbox-chip {{item.checked ? 'active' : ''}}">
|
||||
<checkbox value="{{item.valueId}}" checked="{{item.checked}}" />
|
||||
{{item.labelText}}
|
||||
</label>
|
||||
</block>
|
||||
</checkbox-group>
|
||||
</view>
|
||||
<view class="action-row">
|
||||
<button class="primary-btn" bindtap="handleSubmit">保存美甲师</button>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
@@ -1,5 +0,0 @@
|
||||
@import "../../app.wxss";
|
||||
checkbox {
|
||||
transform: scale(0.75);
|
||||
margin-right: 8rpx;
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
/**
|
||||
* Purpose: artistApi supports index.js by holding or executing the artist api page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const artistApi = require('../../api/nail-artist')
|
||||
/**
|
||||
* Purpose: navigation supports index.js by holding or executing the navigation page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const navigation = require('../../utils/navigation')
|
||||
const { setTempRecord, clearTempRecord } = require('../../utils/storage')
|
||||
|
||||
Page({
|
||||
/**
|
||||
* Purpose: data supports index.js by holding or executing the data page or API role.
|
||||
* Usage: import, call, read, or update this page-data from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
data: {
|
||||
/**
|
||||
* Purpose: list supports index.js by holding or executing the list page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
list: [],
|
||||
/**
|
||||
* Purpose: canCreate supports index.js by holding or executing the can create page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
canCreate: false
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: onShow supports index.js by holding or executing the on show page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
onShow() {
|
||||
if (!navigation.ensureLogin('进入美甲师管理')) {
|
||||
return
|
||||
}
|
||||
|
||||
const permissionCodes = getApp().globalData.permissionCodes || []
|
||||
this.setData({
|
||||
/**
|
||||
* Purpose: canCreate supports index.js by holding or executing the can create page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
canCreate: permissionCodes.includes('user:create') || permissionCodes.includes('nail_artist:edit')
|
||||
})
|
||||
this.loadArtists()
|
||||
},
|
||||
|
||||
async loadArtists() {
|
||||
try {
|
||||
const list = await artistApi.listNailArtists()
|
||||
this.setData({
|
||||
/**
|
||||
* Purpose: list supports index.js by holding or executing the list page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
list: (Array.isArray(list) ? list : []).map(item => ({
|
||||
...item,
|
||||
/**
|
||||
* Purpose: displayStatusText supports index.js by holding or executing the display status text page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
displayStatusText: Number(item.status) === 0 ? '休息中' : '营业中'
|
||||
}))
|
||||
})
|
||||
} catch (error) {
|
||||
wx.showToast({
|
||||
/**
|
||||
* Purpose: title supports index.js by holding or executing the title page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
title: error.message || '美甲师列表加载失败',
|
||||
/**
|
||||
* Purpose: icon supports index.js by holding or executing the icon page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
icon: 'none'
|
||||
})
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: handleCreate supports index.js by holding or executing the handle create page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
handleCreate() {
|
||||
clearTempRecord('currentArtist')
|
||||
navigation.navigate('/pages/artist-form/index', {
|
||||
/**
|
||||
* Purpose: mode supports index.js by holding or executing the mode page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
mode: 'create'
|
||||
}).catch(() => undefined)
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: handleEdit supports index.js by holding or executing the handle edit page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
handleEdit(event) {
|
||||
const artist = event.currentTarget.dataset.artist
|
||||
setTempRecord('currentArtist', artist)
|
||||
navigation.navigate('/pages/artist-form/index', {
|
||||
/**
|
||||
* Purpose: mode supports index.js by holding or executing the mode page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
mode: 'edit',
|
||||
/**
|
||||
* Purpose: userId supports index.js by holding or executing the user id page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
userId: artist.userId
|
||||
}).catch(() => undefined)
|
||||
}
|
||||
})
|
||||
@@ -1,5 +0,0 @@
|
||||
{
|
||||
"usingComponents": {
|
||||
"navigation-bar": "/admin/components/navigation-bar/navigation-bar"
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
<navigation-bar title="美甲师管理" back="{{true}}" color="#f6efe7" background="#081518"></navigation-bar>
|
||||
|
||||
<view class="page-shell">
|
||||
<view class="page-stack">
|
||||
<view class="surface-card">
|
||||
<text class="section-title">美甲师列表</text>
|
||||
<text class="section-desc">店长只能看到并管理自己门店的美甲师;平台管理员可跨店查看,移动端表单集中处理账号和档案两部分信息。</text>
|
||||
</view>
|
||||
|
||||
<block wx:for="{{list}}" wx:key="id">
|
||||
<view class="list-card">
|
||||
<view class="list-head">
|
||||
<view>
|
||||
<text class="list-title">{{item.nickname}}</text>
|
||||
<text class="list-subtitle">{{item.identity || '未设置身份'}} · {{item.shopName || '当前店铺'}}</text>
|
||||
</view>
|
||||
<text class="{{item.status === 0 ? 'soft-badge' : 'badge'}}">{{item.displayStatusText}}</text>
|
||||
</view>
|
||||
<view class="meta-grid">
|
||||
<view class="meta-item">
|
||||
<text class="meta-label">从业年限</text>
|
||||
<text class="meta-value">{{item.experience || 0}} 年</text>
|
||||
</view>
|
||||
<view class="meta-item">
|
||||
<text class="meta-label">评分</text>
|
||||
<text class="meta-value">{{item.rating || 0}}</text>
|
||||
</view>
|
||||
</view>
|
||||
<view class="list-actions">
|
||||
<view class="mini-btn primary" data-artist="{{item}}" bindtap="handleEdit">编辑</view>
|
||||
</view>
|
||||
</view>
|
||||
</block>
|
||||
|
||||
<view wx:if="{{!list.length}}" class="empty-state">
|
||||
<text class="empty-title">还没有美甲师</text>
|
||||
<text class="empty-desc">可以先新增一个美甲师账号,再补充技能、作品集和营业状态。</text>
|
||||
</view>
|
||||
|
||||
<view wx:if="{{canCreate}}" class="fab" bindtap="handleCreate">+</view>
|
||||
</view>
|
||||
</view>
|
||||
@@ -1,4 +0,0 @@
|
||||
@import "../../app.wxss";
|
||||
.page-shell {
|
||||
background: transparent;
|
||||
}
|
||||
@@ -1,154 +0,0 @@
|
||||
const campaignApi = require('../../api/campaign')
|
||||
const navigation = require('../../utils/navigation')
|
||||
const permission = require('../../utils/permission')
|
||||
const format = require('../../utils/format')
|
||||
const { markDirty } = require('../../utils/page-state')
|
||||
|
||||
const STATUS_OPTIONS = [
|
||||
{ label: '全部', value: '' },
|
||||
{ label: '启用', value: '1' },
|
||||
{ label: '停用', value: '0' }
|
||||
]
|
||||
|
||||
function safeList(response) {
|
||||
if (Array.isArray(response && response.list)) {
|
||||
return response.list
|
||||
}
|
||||
if (Array.isArray(response && response.records)) {
|
||||
return response.records
|
||||
}
|
||||
return []
|
||||
}
|
||||
|
||||
Page({
|
||||
data: {
|
||||
loading: false,
|
||||
list: [],
|
||||
total: 0,
|
||||
status: '',
|
||||
statusOptions: STATUS_OPTIONS,
|
||||
canManage: false,
|
||||
form: {
|
||||
title: '',
|
||||
scene: 'HOME',
|
||||
description: '',
|
||||
sortOrder: '0'
|
||||
}
|
||||
},
|
||||
|
||||
onShow() {
|
||||
if (!navigation.ensureLogin('进入活动管理')) {
|
||||
return
|
||||
}
|
||||
const permissionCodes = getApp().globalData.permissionCodes || []
|
||||
this.setData({
|
||||
canManage: permission.hasPermission(permissionCodes, 'campaign:manage')
|
||||
})
|
||||
this.loadCampaigns()
|
||||
},
|
||||
|
||||
onPullDownRefresh() {
|
||||
this.loadCampaigns().finally(() => {
|
||||
wx.stopPullDownRefresh()
|
||||
})
|
||||
},
|
||||
|
||||
async loadCampaigns() {
|
||||
this.setData({ loading: true })
|
||||
try {
|
||||
const response = await campaignApi.listCampaigns({
|
||||
page: 1,
|
||||
size: 20,
|
||||
status: this.data.status === '' ? undefined : Number(this.data.status)
|
||||
})
|
||||
this.setData({
|
||||
list: safeList(response).map(item => this.formatCampaign(item)),
|
||||
total: Number(response && response.total) || 0
|
||||
})
|
||||
} catch (error) {
|
||||
wx.showToast({
|
||||
title: error.message || '活动加载失败',
|
||||
icon: 'none'
|
||||
})
|
||||
} finally {
|
||||
this.setData({ loading: false })
|
||||
}
|
||||
},
|
||||
|
||||
formatCampaign(item) {
|
||||
return {
|
||||
...item,
|
||||
statusText: Number(item.status) === 0 ? '停用' : '启用',
|
||||
displayStartTime: format.formatDateTime(item.startTime),
|
||||
displayEndTime: format.formatDateTime(item.endTime)
|
||||
}
|
||||
},
|
||||
|
||||
handleStatusChange(event) {
|
||||
this.setData({
|
||||
status: event.currentTarget.dataset.status
|
||||
})
|
||||
this.loadCampaigns()
|
||||
},
|
||||
|
||||
handleFormInput(event) {
|
||||
const field = event.currentTarget.dataset.field
|
||||
if (!field) {
|
||||
return
|
||||
}
|
||||
this.setData({
|
||||
[`form.${field}`]: event.detail.value
|
||||
})
|
||||
},
|
||||
|
||||
async handleSaveCampaign() {
|
||||
if (!this.data.canManage) {
|
||||
wx.showToast({
|
||||
title: '当前账号没有活动管理权限',
|
||||
icon: 'none'
|
||||
})
|
||||
return
|
||||
}
|
||||
const form = this.data.form
|
||||
const title = String(form.title || '').trim()
|
||||
if (!title) {
|
||||
wx.showToast({
|
||||
title: '请填写活动标题',
|
||||
icon: 'none'
|
||||
})
|
||||
return
|
||||
}
|
||||
try {
|
||||
await campaignApi.saveCampaign({
|
||||
title,
|
||||
scene: String(form.scene || '').trim() || 'HOME',
|
||||
description: String(form.description || '').trim(),
|
||||
sortOrder: Number(form.sortOrder) || 0,
|
||||
status: 1
|
||||
})
|
||||
markDirty('admin-workbench')
|
||||
wx.showToast({
|
||||
title: '活动已创建',
|
||||
icon: 'none'
|
||||
})
|
||||
this.setData({
|
||||
form: {
|
||||
title: '',
|
||||
scene: 'HOME',
|
||||
description: '',
|
||||
sortOrder: '0'
|
||||
}
|
||||
})
|
||||
this.loadCampaigns()
|
||||
} catch (error) {
|
||||
wx.showToast({
|
||||
title: error.message || '活动保存失败',
|
||||
icon: 'none'
|
||||
})
|
||||
}
|
||||
},
|
||||
|
||||
handleBack() {
|
||||
navigation.goBack('/pages/manage/index')
|
||||
}
|
||||
})
|
||||
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"usingComponents": {
|
||||
"navigation-bar": "/admin/components/navigation-bar/navigation-bar"
|
||||
},
|
||||
"enablePullDownRefresh": true
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
<navigation-bar title="活动管理" back="{{true}}" bindback="handleBack" color="#f6efe7" background="#081518"></navigation-bar>
|
||||
|
||||
<view class="page-shell">
|
||||
<view class="page-stack">
|
||||
<view class="hero-panel">
|
||||
<text class="hero-kicker">Campaign</text>
|
||||
<text class="hero-title">活动管理</text>
|
||||
<text class="hero-desc">查看营销活动和推荐位配置,支持在手机端快速创建启用活动。</text>
|
||||
</view>
|
||||
|
||||
<view wx:if="{{canManage}}" class="surface-card">
|
||||
<text class="section-title">快速创建</text>
|
||||
<input class="field-input compact-field" placeholder="活动标题" placeholder-class="placeholder" value="{{form.title}}" data-field="title" bindinput="handleFormInput"></input>
|
||||
<view class="form-grid">
|
||||
<input class="field-input" placeholder="场景,如 HOME" placeholder-class="placeholder" value="{{form.scene}}" data-field="scene" bindinput="handleFormInput"></input>
|
||||
<input class="field-input" type="number" placeholder="排序" placeholder-class="placeholder" value="{{form.sortOrder}}" data-field="sortOrder" bindinput="handleFormInput"></input>
|
||||
</view>
|
||||
<textarea class="field-textarea compact-textarea" placeholder="活动说明,可留空" placeholder-class="placeholder" value="{{form.description}}" data-field="description" bindinput="handleFormInput"></textarea>
|
||||
<button class="primary-btn compact-btn" loading="{{loading}}" bindtap="handleSaveCampaign">创建活动</button>
|
||||
</view>
|
||||
|
||||
<view class="surface-card">
|
||||
<text class="section-title">活动列表</text>
|
||||
<view class="chip-row">
|
||||
<block wx:for="{{statusOptions}}" wx:key="value">
|
||||
<view class="chip-btn {{status === item.value ? 'active' : ''}}" data-status="{{item.value}}" bindtap="handleStatusChange">{{item.label}}</view>
|
||||
</block>
|
||||
</view>
|
||||
<text class="section-desc">共 {{total}} 条活动</text>
|
||||
</view>
|
||||
|
||||
<block wx:for="{{list}}" wx:key="id">
|
||||
<view class="list-card">
|
||||
<view class="list-head">
|
||||
<view>
|
||||
<text class="list-title">{{item.title}}</text>
|
||||
<text class="list-subtitle">{{item.scene || '未设置场景'}} · 排序 {{item.sortOrder || 0}}</text>
|
||||
</view>
|
||||
<text class="{{item.status === 0 ? 'soft-badge' : 'success-badge'}}">{{item.statusText}}</text>
|
||||
</view>
|
||||
<view wx:if="{{item.description}}" class="hint-card">{{item.description}}</view>
|
||||
<view class="meta-grid">
|
||||
<view class="meta-item">
|
||||
<text class="meta-label">开始</text>
|
||||
<text class="meta-value">{{item.displayStartTime || '--'}}</text>
|
||||
</view>
|
||||
<view class="meta-item">
|
||||
<text class="meta-label">结束</text>
|
||||
<text class="meta-value">{{item.displayEndTime || '--'}}</text>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</block>
|
||||
|
||||
<view wx:if="{{!list.length && !loading}}" class="empty-state">
|
||||
<text class="empty-title">暂无活动</text>
|
||||
<text class="empty-desc">当前筛选条件下没有营销活动。</text>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
@@ -1,21 +0,0 @@
|
||||
@import "../../app.wxss";
|
||||
.page-shell {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.compact-field,
|
||||
.compact-btn,
|
||||
.compact-textarea {
|
||||
margin-top: 16rpx;
|
||||
}
|
||||
|
||||
.form-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 14rpx;
|
||||
margin-top: 16rpx;
|
||||
}
|
||||
|
||||
.compact-textarea {
|
||||
min-height: 140rpx;
|
||||
}
|
||||
@@ -1,143 +0,0 @@
|
||||
/**
|
||||
* Purpose: commentApi supports index.js by holding or executing the comment api page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const commentApi = require('../../api/comment')
|
||||
|
||||
Page({
|
||||
/**
|
||||
* Purpose: data supports index.js by holding or executing the data page or API role.
|
||||
* Usage: import, call, read, or update this page-data from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
data: {
|
||||
/**
|
||||
* Purpose: loading supports index.js by holding or executing the loading page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
loading: false,
|
||||
/**
|
||||
* Purpose: keyword supports index.js by holding or executing the keyword page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
keyword: '',
|
||||
/**
|
||||
* Purpose: comments supports index.js by holding or executing the comments page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
comments: []
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: onShow supports index.js by holding or executing the on show page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
onShow() {
|
||||
this.loadComments()
|
||||
},
|
||||
|
||||
async onPullDownRefresh() {
|
||||
await this.loadComments()
|
||||
wx.stopPullDownRefresh()
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: handleKeywordInput supports index.js by holding or executing the handle keyword input page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
handleKeywordInput(event) {
|
||||
this.setData({
|
||||
/**
|
||||
* Purpose: keyword supports index.js by holding or executing the keyword page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
keyword: event.detail.value
|
||||
})
|
||||
},
|
||||
|
||||
async loadComments() {
|
||||
this.setData({ loading: true })
|
||||
try {
|
||||
const comments = await commentApi.listComments({
|
||||
/**
|
||||
* Purpose: keyword supports index.js by holding or executing the keyword page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
keyword: this.data.keyword || undefined
|
||||
})
|
||||
this.setData({
|
||||
/**
|
||||
* Purpose: comments supports index.js by holding or executing the comments page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
comments: Array.isArray(comments) ? comments : []
|
||||
})
|
||||
} catch (error) {
|
||||
wx.showToast({
|
||||
/**
|
||||
* Purpose: title supports index.js by holding or executing the title page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
title: error.message || '评论加载失败',
|
||||
/**
|
||||
* Purpose: icon supports index.js by holding or executing the icon page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
icon: 'none'
|
||||
})
|
||||
} finally {
|
||||
this.setData({ loading: false })
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: handleSearch supports index.js by holding or executing the handle search page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
handleSearch() {
|
||||
this.loadComments()
|
||||
},
|
||||
|
||||
/**
|
||||
* Purpose: handleDelete supports index.js by holding or executing the handle delete page or API role.
|
||||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
handleDelete(event) {
|
||||
const id = event.currentTarget.dataset.id
|
||||
if (!id) {
|
||||
return
|
||||
}
|
||||
wx.showModal({
|
||||
/**
|
||||
* Purpose: title supports index.js by holding or executing the title page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
title: '删除评论',
|
||||
/**
|
||||
* Purpose: content supports index.js by holding or executing the content page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
content: '确认删除这条评论?',
|
||||
/**
|
||||
* Purpose: confirmText supports index.js by holding or executing the confirm text page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
confirmText: '删除',
|
||||
/**
|
||||
* Purpose: success supports index.js by holding or executing the success page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
success: async res => {
|
||||
if (!res.confirm) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
await commentApi.deleteComment(id)
|
||||
wx.showToast({ title: '评论已删除', icon: 'none' })
|
||||
this.loadComments()
|
||||
} catch (error) {
|
||||
wx.showToast({ title: error.message || '删除失败', icon: 'none' })
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -1 +0,0 @@
|
||||
{}
|
||||
@@ -1,21 +0,0 @@
|
||||
<navigation-bar title="评论管理" showBack="{{true}}" background="#081518" color="#ffffff"></navigation-bar>
|
||||
|
||||
<view class="page">
|
||||
<view class="search-row">
|
||||
<input class="search-input" placeholder="搜索评论内容" value="{{keyword}}" bindinput="handleKeywordInput" confirm-type="search" bindconfirm="handleSearch" />
|
||||
<view class="search-btn" bindtap="handleSearch">搜索</view>
|
||||
</view>
|
||||
|
||||
<view wx:if="{{!comments.length && !loading}}" class="empty">暂无评论</view>
|
||||
|
||||
<view wx:for="{{comments}}" wx:key="id" class="comment-card">
|
||||
<view class="comment-head">
|
||||
<text class="comment-user">{{item.userNickname || '用户'}}</text>
|
||||
<text class="comment-time">{{item.createTime}}</text>
|
||||
</view>
|
||||
<view class="comment-content">{{item.commentContent}}</view>
|
||||
<view wx:if="{{item.parentCommentContent}}" class="reply-content">回复:{{item.parentCommentContent}}</view>
|
||||
<view class="comment-meta">{{item.productTitle || '作品'}} · {{item.shopName || '门店'}}</view>
|
||||
<view class="delete-btn" data-id="{{item.id}}" bindtap="handleDelete">删除</view>
|
||||
</view>
|
||||
</view>
|
||||
@@ -1,95 +0,0 @@
|
||||
@import "../../app.wxss";
|
||||
.page {
|
||||
min-height: 100vh;
|
||||
padding: 28rpx 24rpx 60rpx;
|
||||
background: #0c181b;
|
||||
}
|
||||
|
||||
.search-row {
|
||||
display: flex;
|
||||
gap: 16rpx;
|
||||
margin-bottom: 24rpx;
|
||||
}
|
||||
|
||||
.search-input {
|
||||
flex: 1;
|
||||
height: 76rpx;
|
||||
padding: 0 24rpx;
|
||||
border-radius: 18rpx;
|
||||
background: #132529;
|
||||
color: #ffffff;
|
||||
font-size: 26rpx;
|
||||
}
|
||||
|
||||
.search-btn {
|
||||
width: 128rpx;
|
||||
height: 76rpx;
|
||||
line-height: 76rpx;
|
||||
text-align: center;
|
||||
border-radius: 18rpx;
|
||||
background: #f07e57;
|
||||
color: #ffffff;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.empty {
|
||||
padding: 80rpx 0;
|
||||
text-align: center;
|
||||
color: #7e8f8c;
|
||||
}
|
||||
|
||||
.comment-card {
|
||||
margin-bottom: 18rpx;
|
||||
padding: 24rpx;
|
||||
border-radius: 20rpx;
|
||||
background: #132529;
|
||||
color: #dce7e4;
|
||||
}
|
||||
|
||||
.comment-head {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 16rpx;
|
||||
}
|
||||
|
||||
.comment-user {
|
||||
font-size: 28rpx;
|
||||
font-weight: 700;
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
.comment-time,
|
||||
.comment-meta {
|
||||
font-size: 22rpx;
|
||||
color: #7e8f8c;
|
||||
}
|
||||
|
||||
.comment-content {
|
||||
margin-top: 16rpx;
|
||||
font-size: 26rpx;
|
||||
line-height: 1.8;
|
||||
}
|
||||
|
||||
.reply-content {
|
||||
margin-top: 12rpx;
|
||||
padding: 16rpx;
|
||||
border-radius: 16rpx;
|
||||
background: #0c181b;
|
||||
color: #a9bbb6;
|
||||
font-size: 24rpx;
|
||||
}
|
||||
|
||||
.comment-meta {
|
||||
margin-top: 14rpx;
|
||||
}
|
||||
|
||||
.delete-btn {
|
||||
margin-top: 18rpx;
|
||||
width: 120rpx;
|
||||
height: 56rpx;
|
||||
line-height: 56rpx;
|
||||
text-align: center;
|
||||
border-radius: 999rpx;
|
||||
color: #ffffff;
|
||||
background: #d95f5f;
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
const couponApi = require('../../api/coupon')
|
||||
const userApi = require('../../api/user')
|
||||
const navigation = require('../../utils/navigation')
|
||||
const { getTempRecord, clearTempRecord } = require('../../utils/storage')
|
||||
|
||||
Page({
|
||||
data: {
|
||||
coupon: null,
|
||||
users: [],
|
||||
quantity: 1
|
||||
},
|
||||
|
||||
onLoad() {
|
||||
const coupon = getTempRecord('currentCoupon', null)
|
||||
this.setData({
|
||||
coupon
|
||||
})
|
||||
this.loadUsers()
|
||||
},
|
||||
|
||||
onUnload() {
|
||||
clearTempRecord('currentCoupon')
|
||||
},
|
||||
|
||||
async loadUsers() {
|
||||
try {
|
||||
const users = await userApi.listAllUsers()
|
||||
this.setData({
|
||||
users: (Array.isArray(users) ? users : []).map(item => ({
|
||||
...item,
|
||||
valueId: String(item.id),
|
||||
checked: false
|
||||
}))
|
||||
})
|
||||
} catch (error) {
|
||||
wx.showToast({
|
||||
title: error.message || '可发放用户加载失败',
|
||||
icon: 'none'
|
||||
})
|
||||
}
|
||||
},
|
||||
|
||||
handleUserCheck(event) {
|
||||
const selected = event.detail.value || []
|
||||
this.setData({
|
||||
users: this.data.users.map(item => ({
|
||||
...item,
|
||||
checked: selected.includes(item.valueId)
|
||||
}))
|
||||
})
|
||||
},
|
||||
|
||||
handleQuantityInput(event) {
|
||||
this.setData({
|
||||
quantity: event.detail.value
|
||||
})
|
||||
},
|
||||
|
||||
async handleSubmit() {
|
||||
const selectedUserIds = this.data.users.filter(item => item.checked).map(item => Number(item.id))
|
||||
if (!selectedUserIds.length) {
|
||||
wx.showToast({
|
||||
title: '请至少选择一个用户',
|
||||
icon: 'none'
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
await couponApi.distributeCoupon({
|
||||
couponId: this.data.coupon.id,
|
||||
userIds: selectedUserIds,
|
||||
quantity: Number(this.data.quantity || 1)
|
||||
})
|
||||
wx.showToast({
|
||||
title: '优惠券已发放',
|
||||
icon: 'none'
|
||||
})
|
||||
navigation.goBack('/pages/coupons/index')
|
||||
} catch (error) {
|
||||
wx.showToast({
|
||||
title: error.message || '发放失败',
|
||||
icon: 'none'
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -1,5 +0,0 @@
|
||||
{
|
||||
"usingComponents": {
|
||||
"navigation-bar": "/admin/components/navigation-bar/navigation-bar"
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
<navigation-bar title="发放优惠券" back="{{true}}" color="#f6efe7" background="#081518"></navigation-bar>
|
||||
|
||||
<view class="page-shell">
|
||||
<view class="page-stack">
|
||||
<view class="surface-card" wx:if="{{coupon}}">
|
||||
<text class="section-title">{{coupon.couponName}}</text>
|
||||
<text class="section-desc">选择用户后批量发放,数量默认 1。移动端只保留高频发放能力,不把 Web 的宽表格搬过来。</text>
|
||||
<view class="field-group">
|
||||
<text class="field-label">发放数量</text>
|
||||
<input class="field-input" type="number" value="{{quantity}}" bindinput="handleQuantityInput"></input>
|
||||
</view>
|
||||
<view class="field-group">
|
||||
<text class="field-label">选择用户</text>
|
||||
<checkbox-group bindchange="handleUserCheck">
|
||||
<block wx:for="{{users}}" wx:key="id">
|
||||
<label class="checkbox-chip {{item.checked ? 'active' : ''}}">
|
||||
<checkbox value="{{item.valueId}}" checked="{{item.checked}}" />
|
||||
{{item.nickname || item.account}}
|
||||
</label>
|
||||
</block>
|
||||
</checkbox-group>
|
||||
</view>
|
||||
<view class="action-row">
|
||||
<button class="primary-btn" bindtap="handleSubmit">确认发放</button>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
@@ -1,5 +0,0 @@
|
||||
@import "../../app.wxss";
|
||||
checkbox {
|
||||
transform: scale(0.75);
|
||||
margin-right: 8rpx;
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user