把可拼装的排到前面,再根据发布时间排序

This commit is contained in:
lxp
2026-11-02 14:45:18 +08:00
parent d5624c5f0d
commit 556dab4377
12 changed files with 372 additions and 28 deletions
+20 -3
View File
@@ -355,7 +355,7 @@ interface ProjectView {
repoStatus: RepoStatus;
publishStatus: PublishStatus;
publishedCommitSha: string | null;
publishedAt: ShanghaiDateTime | null;
publishedAt: ShanghaiDateTime | null; // 后台可编辑;发布时仅在为空时填充
sourceProjectCode: string | null;
sourceCommitSha: string | null;
likeCount: number;
@@ -438,8 +438,19 @@ interface TypeView {
| publishStatus | UNPUBLISHED / PUBLISHED / BLOCKED |
| repoStatus | CREATING / READY / FAILED |
| moderationStatus | NORMAL / BLOCKED |
| sort | 可选:`CREATED_AT_DESC`(默认)、`PUBLISHED_AT_DESC`、`RESOURCES_FIRST`;其他值返回 400 |
结果只包含未删除项目,按创建时间倒序。没有 `creationSource` 筛选,也没有已删除项目回收站。
结果只包含未删除项目。排序模式:
| sort | 排序规则 |
| --- | --- |
| CREATED_AT_DESC | 创建时间倒序 |
| PUBLISHED_AT_DESC | 发布时间倒序,NULL 排最后 |
| RESOURCES_FIRST | 四项资源齐全的项目优先,各组内按发布时间倒序,组内 NULL 排最后 |
资源齐全指 `model_glb_object_key`、`assembly_json_object_key`、`walking_resources_prefix`、`model_parts_prefix` 全部非 NULL 且非空字符串。`RESOURCES_FIRST` 下,资源齐全但无发布时间的项目仍排在资源不齐全的项目前面。各模式同值时均有固定顺序,先排序再分页。没有 `creationSource` 筛选,也没有已删除项目回收站。
请求示例:`GET /admin-api/projects?page=1&size=20&sort=RESOURCES_FIRST`;仅按发布时间排序使用 `sort=PUBLISHED_AT_DESC`。
`GET /admin-api/projects/{projectCode}` → `ManagedProjectView`,示例 data:
@@ -507,7 +518,8 @@ interface TypeView {
"name": "社区机器人 V2",
"description": "更新后的说明",
"projectType": "WHEELED",
"coverUrl": ""
"coverUrl": "",
"publishedAt": "2026-11-02T10:30:00.000"
}
```
@@ -517,9 +529,12 @@ interface TypeView {
| description | 最多 2000 字符;省略或 null 会保存为空字符串 |
| projectType | 必填,来自类型接口,最多 64 字符 |
| coverUrl | 可空,HTTPS 地址最多 2048 字符;编辑时省略/null 保留旧封面,传 `""` 清空 |
| publishedAt | 可选,上海时间字符串,无时区后缀;省略保留原值,传 `null` 清空,传时间字符串更新;格式错误返回 400 |
虽然方法为 PATCH,**name、projectType 仍必须传**。编辑表单应提交当前完整基础信息,避免只传一个字段或意外清空 description。基础信息保存后直接生效;发布 Commit 主要固定 Git 文件版本。
`publishedAt` 复用现有发布时间字段,仅后台允许编辑。清空时提交 `"publishedAt": null`,修改后直接影响列表排序,不改变项目发布状态或已发布文件版本。
`DELETE /admin-api/projects/{projectCode}`,无 body → `null`。前端二次确认后调用,成功返回列表并刷新。逻辑删除且社区不可见,无恢复接口。
### 5.5 发布、撤回、下架
@@ -535,6 +550,8 @@ interface TypeView {
文件提交不会自动更新社区已发布版本。已发布项目可以继续编辑文件,明确再次发布后才更新公开文件快照。
发布时仅在 `publishedAt` 为空时填入当前上海时间;已有值(包括管理员手动设置的时间)会保留。管理员清空后,下次发布会重新填充当前时间。
| 状态 | 建议操作 |
| --- | --- |
| repoStatus 非 READY | 展示准备中/失败及迁移任务;不开放目录、文件提交和发布 |
+4 -4
View File
@@ -222,7 +222,7 @@ export interface Project {
repoStatus: 'CREATING' | 'READY' | 'FAILED';
publishStatus: 'UNPUBLISHED' | 'PUBLISHED' | 'BLOCKED';
publishedCommitSha: string | null;
publishedAt: ShanghaiDateTime | null;
publishedAt: ShanghaiDateTime | null; // 仅后台可编辑;发布时仅在为空时填充
sourceProjectCode: string | null;
sourceCommitSha: string | null;
sourceRepositoryUrl: string | null; // 在线迁移任务记录的原仓库地址
@@ -351,7 +351,7 @@ export interface Comment {
| publishStatus = UNPUBLISHED | 当前不在社区展示;这是私有项目状态,不是草稿 |
| publishStatus = PUBLISHED | 当前在社区展示 |
| publishStatus = BLOCKED | 管理员下架,不在社区展示;普通撤回不会解除此状态,只有管理员可解除 |
| publishedCommitSha / publishedAt | 撤回后可能仍保留上一次发布值,是否公开必须判断 publishStatus |
| publishedCommitSha / publishedAt | 撤回后可能仍保留;发布时间可由后台编辑,是否公开必须判断 publishStatus |
| sourceProjectCode / sourceCommitSha | Fork 来源及复制的源版本;普通新项目为 null |
| liked | 当前请求用户是否点赞,匿名访问为 false |
| coverUrl | 固定公开封面地址,null 时展示前端默认图;工作区、社区、Fork 和 AI 卡片共用此字段 |
@@ -462,7 +462,7 @@ data 示例中 image 仅展示格式前缀,实际值为完整图片:
请求示例:`GET /api/community/projects?page=1&size=20&type=GENERAL&keyword=机器人`。使用 URLSearchParams 编码中文等查询值。
成功 data 为 PageResult<Project>。工作区按创建时间倒序;社区优先展示已上传并确认绑定 URDF 的项目,同组内按最近发布时间倒序,排序后分页。不支持客户端指定排序。更换类型或关键词时,把 page 重置为 1。
成功 data 为 PageResult<Project>。工作区按创建时间倒序;社区先展示四项资源齐全的项目,再在各组内按 `publishedAt` 倒序,组内发布时间为 NULL 的排最后。资源齐全指 `model_glb_object_key`、`assembly_json_object_key`、`walking_resources_prefix`、`model_parts_prefix` 全部非 NULL 且非空字符串,对应返回的 `modelGlbUrl`、`assemblyJsonUrl`、`walkingResourcesBaseUrl`、`modelPartsBaseUrl`。资源齐全但无发布时间的项目仍排在资源不齐全的项目前面,URDF 不再影响优先级。时间相同时顺序固定,先排序再分页。不支持客户端指定排序。更换类型或关键词时,把 page 重置为 1。
## 我的项目管理
@@ -938,7 +938,7 @@ data 为 PageResult<HistoryEntry>,只读取 main 的历史,不提供
}
```
commitSha 必须为当前 main 的完整 SHA,不能发布历史提交。成功 data 为 Project,publishStatus=PUBLISHED,publishedCommitSha 为提交的版本,publishedAt 更新为本次发布时间。
commitSha 必须为当前 main 的完整 SHA,不能发布历史提交。成功 data 为 Project,publishStatus=PUBLISHED,publishedCommitSha 为提交的版本。`publishedAt` 仅在为空时填入当前上海时间;已有值会保留,再次发布不会覆盖。后台可以手动修改或清空发布时间,普通用户创建和编辑项目不能修改该字段。
同一路径用于首次发布和以后手动更新社区版本。发布后继续提交、上传或创建目录,都不会自动更新社区代码。需要更新时,取得最新工作区 SHA,再调用此接口。项目名称、描述和类型的修改直接更新展示。
@@ -36,7 +36,8 @@ public class AdminProjectController {
@RequestParam(required = false) String keyword,
@RequestParam(required = false) String publishStatus,
@RequestParam(required = false) String repoStatus,
@RequestParam(required = false) String moderationStatus) {
@RequestParam(required = false) String moderationStatus,
@RequestParam(defaultValue = "CREATED_AT_DESC") String sort) {
return ApiResponse.success(
management.projects(
page,
@@ -46,7 +47,8 @@ public class AdminProjectController {
keyword,
publishStatus,
repoStatus,
moderationStatus));
moderationStatus,
sort));
}
@GetMapping("/types")
@@ -66,8 +68,8 @@ public class AdminProjectController {
@PatchMapping("/{projectCode}")
public ApiResponse<ProjectView> update(
@PathVariable String projectCode, @Valid @RequestBody ProjectInput input) {
return ApiResponse.success(projects.update(0, projectCode, input));
@PathVariable String projectCode, @Valid @RequestBody UpdateProjectInput input) {
return ApiResponse.success(projects.updateByAdmin(projectCode, input));
}
@DeleteMapping("/{projectCode}")
@@ -53,6 +53,6 @@ public class AdminUserController {
@RequestParam(defaultValue = "1") long page,
@RequestParam(defaultValue = "20") long size) {
return ApiResponse.success(
service.projects(page, size, userCode, null, null, null, null, null));
service.projects(page, size, userCode, null, null, null, null, null, null));
}
}
@@ -0,0 +1,31 @@
package com.linkerbot.vibemake.adminapi;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import com.linkerbot.vibemake.adminapi.controller.AdminStepController;
import com.linkerbot.vibemake.common.ApiResponse;
import com.linkerbot.vibemake.common.RequestTooLargeException;
import com.linkerbot.vibemake.service.admin.AdminStepService;
import org.junit.jupiter.api.Test;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.mock.http.MockHttpInputMessage;
class AdminStepControllerTest {
@Test
void jsonParsingErrorsKeepRequestBodyLimitSeparateFromInvalidFileParameters() {
AdminStepController controller = new AdminStepController(mock(AdminStepService.class));
HttpMessageNotReadableException oversized = new HttpMessageNotReadableException("读取失败",
new RuntimeException(new RequestTooLargeException()), new MockHttpInputMessage(new byte[0]));
ResponseEntity<ApiResponse<Object>> response = controller.invalidJson(oversized);
assertThat(response.getStatusCode().value()).isEqualTo(413);
assertThat(response.getBody().code()).isEqualTo("REQUEST_TOO_LARGE");
assertThat(response.getHeaders().getCacheControl()).isEqualTo("no-store");
HttpMessageNotReadableException invalid = new HttpMessageNotReadableException(
"大小不是整数", new MockHttpInputMessage(new byte[0]));
ResponseEntity<ApiResponse<Object>> invalidResponse = controller.invalidJson(invalid);
assertThat(invalidResponse.getStatusCode().value()).isEqualTo(400);
assertThat(invalidResponse.getBody().code()).isEqualTo("STEP_INVALID_FILE");
}
}
@@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.*;
import com.linkerbot.vibemake.adminapi.security.AdminAuthService;
import com.linkerbot.vibemake.bean.entity.*;
import com.linkerbot.vibemake.common.BusinessException;
import com.linkerbot.vibemake.common.ProjectListingFixtures;
import com.linkerbot.vibemake.security.TokenService;
import com.linkerbot.vibemake.service.*;
import com.linkerbot.vibemake.service.admin.AdminImportService;
@@ -177,6 +178,90 @@ class AdminWorkflowTest {
.asText();
}
@Test
void publicationTimeCanBeSetOmittedClearedAndIsProtectedFromOrdinaryUsers() throws Exception {
String code = createProject();
String endpoint = "/admin-api/projects/" + code;
String sha = request(signed(get(endpoint + "/tree")), 200).path("data").path("commitSha").asText();
JsonNode published = request(signed(body(put(endpoint + "/publication"),
Map.of("commitSha", sha))), 200).path("data");
assertThat(published.path("publishedAt").isTextual()).isTrue();
String manualTime = "2020-01-02T03:04:05.123";
Map<String, Object> input = new HashMap<>(metadata());
input.put("publishedAt", manualTime);
// 请求不能伪造字段存在标记来绕过实际 publishedAt 的提交语义。
input.put("publishedAtProvided", false);
JsonNode edited = request(signed(body(patch(endpoint), input)), 200).path("data");
assertThat(edited.path("publishedAt").asText()).isEqualTo(manualTime);
for (String field : List.of("publishStatus", "publishedCommitSha"))
assertThat(edited.path(field)).isEqualTo(published.path(field));
Map<String, Object> omitted = new HashMap<>(metadata());
omitted.put("publishedAtProvided", true);
assertThat(request(signed(body(patch(endpoint), omitted)), 200)
.path("data").path("publishedAt").asText()).isEqualTo(manualTime);
assertThat(request(signed(body(put(endpoint + "/publication"), Map.of("commitSha", sha))), 200)
.path("data").path("publishedAt").asText()).isEqualTo(manualTime);
for (Object invalid : List.of("not-a-time", "", "2026-11-02T10:30:00Z", 123,
List.of(2026, 11, 2, 10, 30))) {
input.put("publishedAt", invalid);
request(signed(body(patch(endpoint), input)), 400);
}
request(signed(body(patch(endpoint), Map.of("publishedAt", manualTime))), 400);
assertThat(request(signed(get(endpoint)), 200).path("data").path("project")
.path("publishedAt").asText()).isEqualTo(manualTime);
input.put("publishedAt", null);
JsonNode cleared = request(signed(body(patch(endpoint), input)), 200).path("data");
assertThat(cleared.path("publishedAt").isNull()).isTrue();
for (String field : List.of("publishStatus", "publishedCommitSha"))
assertThat(cleared.path(field)).isEqualTo(published.path(field));
assertThat(jdbc.queryForObject("SELECT published_at FROM project WHERE project_code=?",
java.time.LocalDateTime.class, code)).isNull();
assertThat(request(signed(body(put(endpoint + "/publication"), Map.of("commitSha", sha))), 200)
.path("data").path("publishedAt").isTextual()).isTrue();
String ordinaryToken = tokens.issue(ordinary.getId(), ordinary.getSessionVersion());
request(body(patch(endpoint), input).header("Authorization", "Bearer " + ordinaryToken), 403);
assertThatThrownBy(() -> projectService.updateByAdmin(code,
json.convertValue(input, com.linkerbot.vibemake.bean.AdminContracts.UpdateProjectInput.class)))
.isInstanceOf(BusinessException.class).hasMessageContaining("仅限后台管理员");
}
@Test
void projectListSupportsAllSortModesWithStablePaginationAndFilters() throws Exception {
String template = createProject();
ProjectListingFixtures.Fixture fixture = ProjectListingFixtures.create(dataSource, template);
jdbc.update("UPDATE project SET deleted=1 WHERE project_code=?", template);
Map<String, List<String>> orders = Map.of(
"CREATED_AT_DESC", fixture.createdOrder(),
"PUBLISHED_AT_DESC", fixture.publishedOrder(),
"RESOURCES_FIRST", fixture.resourcesOrder());
for (Map.Entry<String, List<String>> entry : orders.entrySet()) {
List<String> actual = new ArrayList<>();
for (int page = 1; page <= 4; page++) {
JsonNode data = request(signed(get("/admin-api/projects")
.param("sort", entry.getKey()).param("page", Integer.toString(page)).param("size", "3")
.param("type", "WHEELED").param("keyword", "排序测试")
.param("publishStatus", "PUBLISHED").param("repoStatus", "READY")
.param("moderationStatus", "NORMAL")), 200).path("data");
assertThat(data.path("total").asLong()).isEqualTo(10);
for (JsonNode item : data.path("items"))
actual.add(item.path("project").path("projectCode").asText());
}
assertThat(actual).as(entry.getKey()).containsExactlyElementsOf(entry.getValue());
}
JsonNode defaults = request(signed(get("/admin-api/projects")), 200).path("data").path("items");
assertThat(defaults).extracting(p -> p.path("project").path("projectCode").asText())
.containsExactlyElementsOf(fixture.createdOrder());
assertThat(request(signed(get("/admin-api/projects").param("sort", "RESOURCES_FIRST")
.param("ownerUserCode", ordinary.getUserCode())), 200)
.path("data").path("total").asLong()).isZero();
assertThat(request(signed(get("/admin-api/projects").param("sort", "PUBLISHED_AT_DESC")
.param("moderationStatus", "BLOCKED")), 200)
.path("data").path("total").asLong()).isZero();
for (String invalid : List.of("unknown", "published_at DESC", "id; DROP TABLE project"))
request(signed(get("/admin-api/projects").param("sort", invalid)), 400);
}
private MockHttpServletRequestBuilder uploadRequest(String code, String sha) {
return signed(multipart("/admin-api/projects/" + code + "/uploads/commit")
.file(new MockMultipartFile("files", "sample.txt", "text/plain", "hello".getBytes()))
@@ -8,6 +8,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linkerbot.vibemake.common.BusinessException;
import com.linkerbot.vibemake.common.ProjectListingFixtures;
import com.linkerbot.vibemake.security.CaptchaService;
import com.linkerbot.vibemake.service.admin.AdminProjectResourceService;
import com.linkerbot.vibemake.service.support.ProjectActors;
@@ -205,6 +206,68 @@ class WorkflowTest {
200);
}
@Test
void communitySortsCompleteResourcesBeforePublicationTimeAndPaginatesStably() throws Exception {
String owner = login("project-sorting@example.invalid");
String template = create(owner, "列表模板");
ProjectListingFixtures.Fixture fixture = ProjectListingFixtures.create(jdbc.getDataSource(), template);
jdbc.update("UPDATE project SET deleted=1 WHERE project_code=?", template);
String urdfOnly = fixture.resourcesOrder().getLast();
jdbc.update("UPDATE project SET urdf_main_object_key=? WHERE project_code=?",
"/urdf/" + urdfOnly + "/robot.urdf", urdfOnly);
List<String> actual = new ArrayList<>();
for (int page = 1; page <= 4; page++) {
JsonNode data = perform(get("/api/community/projects")
.param("page", Integer.toString(page)).param("size", "3")
.param("type", "GENERAL").param("keyword", "排序测试"), 200).path("data");
assertThat(data.path("total").asLong()).isEqualTo(10);
for (JsonNode project : data.path("items")) {
assertThat(project.has("id")).isFalse();
actual.add(project.path("projectCode").asText());
}
}
assertThat(actual).containsExactlyElementsOf(fixture.resourcesOrder());
JsonNode workspace = perform(auth(get("/api/workspace/projects"), owner)
.param("size", "20"), 200).path("data");
assertThat(workspace.path("items")).extracting(p -> p.path("projectCode").asText())
.containsExactlyElementsOf(fixture.createdOrder());
assertThat(perform(get("/api/community/projects").param("type", "ROBOTIC_ARM"), 200)
.path("data").path("total").asLong()).isZero();
}
@Test
void workspaceCannotEditPublicationTimeAndRepublishingKeepsExistingTime() throws Exception {
String owner = login("publication-time@example.invalid");
String code = create(owner, "发布时间测试");
String endpoint = "/api/workspace/projects/" + code;
String sha = head(owner, code);
assertThat(perform(auth(get(endpoint), owner), 200).path("data").path("publishedAt").isNull())
.isTrue();
publish(owner, code, sha);
assertThat(perform(auth(get(endpoint), owner), 200).path("data").path("publishedAt").isTextual())
.isTrue();
String manualTime = "2020-01-02T03:04:05.123";
jdbc.update("UPDATE project SET published_at=? WHERE project_code=?", manualTime, code);
Map<String, Object> input = new HashMap<>(Map.of(
"name", "发布时间测试", "projectType", "GENERAL", "description", "普通用户编辑"));
input.put("publishedAt", "2030-01-01T00:00:00");
input.put("publishedAtProvided", true);
JsonNode updated = perform(body(auth(patch(endpoint), owner), input), 200).path("data");
assertThat(updated.path("publishedAt").asText()).isEqualTo(manualTime);
input.put("publishedAt", null);
perform(body(auth(patch(endpoint), owner), input), 200);
String nextSha = commit(owner, code, sha, "再次发布测试");
publish(owner, code, nextSha);
JsonNode republished = perform(auth(get(endpoint), owner), 200).path("data");
assertThat(republished.path("publishedAt").asText()).isEqualTo(manualTime);
assertThat(republished.path("publishedCommitSha").asText()).isEqualTo(nextSha);
jdbc.update("UPDATE project SET published_at=NULL WHERE project_code=?", code);
publish(owner, code, nextSha);
JsonNode filledTime = perform(auth(get(endpoint), owner), 200).path("data").path("publishedAt");
assertThat(filledTime.isTextual()).isTrue();
assertThat(filledTime.asText()).isNotEqualTo(manualTime);
}
@Test
void crossOriginLoginDownloadsAndBusinessErrorsKeepCorsHeaders() throws Exception {
String origin = "https://dev-vibemake.robotquan.com";
@@ -1,5 +1,13 @@
package com.linkerbot.vibemake.bean;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonSetter;
import com.fasterxml.jackson.annotation.Nulls;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.linkerbot.vibemake.bean.Contracts.ProjectInput;
import com.linkerbot.vibemake.bean.Contracts.ProjectView;
import com.linkerbot.vibemake.bean.Contracts.UrdfConfirmInput;
@@ -8,7 +16,12 @@ import com.linkerbot.vibemake.bean.Contracts.UrdfFile;
import jakarta.validation.Valid;
import jakarta.validation.constraints.*;
import lombok.Getter;
import lombok.Setter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeParseException;
import java.util.List;
public final class AdminContracts {
@@ -43,6 +56,53 @@ public final class AdminContracts {
public record CreateProjectInput(String ownerUserCode, @NotNull @Valid ProjectInput project) {}
@Getter
public static final class UpdateProjectInput {
@Setter @NotBlank @Size(max = 100)
private String name;
@Setter @Size(max = 2000)
private String description;
@Setter @NotBlank @Size(max = 64)
private String projectType;
@Setter
private String coverUrl;
@JsonDeserialize(using = PublishedAtDeserializer.class)
private LocalDateTime publishedAt;
@JsonIgnore
private boolean publishedAtProvided;
// 区分省略字段与显式 null,避免编辑基础信息时意外清空发布时间。
@JsonSetter(value = "publishedAt", nulls = Nulls.SET)
public void setPublishedAt(LocalDateTime publishedAt) {
this.publishedAt = publishedAt;
this.publishedAtProvided = true;
}
public ProjectInput project() {
return new ProjectInput(name, description, projectType, coverUrl);
}
}
/** 只接受本地时间字符串,避免空字符串被 Jackson 自动转换成清空操作。 */
public static final class PublishedAtDeserializer extends JsonDeserializer<LocalDateTime> {
@Override
public LocalDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException {
if (!parser.hasToken(JsonToken.VALUE_STRING))
return (LocalDateTime) context.handleUnexpectedToken(LocalDateTime.class, parser);
String value = parser.getText();
try {
return LocalDateTime.parse(value);
} catch (DateTimeParseException error) {
throw context.weirdStringException(value, LocalDateTime.class, "发布时间必须为无时区后缀的上海时间字符串");
}
}
}
public record ManagedProjectView(
ProjectView project,
String moderationStatus,
@@ -0,0 +1,67 @@
package com.linkerbot.vibemake.common;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
/** 两端分页测试使用同一组资源、时间和并列值,预期顺序独立指定。 */
public final class ProjectListingFixtures {
private ProjectListingFixtures() {}
public record Fixture(
List<String> createdOrder, List<String> publishedOrder, List<String> resourcesOrder) {}
public static Fixture create(DataSource source, String templateCode) throws SQLException {
LocalDateTime base = LocalDateTime.of(2026, 10, 1, 10, 30);
List<String> codes = new ArrayList<>();
try (Connection connection = source.getConnection();
PreparedStatement insert = connection.prepareStatement("""
INSERT INTO project (project_code, owner_user_id, name, description,
project_type, gitea_owner, gitea_repo_name, repo_status, publish_status,
published_at, created_at, updated_at, model_glb_object_key,
assembly_json_object_key, walking_resources_prefix, model_parts_prefix)
SELECT ?, owner_user_id, ?, '', project_type, gitea_owner, ?, 'READY',
'PUBLISHED', ?, ?, ?, ?, ?, ?, ? FROM project WHERE project_code = ?
""")) {
for (int index = 0; index < 10; index++) {
String code = ProjectCodes.next();
codes.add(code);
LocalDateTime publishedAt = switch (index) {
case 0 -> base.plusDays(1);
case 1, 2 -> base.plusDays(2);
case 3, 9 -> null;
case 8 -> base.plusDays(4);
default -> base.plusDays(3);
};
String prefix = "/project-resources/" + code + "/";
insert.setString(1, code);
insert.setString(2, "排序测试 " + index);
insert.setString(3, "p_" + code);
insert.setObject(4, publishedAt);
insert.setObject(5, base.plusDays(index));
insert.setObject(6, base.plusDays(index));
insert.setString(7, index == 4 || index >= 8 ? "" : prefix + "model.glb");
insert.setString(8, index == 5 || index >= 8 ? "" : prefix + "assembly.json");
insert.setString(9, index == 6 || index >= 8 ? "" : prefix + "walking/");
insert.setString(10, index == 7 || index >= 8 ? "" : prefix + "parts/");
insert.setString(11, templateCode);
insert.executeUpdate();
}
}
return new Fixture(
order(codes, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0),
order(codes, 8, 7, 6, 5, 4, 2, 1, 0, 9, 3),
order(codes, 2, 1, 0, 3, 8, 7, 6, 5, 4, 9));
}
private static List<String> order(List<String> codes, int... indexes) {
List<String> result = new ArrayList<>();
for (int index : indexes) result.add(codes.get(index));
return List.copyOf(result);
}
}
@@ -1,5 +1,6 @@
package com.linkerbot.vibemake.service;
import com.linkerbot.vibemake.bean.AdminContracts.UpdateProjectInput;
import com.linkerbot.vibemake.bean.Contracts.ForkInput;
import com.linkerbot.vibemake.bean.Contracts.ProjectInput;
import com.linkerbot.vibemake.bean.Contracts.ProjectView;
@@ -28,6 +29,8 @@ public interface ProjectService {
ProjectView update(long userId, String code, ProjectInput input);
ProjectView updateByAdmin(String code, UpdateProjectInput input);
void delete(long userId, String code);
ProjectView publish(long userId, String code, String expectedSha);
@@ -189,12 +189,13 @@ public class AdminManagementService {
String keyword,
String publishStatus,
String repoStatus,
String moderationStatus) {
String moderationStatus,
String sort) {
requireAdmin();
ProjectSupport.pageCheck(page, size);
checkKeyword(keyword);
LambdaQueryWrapper<Project> query =
new LambdaQueryWrapper<Project>().eq(Project::getDeleted, false);
ProjectSort.fromParameter(sort).query().eq(Project::getDeleted, false);
query.select(Project.class, field -> !Set.of("urdfFiles", "modelPartsFiles", "walkingResourcesFiles")
.contains(field.getProperty()));
if (ownerCode != null) query.eq(Project::getOwnerUserId, user(ownerCode).getId());
@@ -213,7 +214,6 @@ public class AdminManagementService {
q.like(Project::getName, keyword)
.or()
.like(Project::getDescription, keyword));
query.orderByDesc(Project::getCreatedAt).orderByDesc(Project::getId);
Page<Project> result = mapper.selectPage(new Page<>(page, size), query);
List<Contracts.ProjectView> views = projects.views(result.getRecords(), null);
List<AdminContracts.ManagedProjectView> managed = new java.util.ArrayList<>();
@@ -4,9 +4,9 @@ import static com.linkerbot.vibemake.service.support.ProjectSupport.now;
import static com.linkerbot.vibemake.service.support.ProjectSupport.pageCheck;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.linkerbot.vibemake.bean.AdminContracts.UpdateProjectInput;
import com.linkerbot.vibemake.bean.Contracts.*;
import com.linkerbot.vibemake.bean.entity.*;
import com.linkerbot.vibemake.common.*;
@@ -26,6 +26,7 @@ import com.linkerbot.vibemake.service.state.RateLimits;
import com.linkerbot.vibemake.service.support.ProjectActors;
import com.linkerbot.vibemake.service.support.ProjectInputs;
import com.linkerbot.vibemake.service.support.ProjectLocks;
import com.linkerbot.vibemake.service.support.ProjectSort;
import lombok.RequiredArgsConstructor;
@@ -35,6 +36,7 @@ import org.springframework.beans.factory.ObjectProvider;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
@@ -252,22 +254,18 @@ public class ProjectServiceImpl implements ProjectService {
public PageResponse<ProjectView> list(
Long ownerId, String type, String keyword, long page, long size, Long currentUser) {
pageCheck(page, size);
// 社区优先展示已绑定 URDF 的项目,在数据库分页前排序。
// 社区资源齐全优先,工作区按创建时间排序;统一在数据库分页前排序。
LambdaQueryWrapper<Project> query =
new QueryWrapper<Project>()
.orderByDesc(
ownerId == null,
"CASE WHEN urdf_main_object_key <> '' THEN 1 ELSE 0 END")
.lambda()
(ownerId == null ? ProjectSort.RESOURCES_FIRST : ProjectSort.CREATED_AT_DESC)
.query()
.eq(Project::getDeleted, false);
// 列表不需要资源包清单,避免为每个项目读取可能很大的 JSON 字段。
query.select(Project.class, field -> !Set.of("urdfFiles", "modelPartsFiles", "walkingResourcesFiles")
.contains(field.getProperty()));
if (ownerId == null)
query.eq(Project::getRepoStatus, "READY")
.eq(Project::getPublishStatus, "PUBLISHED")
.orderByDesc(Project::getPublishedAt);
else query.eq(Project::getOwnerUserId, ownerId).orderByDesc(Project::getCreatedAt);
.eq(Project::getPublishStatus, "PUBLISHED");
else query.eq(Project::getOwnerUserId, ownerId);
if (type != null && !type.isBlank()) query.eq(Project::getProjectType, type);
if (keyword != null && !keyword.isBlank()) {
if (keyword.length() > 200) throw BusinessException.badRequest("关键词过长");
@@ -277,7 +275,6 @@ public class ProjectServiceImpl implements ProjectService {
.or()
.like(Project::getDescription, keyword));
}
query.orderByDesc(Project::getId);
Page<Project> result = projects.selectPage(new Page<>(page, size), query);
return new PageResponse<>(
views(result.getRecords(), currentUser), page, size, result.getTotal());
@@ -584,18 +581,33 @@ public class ProjectServiceImpl implements ProjectService {
@Override
public ProjectView update(long userId, String code, ProjectInput input) {
return update(userId, code, input, false, null);
}
@Override
public ProjectView updateByAdmin(String code, UpdateProjectInput input) {
if (!ProjectActors.isAdmin())
throw new BusinessException(403, "FORBIDDEN", "此操作仅限后台管理员");
return update(0, code, input.project(), input.isPublishedAtProvided(), input.getPublishedAt());
}
private ProjectView update(
long userId, String code, ProjectInput input,
boolean publishedAtProvided, LocalDateTime publishedAt) {
validateInput(input);
String coverUrl = normalizeCoverUrl(input.coverUrl());
return metadata(
userId,
code,
project -> {
LocalDateTime previousPublishedAt = project.getPublishedAt();
project.setName(input.name().trim());
project.setDescription(input.description() == null ? "" : input.description());
project.setProjectType(input.projectType());
if (input.coverUrl() != null) project.setCoverUrl(coverUrl);
if (publishedAtProvided) project.setPublishedAt(publishedAt);
project.setUpdatedAt(now());
// 显式 SET,确保空字符串清除封面时实际写入 NULL;省略字段仍保留旧值。
// 显式 SET,确保清空封面或发布时间时写入 NULL;省略字段仍保留旧值。
projects.update(
null,
new LambdaUpdateWrapper<Project>()
@@ -604,9 +616,13 @@ public class ProjectServiceImpl implements ProjectService {
.set(Project::getDescription, project.getDescription())
.set(Project::getProjectType, project.getProjectType())
.set(input.coverUrl() != null, Project::getCoverUrl, coverUrl)
.set(publishedAtProvided, Project::getPublishedAt, publishedAt)
.set(Project::getUpdatedAt, project.getUpdatedAt()));
if (input.coverUrl() != null)
log.info("更新项目封面 projectCode={} hasCover={}", code, coverUrl != null);
if (publishedAtProvided)
log.info("更新项目发布时间 projectCode={} previousPublishedAt={} publishedAt={}",
code, previousPublishedAt, publishedAt);
return view(project, userId);
});
}
@@ -640,7 +656,7 @@ public class ProjectServiceImpl implements ProjectService {
throw BusinessException.conflict("工作区版本已变化,请刷新后发布");
project.setPublishedCommitSha(head);
project.setPublishStatus("PUBLISHED");
project.setPublishedAt(now());
if (project.getPublishedAt() == null) project.setPublishedAt(now());
project.setUpdatedAt(now());
projects.updateById(project);
log.info("发布社区 projectCode={} commitSha={}", code, head);