feat: 支持家庭邀请和成员权限管理
This commit is contained in:
parent
1928ed55d3
commit
8d029d6d66
|
|
@ -23,6 +23,7 @@ Compose 的 `local` profile 带 `owner`、`viewer`、`other` 三个演示用户
|
||||||
|
|
||||||
| 资源 | 操作 |
|
| 资源 | 操作 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
|
| `/members`、`/invitations` | 所有者查看成员、调整权限、移除成员和管理一次性邀请。 [家庭邀请与成员权限](../docs/architecture/household-access.md) |
|
||||||
| `/locations` | 列表、新建、移动位置树与归档。 |
|
| `/locations` | 列表、新建、移动位置树与归档。 |
|
||||||
| `/items` | 新建、搜索、详情、修改、归档。修改、移位和归档需带当前版本。 |
|
| `/items` | 新建、搜索、详情、修改、归档。修改、移位和归档需带当前版本。 |
|
||||||
| `/items/{id}/moves`、`/relations`、`/preference` | 移位、关联和个人收藏评分。 |
|
| `/items/{id}/moves`、`/relations`、`/preference` | 移位、关联和个人收藏评分。 |
|
||||||
|
|
@ -35,6 +36,6 @@ Compose 的 `local` profile 带 `owner`、`viewer`、`other` 三个演示用户
|
||||||
|
|
||||||
## 验收与排错
|
## 验收与排错
|
||||||
|
|
||||||
- 家庭建档使用 `POST /api/households`,请求体为 `{"name":"家庭名称"}`。创建者在同一事务成为 OWNER。用返回的 `Location` 查询家庭详情。
|
- 家庭建档使用 `POST /api/households`,请求体为 `{"name":"家庭名称"}`,可传 `displayName`。创建者在同一事务成为 OWNER。用返回的 `Location` 查询家庭详情。受邀者登录后使用 `POST /api/households/invitations/redeem` 兑换。
|
||||||
- 录入状态进入 `NEEDS_REVIEW` 后,草稿创建者可调用 `POST /api/households/{household}/operations/{operation}/retry`。返回 `202` 时继续查询同一操作号。当前操作最多支持启动一次额外恢复窗口。
|
- 录入状态进入 `NEEDS_REVIEW` 后,草稿创建者可调用 `POST /api/households/{household}/operations/{operation}/retry`。返回 `202` 时继续查询同一操作号。当前操作最多支持启动一次额外恢复窗口。
|
||||||
- 业务覆盖、受限的功能和实际复现命令见 [后端验收](../docs/testing/backend-readiness.md) 与 [部署和监控](../docs/deployment/observability.md)。
|
- 业务覆盖、受限的功能和实际复现命令见 [后端验收](../docs/testing/backend-readiness.md) 与 [部署和监控](../docs/deployment/observability.md)。
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,47 @@
|
||||||
|
package com.tutudog.itematlas.inventory;
|
||||||
|
|
||||||
|
import static org.springframework.http.HttpStatus.*;
|
||||||
|
|
||||||
|
import java.util.UUID;
|
||||||
|
import org.springframework.jdbc.core.simple.JdbcClient;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
class HouseholdAccess {
|
||||||
|
private final JdbcClient db;
|
||||||
|
|
||||||
|
HouseholdAccess(JdbcClient db) { this.db = db; }
|
||||||
|
|
||||||
|
String role(UUID household, String actor) {
|
||||||
|
return db.sql("SELECT role FROM household_member WHERE household_id=:id AND subject=:actor")
|
||||||
|
.param("id", household).param("actor", actor).query(String.class).optional()
|
||||||
|
.orElseThrow(HouseholdAccess::missing);
|
||||||
|
}
|
||||||
|
|
||||||
|
String lockMember(UUID household, String actor) {
|
||||||
|
db.sql("""
|
||||||
|
SELECT h.id FROM household h JOIN household_member m ON m.household_id=h.id
|
||||||
|
WHERE h.id=:id AND m.subject=:actor FOR UPDATE OF h
|
||||||
|
""").param("id", household).param("actor", actor).query(UUID.class).optional()
|
||||||
|
.orElseThrow(HouseholdAccess::missing);
|
||||||
|
// The role can change while waiting for the household lock. Read it again after acquiring the lock.
|
||||||
|
return role(household, actor);
|
||||||
|
}
|
||||||
|
|
||||||
|
void requireWrite(UUID household, String actor) {
|
||||||
|
if ("VIEWER".equals(lockMember(household, actor))) {
|
||||||
|
throw new ResponseStatusException(FORBIDDEN, "当前角色只有查看权限");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void requireOwner(String role) {
|
||||||
|
if (!"OWNER".equals(role)) {
|
||||||
|
throw new ResponseStatusException(FORBIDDEN, "只有家庭所有者可以管理成员");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static ResponseStatusException missing() {
|
||||||
|
return new ResponseStatusException(NOT_FOUND, "家庭不存在");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,76 @@
|
||||||
|
package com.tutudog.itematlas.inventory;
|
||||||
|
|
||||||
|
import static com.tutudog.itematlas.inventory.HouseholdDtos.*;
|
||||||
|
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.security.Principal;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
import org.springframework.http.CacheControl;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
class HouseholdController {
|
||||||
|
private static final String ROOT = "/api/households";
|
||||||
|
private static final String FAMILY = ROOT + "/{household}";
|
||||||
|
private final HouseholdService service;
|
||||||
|
|
||||||
|
HouseholdController(HouseholdService service) { this.service = service; }
|
||||||
|
|
||||||
|
@GetMapping(ROOT)
|
||||||
|
List<Household> list(Principal user) { return service.households(user.getName()); }
|
||||||
|
|
||||||
|
@PostMapping(ROOT)
|
||||||
|
ResponseEntity<Household> create(Principal user, @RequestBody @Valid HouseholdInput input) {
|
||||||
|
var household = service.createHousehold(user.getName(), input);
|
||||||
|
return ResponseEntity.created(URI.create(ROOT + "/" + household.id())).body(household);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping(FAMILY)
|
||||||
|
Household detail(@PathVariable UUID household, Principal user) {
|
||||||
|
return service.household(household, user.getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping(FAMILY + "/members")
|
||||||
|
List<Member> members(@PathVariable UUID household, Principal user) {
|
||||||
|
return service.members(household, user.getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping(FAMILY + "/members/{member}/role")
|
||||||
|
Member changeRole(@PathVariable UUID household, @PathVariable UUID member, Principal user,
|
||||||
|
@RequestBody @Valid RoleInput input) {
|
||||||
|
return service.changeRole(household, user.getName(), member, input.role());
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping(FAMILY + "/members/{member}")
|
||||||
|
ResponseEntity<Void> removeMember(@PathVariable UUID household, @PathVariable UUID member, Principal user) {
|
||||||
|
service.removeMember(household, user.getName(), member);
|
||||||
|
return ResponseEntity.noContent().build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping(FAMILY + "/invitations")
|
||||||
|
List<Invitation> invitations(@PathVariable UUID household, Principal user) {
|
||||||
|
return service.invitations(household, user.getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping(FAMILY + "/invitations")
|
||||||
|
ResponseEntity<CreatedInvitation> createInvitation(@PathVariable UUID household, Principal user,
|
||||||
|
@RequestBody @Valid RoleInput input) {
|
||||||
|
var invitation = service.createInvitation(household, user.getName(), input.role());
|
||||||
|
return ResponseEntity.status(201).cacheControl(CacheControl.noStore()).body(invitation);
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping(FAMILY + "/invitations/{invitation}")
|
||||||
|
ResponseEntity<Void> revokeInvitation(@PathVariable UUID household, @PathVariable UUID invitation,
|
||||||
|
Principal user) {
|
||||||
|
service.revokeInvitation(household, user.getName(), invitation);
|
||||||
|
return ResponseEntity.noContent().build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping(ROOT + "/invitations/redeem")
|
||||||
|
Household redeem(Principal user, @RequestBody @Valid RedeemInput input) {
|
||||||
|
return service.redeem(user.getName(), input);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,20 @@
|
||||||
|
package com.tutudog.itematlas.inventory;
|
||||||
|
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import jakarta.validation.constraints.NotNull;
|
||||||
|
import jakarta.validation.constraints.Pattern;
|
||||||
|
import jakarta.validation.constraints.Size;
|
||||||
|
import java.time.OffsetDateTime;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
final class HouseholdDtos {
|
||||||
|
record Household(UUID id, String name, String role) {}
|
||||||
|
record HouseholdInput(@NotBlank @Size(max = 100) String name, @Size(max = 80) String displayName) {}
|
||||||
|
enum MemberRole { EDITOR, VIEWER }
|
||||||
|
record RoleInput(@NotNull MemberRole role) {}
|
||||||
|
record Member(UUID id, String displayName, String role) {}
|
||||||
|
record Invitation(UUID id, MemberRole role, OffsetDateTime expiresAt) {}
|
||||||
|
record CreatedInvitation(UUID id, MemberRole role, OffsetDateTime expiresAt, String code) {}
|
||||||
|
record RedeemInput(@NotBlank @Pattern(regexp = "[A-Za-z0-9_-]{43}") String code,
|
||||||
|
@NotBlank @Size(max = 80) String displayName) {}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,206 @@
|
||||||
|
package com.tutudog.itematlas.inventory;
|
||||||
|
|
||||||
|
import static com.tutudog.itematlas.inventory.HouseholdDtos.*;
|
||||||
|
import static org.springframework.http.HttpStatus.*;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
import java.security.SecureRandom;
|
||||||
|
import java.time.OffsetDateTime;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
import org.springframework.jdbc.core.RowMapper;
|
||||||
|
import org.springframework.jdbc.core.simple.JdbcClient;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
class HouseholdService {
|
||||||
|
private static final int MAX_ACTIVE_INVITATIONS = 20;
|
||||||
|
private static final SecureRandom RANDOM = new SecureRandom();
|
||||||
|
private static final RowMapper<Member> MEMBER = (rs, row) -> new Member(
|
||||||
|
rs.getObject("member_id", UUID.class), rs.getString("display_name"), rs.getString("role"));
|
||||||
|
private static final RowMapper<Invitation> INVITATION = (rs, row) -> new Invitation(
|
||||||
|
rs.getObject("id", UUID.class), MemberRole.valueOf(rs.getString("role")),
|
||||||
|
rs.getObject("expires_at", OffsetDateTime.class));
|
||||||
|
private final JdbcClient db;
|
||||||
|
private final HouseholdAccess access;
|
||||||
|
|
||||||
|
HouseholdService(JdbcClient db, HouseholdAccess access) {
|
||||||
|
this.db = db;
|
||||||
|
this.access = access;
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Household> households(String actor) {
|
||||||
|
return db.sql("""
|
||||||
|
SELECT h.id,h.name,m.role FROM household h JOIN household_member m ON m.household_id=h.id
|
||||||
|
WHERE m.subject=:actor ORDER BY h.name,h.id
|
||||||
|
""").param("actor", actor).query((rs, row) -> new Household(
|
||||||
|
rs.getObject("id", UUID.class), rs.getString("name"), rs.getString("role"))).list();
|
||||||
|
}
|
||||||
|
|
||||||
|
Household household(UUID id, String actor) {
|
||||||
|
return db.sql("""
|
||||||
|
SELECT h.name,m.role FROM household h JOIN household_member m ON m.household_id=h.id
|
||||||
|
WHERE h.id=:id AND m.subject=:actor
|
||||||
|
""").param("id", id).param("actor", actor)
|
||||||
|
.query((rs, row) -> new Household(id, rs.getString(1), rs.getString(2))).optional()
|
||||||
|
.orElseThrow(HouseholdAccess::missing);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
Household createHousehold(String actor, HouseholdInput input) {
|
||||||
|
UUID id = UUID.randomUUID();
|
||||||
|
String name = input.name().strip();
|
||||||
|
String displayName = input.displayName() == null || input.displayName().isBlank()
|
||||||
|
? "家庭所有者" : input.displayName().strip();
|
||||||
|
db.sql("INSERT INTO household(id,name) VALUES (:id,:name)")
|
||||||
|
.param("id", id).param("name", name).update();
|
||||||
|
addMember(id, actor, displayName, "OWNER");
|
||||||
|
return new Household(id, name, "OWNER");
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Member> members(UUID household, String actor) {
|
||||||
|
access.requireOwner(access.role(household, actor));
|
||||||
|
return db.sql("""
|
||||||
|
SELECT member_id,display_name,role FROM household_member WHERE household_id=:household
|
||||||
|
ORDER BY (role='OWNER') DESC,display_name,member_id
|
||||||
|
""").param("household", household).query(MEMBER).list();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
Member changeRole(UUID household, String actor, UUID memberId, MemberRole role) {
|
||||||
|
access.requireOwner(access.lockMember(household, actor));
|
||||||
|
editableSubject(household, memberId);
|
||||||
|
return db.sql("""
|
||||||
|
UPDATE household_member SET role=:role
|
||||||
|
WHERE household_id=:household AND member_id=:id RETURNING member_id,display_name,role
|
||||||
|
""").param("role", role.name()).param("household", household).param("id", memberId)
|
||||||
|
.query(MEMBER).single();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
void removeMember(UUID household, String actor, UUID memberId) {
|
||||||
|
access.requireOwner(access.lockMember(household, actor));
|
||||||
|
String subject = editableSubject(household, memberId);
|
||||||
|
db.sql("DELETE FROM item_preference WHERE household_id=:household AND subject=:subject")
|
||||||
|
.param("household", household).param("subject", subject).update();
|
||||||
|
db.sql("DELETE FROM household_member WHERE household_id=:household AND member_id=:id")
|
||||||
|
.param("household", household).param("id", memberId).update();
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Invitation> invitations(UUID household, String actor) {
|
||||||
|
access.requireOwner(access.role(household, actor));
|
||||||
|
return db.sql("""
|
||||||
|
SELECT id,role,expires_at FROM household_invitation WHERE household_id=:household
|
||||||
|
AND expires_at>clock_timestamp() AND revoked_at IS NULL AND redeemed_member_id IS NULL
|
||||||
|
ORDER BY expires_at,id
|
||||||
|
""").param("household", household).query(INVITATION).list();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
CreatedInvitation createInvitation(UUID household, String actor, MemberRole role) {
|
||||||
|
access.requireOwner(access.lockMember(household, actor));
|
||||||
|
db.sql("DELETE FROM household_invitation WHERE household_id=:household AND expires_at<now()-interval '30 days'")
|
||||||
|
.param("household", household).update();
|
||||||
|
int active = db.sql("""
|
||||||
|
SELECT count(*) FROM household_invitation WHERE household_id=:household
|
||||||
|
AND expires_at>clock_timestamp() AND revoked_at IS NULL AND redeemed_member_id IS NULL
|
||||||
|
""").param("household", household).query(Integer.class).single();
|
||||||
|
if (active >= MAX_ACTIVE_INVITATIONS) {
|
||||||
|
throw new ResponseStatusException(CONFLICT, "未使用的邀请已达上限");
|
||||||
|
}
|
||||||
|
|
||||||
|
byte[] random = new byte[32];
|
||||||
|
RANDOM.nextBytes(random);
|
||||||
|
String code = Base64.getUrlEncoder().withoutPadding().encodeToString(random);
|
||||||
|
var invitation = db.sql("""
|
||||||
|
INSERT INTO household_invitation(id,household_id,role,token_hash,expires_at)
|
||||||
|
VALUES (:id,:household,:role,:hash,clock_timestamp()+interval '24 hours')
|
||||||
|
RETURNING id,role,expires_at
|
||||||
|
""").param("id", UUID.randomUUID()).param("household", household).param("role", role.name())
|
||||||
|
.param("hash", digest(code)).query(INVITATION).single();
|
||||||
|
return new CreatedInvitation(invitation.id(), invitation.role(), invitation.expiresAt(), code);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
void revokeInvitation(UUID household, String actor, UUID invitationId) {
|
||||||
|
access.requireOwner(access.lockMember(household, actor));
|
||||||
|
int changed = db.sql("""
|
||||||
|
UPDATE household_invitation SET revoked_at=coalesce(revoked_at,clock_timestamp())
|
||||||
|
WHERE id=:id AND household_id=:household AND redeemed_member_id IS NULL
|
||||||
|
""").param("id", invitationId).param("household", household).update();
|
||||||
|
if (changed == 0) { throw inviteUnavailable(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
Household redeem(String actor, RedeemInput input) {
|
||||||
|
byte[] hash = digest(input.code());
|
||||||
|
UUID household = db.sql("SELECT household_id FROM household_invitation WHERE token_hash=:hash")
|
||||||
|
.param("hash", hash).query(UUID.class).optional().orElseThrow(HouseholdService::inviteUnavailable);
|
||||||
|
// Every membership mutation locks the household first, including join and owner revocation.
|
||||||
|
String name = db.sql("SELECT name FROM household WHERE id=:id FOR UPDATE")
|
||||||
|
.param("id", household).query(String.class).optional().orElseThrow(HouseholdService::inviteUnavailable);
|
||||||
|
var invitation = db.sql("""
|
||||||
|
SELECT id,role,redeemed_member_id,expires_at>clock_timestamp() AND revoked_at IS NULL AS valid
|
||||||
|
FROM household_invitation WHERE household_id=:household AND token_hash=:hash
|
||||||
|
""").param("household", household).param("hash", hash).query((rs, row) -> new Redemption(
|
||||||
|
rs.getObject("id", UUID.class), rs.getString("role"),
|
||||||
|
rs.getObject("redeemed_member_id", UUID.class), rs.getBoolean("valid")))
|
||||||
|
.optional().orElseThrow(HouseholdService::inviteUnavailable);
|
||||||
|
if (!invitation.valid()) { throw inviteUnavailable(); }
|
||||||
|
var membership = db.sql("""
|
||||||
|
SELECT member_id,display_name,role FROM household_member WHERE household_id=:household AND subject=:actor
|
||||||
|
""").param("household", household).param("actor", actor).query(MEMBER).optional().orElse(null);
|
||||||
|
|
||||||
|
if (invitation.redeemedMemberId() != null) {
|
||||||
|
if (membership != null && invitation.redeemedMemberId().equals(membership.id())) {
|
||||||
|
return new Household(household, name, membership.role());
|
||||||
|
}
|
||||||
|
throw inviteUnavailable();
|
||||||
|
}
|
||||||
|
if (membership != null) {
|
||||||
|
throw new ResponseStatusException(CONFLICT, "已加入此家庭");
|
||||||
|
}
|
||||||
|
UUID memberId = addMember(household, actor, input.displayName().strip(), invitation.role());
|
||||||
|
db.sql("UPDATE household_invitation SET redeemed_member_id=:member WHERE id=:id")
|
||||||
|
.param("member", memberId).param("id", invitation.id()).update();
|
||||||
|
return new Household(household, name, invitation.role());
|
||||||
|
}
|
||||||
|
|
||||||
|
private UUID addMember(UUID household, String actor, String displayName, String role) {
|
||||||
|
return db.sql("""
|
||||||
|
INSERT INTO household_member(household_id,subject,role,display_name)
|
||||||
|
VALUES (:household,:actor,:role,:name) RETURNING member_id
|
||||||
|
""").param("household", household).param("actor", actor).param("role", role)
|
||||||
|
.param("name", displayName).query(UUID.class).single();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String editableSubject(UUID household, UUID memberId) {
|
||||||
|
return db.sql("""
|
||||||
|
SELECT subject,role FROM household_member WHERE household_id=:household AND member_id=:id
|
||||||
|
""").param("household", household).param("id", memberId).query((rs, row) -> {
|
||||||
|
if ("OWNER".equals(rs.getString("role"))) {
|
||||||
|
throw new ResponseStatusException(CONFLICT, "家庭所有者不能通过成员管理修改或移除");
|
||||||
|
}
|
||||||
|
return rs.getString("subject");
|
||||||
|
}).optional().orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "成员不存在"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] digest(String code) {
|
||||||
|
try {
|
||||||
|
return MessageDigest.getInstance("SHA-256").digest(code.getBytes(StandardCharsets.US_ASCII));
|
||||||
|
} catch (NoSuchAlgorithmException ex) {
|
||||||
|
throw new IllegalStateException("SHA-256 is required by the Java platform", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ResponseStatusException inviteUnavailable() {
|
||||||
|
return new ResponseStatusException(NOT_FOUND, "邀请不可用");
|
||||||
|
}
|
||||||
|
|
||||||
|
private record Redemption(UUID id, String role, UUID redeemedMemberId, boolean valid) {}
|
||||||
|
}
|
||||||
|
|
@ -20,20 +20,6 @@ class InventoryController {
|
||||||
|
|
||||||
InventoryController(InventoryService service) { this.service = service; }
|
InventoryController(InventoryService service) { this.service = service; }
|
||||||
|
|
||||||
@GetMapping("/api/households")
|
|
||||||
List<Household> households(Principal user) { return service.households(user.getName()); }
|
|
||||||
|
|
||||||
@PostMapping("/api/households")
|
|
||||||
ResponseEntity<Household> createHousehold(Principal user, @RequestBody @Valid HouseholdInput input) {
|
|
||||||
var household = service.createHousehold(user.getName(), input);
|
|
||||||
return ResponseEntity.created(URI.create("/api/households/" + household.id())).body(household);
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping(FAMILY)
|
|
||||||
Household getHousehold(@PathVariable UUID household, Principal user) {
|
|
||||||
return service.household(household, user.getName());
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping(FAMILY + "/locations")
|
@GetMapping(FAMILY + "/locations")
|
||||||
List<Location> locations(@PathVariable UUID household, Principal user) {
|
List<Location> locations(@PathVariable UUID household, Principal user) {
|
||||||
return service.locations(household, user.getName());
|
return service.locations(household, user.getName());
|
||||||
|
|
|
||||||
|
|
@ -12,8 +12,6 @@ import java.util.List;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
final class InventoryDtos {
|
final class InventoryDtos {
|
||||||
record Household(UUID id, String name, String role) {}
|
|
||||||
record HouseholdInput(@NotBlank @Size(max = 100) String name) {}
|
|
||||||
record Location(UUID id, UUID parentId, String name, String path) {}
|
record Location(UUID id, UUID parentId, String name, String path) {}
|
||||||
record LocationInput(@NotBlank @Size(max = 100) String name, UUID parentId) {}
|
record LocationInput(@NotBlank @Size(max = 100) String name, UUID parentId) {}
|
||||||
record Item(UUID id, String name, int quantity, String notes, UUID locationId,
|
record Item(UUID id, String name, int quantity, String notes, UUID locationId,
|
||||||
|
|
|
||||||
|
|
@ -31,63 +31,21 @@ class InventoryService {
|
||||||
WHERE i.household_id=:household AND i.archived_at IS NULL
|
WHERE i.household_id=:household AND i.archived_at IS NULL
|
||||||
""";
|
""";
|
||||||
private final JdbcClient db;
|
private final JdbcClient db;
|
||||||
|
private final HouseholdAccess access;
|
||||||
|
|
||||||
InventoryService(JdbcClient db) { this.db = db; }
|
InventoryService(JdbcClient db, HouseholdAccess access) {
|
||||||
|
this.db = db;
|
||||||
List<Household> households(String actor) {
|
this.access = access;
|
||||||
return db.sql("""
|
|
||||||
SELECT h.id, h.name, m.role FROM household h JOIN household_member m ON m.household_id=h.id
|
|
||||||
WHERE m.subject=:actor ORDER BY h.name,h.id
|
|
||||||
""").param("actor", actor).query((rs, row) -> new Household(
|
|
||||||
rs.getObject("id", UUID.class), rs.getString("name"), rs.getString("role"))).list();
|
|
||||||
}
|
|
||||||
|
|
||||||
Household household(UUID id, String actor) {
|
|
||||||
return db.sql("""
|
|
||||||
SELECT h.name,m.role FROM household h JOIN household_member m ON m.household_id=h.id
|
|
||||||
WHERE h.id=:id AND m.subject=:actor
|
|
||||||
""").param("id", id).param("actor", actor)
|
|
||||||
.query((rs, row) -> new Household(id, rs.getString(1), rs.getString(2))).optional()
|
|
||||||
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "家庭不存在"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional
|
|
||||||
Household createHousehold(String actor, HouseholdInput input) {
|
|
||||||
UUID id = UUID.randomUUID();
|
|
||||||
String name = input.name().strip();
|
|
||||||
db.sql("INSERT INTO household(id,name) VALUES (:id,:name)")
|
|
||||||
.param("id", id).param("name", name).update();
|
|
||||||
db.sql("INSERT INTO household_member(household_id,subject,role) VALUES (:id,:actor,'OWNER')")
|
|
||||||
.param("id", id).param("actor", actor).update();
|
|
||||||
return new Household(id, name, "OWNER");
|
|
||||||
}
|
|
||||||
|
|
||||||
String role(UUID household, String actor) {
|
|
||||||
return db.sql("SELECT role FROM household_member WHERE household_id=:id AND subject=:actor")
|
|
||||||
.param("id", household).param("actor", actor).query(String.class).optional()
|
|
||||||
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "家庭不存在"));
|
|
||||||
}
|
|
||||||
|
|
||||||
private void requireWrite(UUID household, String actor) {
|
|
||||||
// Serialize writes within a household so a move cannot race an archive or a tree change.
|
|
||||||
String membership = db.sql("""
|
|
||||||
SELECT m.role FROM household h JOIN household_member m ON m.household_id=h.id
|
|
||||||
WHERE h.id=:id AND m.subject=:actor FOR UPDATE OF h,m
|
|
||||||
""").param("id", household).param("actor", actor).query(String.class).optional()
|
|
||||||
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "家庭不存在"));
|
|
||||||
if ("VIEWER".equals(membership)) {
|
|
||||||
throw new ResponseStatusException(FORBIDDEN, "当前角色只有查看权限");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
List<Location> locations(UUID household, String actor) {
|
List<Location> locations(UUID household, String actor) {
|
||||||
role(household, actor);
|
access.role(household, actor);
|
||||||
return db.sql("SELECT * FROM location_path WHERE household_id=:household ORDER BY path,id")
|
return db.sql("SELECT * FROM location_path WHERE household_id=:household ORDER BY path,id")
|
||||||
.param("household", household).query(LOCATION).list();
|
.param("household", household).query(LOCATION).list();
|
||||||
}
|
}
|
||||||
|
|
||||||
Location location(UUID household, String actor, UUID id) {
|
Location location(UUID household, String actor, UUID id) {
|
||||||
role(household, actor);
|
access.role(household, actor);
|
||||||
return location(household, id);
|
return location(household, id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -99,7 +57,7 @@ class InventoryService {
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
Location saveLocation(UUID household, String actor, UUID id, LocationInput input) {
|
Location saveLocation(UUID household, String actor, UUID id, LocationInput input) {
|
||||||
requireWrite(household, actor);
|
access.requireWrite(household, actor);
|
||||||
UUID parent = input.parentId();
|
UUID parent = input.parentId();
|
||||||
if (parent != null) {
|
if (parent != null) {
|
||||||
location(household, parent);
|
location(household, parent);
|
||||||
|
|
@ -125,7 +83,7 @@ class InventoryService {
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
void archiveLocation(UUID household, String actor, UUID id) {
|
void archiveLocation(UUID household, String actor, UUID id) {
|
||||||
requireWrite(household, actor);
|
access.requireWrite(household, actor);
|
||||||
location(household, id);
|
location(household, id);
|
||||||
boolean occupied = db.sql("""
|
boolean occupied = db.sql("""
|
||||||
SELECT EXISTS (SELECT FROM location WHERE household_id=:household AND parent_id=:id
|
SELECT EXISTS (SELECT FROM location WHERE household_id=:household AND parent_id=:id
|
||||||
|
|
@ -138,7 +96,7 @@ class InventoryService {
|
||||||
}
|
}
|
||||||
|
|
||||||
List<Item> items(UUID household, String actor, String q, int limit, int offset) {
|
List<Item> items(UUID household, String actor, String q, int limit, int offset) {
|
||||||
role(household, actor);
|
access.role(household, actor);
|
||||||
return db.sql(SELECT_ITEMS + """
|
return db.sql(SELECT_ITEMS + """
|
||||||
AND (strpos(lower(i.name),lower(:q)) > 0 OR strpos(lower(p.path),lower(:q)) > 0
|
AND (strpos(lower(i.name),lower(:q)) > 0 OR strpos(lower(p.path),lower(:q)) > 0
|
||||||
OR EXISTS (SELECT FROM item_alias a WHERE a.household_id=i.household_id
|
OR EXISTS (SELECT FROM item_alias a WHERE a.household_id=i.household_id
|
||||||
|
|
@ -154,7 +112,7 @@ class InventoryService {
|
||||||
}
|
}
|
||||||
|
|
||||||
Detail detail(UUID household, String actor, UUID id) {
|
Detail detail(UUID household, String actor, UUID id) {
|
||||||
role(household, actor);
|
access.role(household, actor);
|
||||||
Item item = item(household, id);
|
Item item = item(household, id);
|
||||||
var moves = db.sql("""
|
var moves = db.sql("""
|
||||||
SELECT from_path,to_path,moved_at FROM item_move
|
SELECT from_path,to_path,moved_at FROM item_move
|
||||||
|
|
@ -180,7 +138,7 @@ class InventoryService {
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
Item create(UUID household, String actor, ItemInput input) {
|
Item create(UUID household, String actor, ItemInput input) {
|
||||||
requireWrite(household, actor);
|
access.requireWrite(household, actor);
|
||||||
location(household, input.locationId());
|
location(household, input.locationId());
|
||||||
return insertItem(household, input);
|
return insertItem(household, input);
|
||||||
}
|
}
|
||||||
|
|
@ -199,7 +157,7 @@ class InventoryService {
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
Item edit(UUID household, String actor, UUID id, ItemEdit input) {
|
Item edit(UUID household, String actor, UUID id, ItemEdit input) {
|
||||||
requireWrite(household, actor);
|
access.requireWrite(household, actor);
|
||||||
Item current = item(household, id);
|
Item current = item(household, id);
|
||||||
checkVersion(current, input.version());
|
checkVersion(current, input.version());
|
||||||
db.sql("""
|
db.sql("""
|
||||||
|
|
@ -223,7 +181,7 @@ class InventoryService {
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
Item move(UUID household, String actor, UUID id, MoveInput input) {
|
Item move(UUID household, String actor, UUID id, MoveInput input) {
|
||||||
requireWrite(household, actor);
|
access.requireWrite(household, actor);
|
||||||
Item current = item(household, id);
|
Item current = item(household, id);
|
||||||
checkVersion(current, input.version());
|
checkVersion(current, input.version());
|
||||||
Location destination = location(household, input.locationId());
|
Location destination = location(household, input.locationId());
|
||||||
|
|
@ -240,7 +198,7 @@ class InventoryService {
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
void archive(UUID household, String actor, UUID id, int version) {
|
void archive(UUID household, String actor, UUID id, int version) {
|
||||||
requireWrite(household, actor);
|
access.requireWrite(household, actor);
|
||||||
checkVersion(item(household, id), version);
|
checkVersion(item(household, id), version);
|
||||||
db.sql("""
|
db.sql("""
|
||||||
UPDATE item SET archived_at=now(),version=version+1 WHERE household_id=:household AND id=:id
|
UPDATE item SET archived_at=now(),version=version+1 WHERE household_id=:household AND id=:id
|
||||||
|
|
@ -249,7 +207,7 @@ class InventoryService {
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
void link(UUID household, String actor, UUID id, RelationInput input) {
|
void link(UUID household, String actor, UUID id, RelationInput input) {
|
||||||
requireWrite(household, actor);
|
access.requireWrite(household, actor);
|
||||||
item(household, id);
|
item(household, id);
|
||||||
item(household, input.itemId());
|
item(household, input.itemId());
|
||||||
if (id.equals(input.itemId())) { throw new ResponseStatusException(BAD_REQUEST, "不能关联自身"); }
|
if (id.equals(input.itemId())) { throw new ResponseStatusException(BAD_REQUEST, "不能关联自身"); }
|
||||||
|
|
@ -263,7 +221,7 @@ class InventoryService {
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
void unlink(UUID household, String actor, UUID id, UUID related) {
|
void unlink(UUID household, String actor, UUID id, UUID related) {
|
||||||
requireWrite(household, actor);
|
access.requireWrite(household, actor);
|
||||||
item(household, id);
|
item(household, id);
|
||||||
db.sql("DELETE FROM item_relation WHERE household_id=:household AND item_id=:id AND related_id=:related")
|
db.sql("DELETE FROM item_relation WHERE household_id=:household AND item_id=:id AND related_id=:related")
|
||||||
.param("household", household).param("id", id).param("related", related).update();
|
.param("household", household).param("id", id).param("related", related).update();
|
||||||
|
|
@ -271,7 +229,7 @@ class InventoryService {
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
Preference preference(UUID household, String actor, UUID id, Preference preference) {
|
Preference preference(UUID household, String actor, UUID id, Preference preference) {
|
||||||
role(household, actor);
|
access.lockMember(household, actor);
|
||||||
item(household, id);
|
item(household, id);
|
||||||
db.sql("""
|
db.sql("""
|
||||||
INSERT INTO item_preference(household_id,item_id,subject,favorite,rating,note)
|
INSERT INTO item_preference(household_id,item_id,subject,favorite,rating,note)
|
||||||
|
|
@ -299,7 +257,7 @@ class InventoryService {
|
||||||
return new DeliveryResult(previous);
|
return new DeliveryResult(previous);
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
requireWrite(household, delivery.actor());
|
access.requireWrite(household, delivery.actor());
|
||||||
for (ItemInput input : delivery.items()) { location(household, input.locationId()); }
|
for (ItemInput input : delivery.items()) { location(household, input.locationId()); }
|
||||||
} catch (ResponseStatusException rejected) {
|
} catch (ResponseStatusException rejected) {
|
||||||
db.sql("UPDATE delivered_operation SET outcome='REJECTED' WHERE id=:id")
|
db.sql("UPDATE delivered_operation SET outcome='REJECTED' WHERE id=:id")
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,21 @@
|
||||||
|
ALTER TABLE household_member
|
||||||
|
ADD COLUMN member_id uuid NOT NULL DEFAULT gen_random_uuid(),
|
||||||
|
ADD COLUMN display_name text NOT NULL DEFAULT '家庭成员' CHECK (length(display_name) BETWEEN 1 AND 80),
|
||||||
|
ADD UNIQUE (household_id, member_id);
|
||||||
|
|
||||||
|
UPDATE household_member SET display_name='家庭所有者' WHERE role='OWNER';
|
||||||
|
|
||||||
|
CREATE INDEX item_preference_member ON item_preference(household_id, subject);
|
||||||
|
|
||||||
|
CREATE TABLE household_invitation (
|
||||||
|
id uuid PRIMARY KEY,
|
||||||
|
household_id uuid NOT NULL REFERENCES household(id),
|
||||||
|
role text NOT NULL CHECK (role IN ('EDITOR', 'VIEWER')),
|
||||||
|
token_hash bytea NOT NULL UNIQUE CHECK (octet_length(token_hash)=32),
|
||||||
|
expires_at timestamptz NOT NULL,
|
||||||
|
revoked_at timestamptz,
|
||||||
|
redeemed_member_id uuid,
|
||||||
|
CHECK (revoked_at IS NULL OR redeemed_member_id IS NULL)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX household_invitation_expiry ON household_invitation(household_id, expires_at);
|
||||||
|
|
@ -43,7 +43,8 @@ def call(method, path, payload=None, *, user="owner", status=200):
|
||||||
response = error
|
response = error
|
||||||
with response:
|
with response:
|
||||||
raw = response.read()
|
raw = response.read()
|
||||||
assert response.status == status, f"{method} {path} expected {status}, got {response.status}: {raw[:800]!r}"
|
summary = "invitation response omitted" if "/invitations" in path else repr(raw[:800])
|
||||||
|
assert response.status == status, f"{method} {path} expected {status}, got {response.status}: {summary}"
|
||||||
return json.loads(raw) if raw and "json" in response.headers.get("Content-Type", "") else None
|
return json.loads(raw) if raw and "json" in response.headers.get("Content-Type", "") else None
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -123,6 +124,86 @@ def verify_metrics(targets):
|
||||||
print("PASS Prometheus metrics on gateway, inventory and intake", flush=True)
|
print("PASS Prometheus metrics on gateway, inventory and intake", flush=True)
|
||||||
|
|
||||||
|
|
||||||
|
def verify_household_membership(family):
|
||||||
|
members_path = family + "/members"
|
||||||
|
invitations = family + "/invitations"
|
||||||
|
redeem_path = "/api/households/invitations/redeem"
|
||||||
|
owner, = call("GET", members_path, user="other")
|
||||||
|
assert set(owner) == {"id", "displayName", "role"} and owner["role"] == "OWNER"
|
||||||
|
call("GET", members_path, user="viewer", status=404)
|
||||||
|
call("POST", invitations, {"role": "VIEWER"}, user="viewer", status=404)
|
||||||
|
call("POST", invitations, {"role": "OWNER"}, user="other", status=400)
|
||||||
|
call("PUT", members_path + f"/{owner['id']}/role", {"role": "VIEWER"}, user="other", status=409)
|
||||||
|
call("DELETE", members_path + f"/{owner['id']}", user="other", status=409)
|
||||||
|
|
||||||
|
revoked = call("POST", invitations, {"role": "EDITOR"}, user="other", status=201)
|
||||||
|
call("DELETE", invitations + "/" + revoked["id"], user="other", status=204)
|
||||||
|
call("POST", redeem_path, {"code": revoked["code"], "displayName": "已撤销"}, user="viewer", status=404)
|
||||||
|
|
||||||
|
invite = call("POST", invitations, {"role": "VIEWER"}, user="other", status=201)
|
||||||
|
pending = call("GET", invitations, user="other")
|
||||||
|
assert pending == [{key: invite[key] for key in ("id", "role", "expiresAt")}]
|
||||||
|
call("POST", redeem_path, {"code": invite["code"], "displayName": "匿名"}, user=None, status=401)
|
||||||
|
call("POST", redeem_path, {"code": "invalid", "displayName": "格式错误"}, user="viewer", status=400)
|
||||||
|
|
||||||
|
def compete(user):
|
||||||
|
payload = {"code": invite["code"], "displayName": "受邀人 " + user}
|
||||||
|
try:
|
||||||
|
with urlopen(make_request("POST", redeem_path, payload, user), timeout=10) as response:
|
||||||
|
return user, response.status
|
||||||
|
except HTTPError as error:
|
||||||
|
with error:
|
||||||
|
return user, error.code
|
||||||
|
|
||||||
|
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
|
||||||
|
attempts = list(pool.map(compete, ["owner", "viewer"]))
|
||||||
|
assert sorted(status for _, status in attempts) == [200, 404], attempts
|
||||||
|
winner = next(user for user, status in attempts if status == 200)
|
||||||
|
loser = next(user for user, status in attempts if status == 404)
|
||||||
|
joined = call("POST", redeem_path, {"code": invite["code"], "displayName": "重试不改名"}, user=winner)
|
||||||
|
assert joined["id"] == family.rsplit("/", 1)[1] and joined["role"] == "VIEWER"
|
||||||
|
assert call("GET", invitations, user="other") == []
|
||||||
|
owner_after, member = call("GET", members_path, user="other")
|
||||||
|
assert owner_after == owner and member["displayName"] == "受邀人 " + winner
|
||||||
|
member_path = members_path + "/" + member["id"]
|
||||||
|
|
||||||
|
call("GET", family + "/items", user=winner)
|
||||||
|
call("GET", members_path, user=winner, status=403)
|
||||||
|
call("POST", family + "/locations", {"name": "只读不能写"}, user=winner, status=403)
|
||||||
|
assert call("PUT", member_path + "/role", {"role": "EDITOR"}, user="other")["role"] == "EDITOR"
|
||||||
|
place = call("POST", family + "/locations", {"name": "共享位置"}, user=winner, status=201)
|
||||||
|
item = call("POST", family + "/items", {"name": "共享物品", "locationId": place["id"], "quantity": 1},
|
||||||
|
user=winner, status=201)
|
||||||
|
item_path = family + "/items/" + item["id"]
|
||||||
|
call("PUT", item_path + "/preference", {"favorite": True, "rating": 5}, user=winner)
|
||||||
|
call("PUT", item_path + "/preference", {"favorite": True, "rating": 4}, user="other")
|
||||||
|
assert call("PUT", member_path + "/role", {"role": "VIEWER"}, user="other")["role"] == "VIEWER"
|
||||||
|
call("POST", family + "/drafts", {"text": "只读成员不能生成草稿"}, user=winner, status=403)
|
||||||
|
call("DELETE", member_path, user="other", status=204)
|
||||||
|
call("GET", item_path, user=winner, status=404)
|
||||||
|
call("POST", family + "/drafts", {"text": "移除后不能生成草稿"}, user=winner, status=404)
|
||||||
|
call("POST", redeem_path, {"code": invite["code"], "displayName": "不能再用"}, user=winner, status=404)
|
||||||
|
|
||||||
|
rejoin = call("POST", invitations, {"role": "VIEWER"}, user="other", status=201)
|
||||||
|
call("POST", redeem_path, {"code": rejoin["code"], "displayName": "再次受邀"}, user=winner)
|
||||||
|
assert call("GET", item_path, user=winner)["preference"]["rating"] is None
|
||||||
|
assert call("GET", item_path, user="other")["preference"]["rating"] == 4
|
||||||
|
_, new_member = call("GET", members_path, user="other")
|
||||||
|
assert new_member["id"] != member["id"]
|
||||||
|
call("DELETE", members_path + "/" + new_member["id"], user="other", status=204)
|
||||||
|
|
||||||
|
if dsn := os.environ.get("ATLAS_SMOKE_INVENTORY_DSN"):
|
||||||
|
expiring = call("POST", invitations, {"role": "EDITOR"}, user="other", status=201)
|
||||||
|
invite_id = str(uuid.UUID(expiring["id"]))
|
||||||
|
subprocess.run(
|
||||||
|
["psql", dsn, "-XAt", "-v", "ON_ERROR_STOP=1"], text=True, capture_output=True, check=True,
|
||||||
|
input=f"UPDATE household_invitation SET expires_at=now()-interval '1 second' WHERE id='{invite_id}';",
|
||||||
|
)
|
||||||
|
call("POST", redeem_path, {"code": expiring["code"], "displayName": "到期"}, user=loser, status=404)
|
||||||
|
assert call("GET", invitations, user="other") == []
|
||||||
|
print("PASS owner-only invitations, concurrent redemption, role changes and membership removal", flush=True)
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
ready()
|
ready()
|
||||||
call("GET", HOUSE + "/items", user=None, status=401)
|
call("GET", HOUSE + "/items", user=None, status=401)
|
||||||
|
|
@ -148,6 +229,7 @@ def main():
|
||||||
except HTTPError as error:
|
except HTTPError as error:
|
||||||
assert error.code == 403, error.code
|
assert error.code == 403, error.code
|
||||||
print("PASS authentication, household isolation and internal route boundary", flush=True)
|
print("PASS authentication, household isolation and internal route boundary", flush=True)
|
||||||
|
verify_household_membership(family_path)
|
||||||
|
|
||||||
study = location("书房 " + RUN)
|
study = location("书房 " + RUN)
|
||||||
entry = location("玄关 " + RUN)
|
entry = location("玄关 " + RUN)
|
||||||
|
|
|
||||||
|
|
@ -26,6 +26,7 @@ java -jar backend/gateway/target/app.jar > /tmp/atlas-gateway.log 2>&1 &
|
||||||
service_pids="$service_pids $!"
|
service_pids="$service_pids $!"
|
||||||
|
|
||||||
export ATLAS_SMOKE_INTAKE_DSN="postgresql://postgres@postgres/itematlas_intake"
|
export ATLAS_SMOKE_INTAKE_DSN="postgresql://postgres@postgres/itematlas_intake"
|
||||||
|
export ATLAS_SMOKE_INVENTORY_DSN="postgresql://postgres@postgres/itematlas_inventory"
|
||||||
export ATLAS_SMOKE_METRIC_TARGETS="http://127.0.0.1:8080,http://127.0.0.1:8081,http://127.0.0.1:8082"
|
export ATLAS_SMOKE_METRIC_TARGETS="http://127.0.0.1:8080,http://127.0.0.1:8081,http://127.0.0.1:8082"
|
||||||
if ! python3 backend/tests/smoke.py; then
|
if ! python3 backend/tests/smoke.py; then
|
||||||
tail -80 /tmp/atlas-inventory.log /tmp/atlas-intake.log /tmp/atlas-gateway.log
|
tail -80 /tmp/atlas-inventory.log /tmp/atlas-intake.log /tmp/atlas-gateway.log
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,30 @@
|
||||||
|
# 家庭邀请与成员权限
|
||||||
|
|
||||||
|
用户登录后可以创建家庭。所有者负责邀请、调整成员角色和移除成员。编辑者可修改物品与位置,查看者可查找物品和维护自己的收藏与评分。邀请时可选编辑者或查看者。所有者身份在建档时建立,现阶段的成员接口保留所有者记录。
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
以下 API 通过网关访问,使用与物品 API 相同的访问凭据。请求和响应使用 JSON。
|
||||||
|
|
||||||
|
| 请求 | 输入和结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| `POST /api/households` | `{"name":"家里","displayName":"阿峰"}`。显示名可省略。返回家庭及 OWNER 角色。 |
|
||||||
|
| `GET /api/households/{id}/members` | 所有者查看成员 ID、家庭内显示名和角色。 |
|
||||||
|
| `POST /api/households/{id}/invitations` | `{"role":"VIEWER"}` 或 `EDITOR`。返回邀请 ID、邀请码、角色和过期时间。 |
|
||||||
|
| `GET /api/households/{id}/invitations` | 所有者查看尚可兑换的邀请,返回 ID、角色和过期时间。 |
|
||||||
|
| `DELETE /api/households/{id}/invitations/{invitationId}` | 撤销尚未兑换的邀请,返回 `204`。 |
|
||||||
|
| `POST /api/households/invitations/redeem` | `{"code":"创建邀请时返回的值","displayName":"家庭内的名字"}`。返回家庭和当前角色。 |
|
||||||
|
| `PUT /api/households/{id}/members/{memberId}/role` | 所有者将普通成员设为 `EDITOR` 或 `VIEWER`,返回更新后的成员。 |
|
||||||
|
| `DELETE /api/households/{id}/members/{memberId}` | 所有者移除普通成员,返回 `204`。 |
|
||||||
|
|
||||||
|
邀请码 24 小时有效。所有者把一次性值发给受邀者,受邀者登录后把它放进请求体。服务端仅保存 SHA-256 摘要,包含明文的创建响应设为 `Cache-Control: no-store`。一个家庭最多有 20 条可兑换邀请。邀请码持有者可兑换,发布后应只在可信渠道分享。 [OWASP 单次令牌指南](https://cheatsheetseries.owasp.org/cheatsheets/Forgot_Password_Cheat_Sheet.html)
|
||||||
|
|
||||||
|
同一邀请只能建立一份成员身份。期限内同一受邀者重试,且原成员身份仍有效时,返回已有家庭和当前角色。其他人重放、邀请过期或撤销均返回 `404`。已经是成员的用户兑换新邀请会收到 `409`,该邀请码仍可给其他人。邀请、成员与物品路径对非成员返回 `404`,对缺少管理权限的成员返回 `403`。
|
||||||
|
|
||||||
|
## 事务和权限
|
||||||
|
|
||||||
|
成员变更和已有物品写入都持有同一家庭行锁。锁到后重新读取角色,避免等锁期间的降权被旧结果覆盖。兑换要在同一事务新增成员并消耗邀请。移除成员要在一个事务清除该成员在该家庭的个人评价与成员记录,物品和其他人的评价保留。再次加入会得到新的成员 ID。 [PostgreSQL 行锁](https://www.postgresql.org/docs/15/explicit-locking.html#LOCKING-ROWS)
|
||||||
|
|
||||||
|
业务服务按 JWT subject 判定成员权限。响应里的成员 ID 是家庭内的随机 UUID。公开列表使用家庭内显示名,OIDC subject 留在服务端。更改权限在事务提交后对后续请求生效,原 Token 可以继续用于其他有权限的家庭。录入服务查最新成员状态,后台投递在实际写入前也重验权限。
|
||||||
|
|
||||||
|
物品库 Flyway V3 为已有成员补 UUID 与显示名,并建立邀请表。现有家庭和业务数据继续按原 ID 使用。部署后核对迁移成功、邀请并发兑换以及使用同一 Token 的降权和撤权。应用回退按 Helm 操作,保留已应用的增量迁移。
|
||||||
|
|
@ -54,4 +54,4 @@ Spring Boot 负责服务本身,Spring Cloud 主要用 Gateway。正式部署
|
||||||
|
|
||||||
普通搜索、手工录入与模型生成分开设超时。录入服务每个实例保留一个本地模型调用槽,单机 Ollama 的推理容量需按实测配置。Worker 每次领取一条并退避重试,前端定期查状态。模型额度、队列容量告警和正式入口的速率限制分别跟踪。在容量测试后确定吞吐和延迟目标。
|
普通搜索、手工录入与模型生成分开设超时。录入服务每个实例保留一个本地模型调用槽,单机 Ollama 的推理容量需按实测配置。Worker 每次领取一条并退避重试,前端定期查状态。模型额度、队列容量告警和正式入口的速率限制分别跟踪。在容量测试后确定吞吐和延迟目标。
|
||||||
|
|
||||||
[需求与验收](../product/requirements.md) · [模型接入](ai-providers.md) · [两级缓存设计](cache.md) · [部署与发布](../deployment/overview.md) · [后端验收](../testing/backend-readiness.md)
|
[需求与验收](../product/requirements.md) · [家庭邀请与成员权限](household-access.md) · [模型接入](ai-providers.md) · [两级缓存设计](cache.md) · [部署与发布](../deployment/overview.md) · [后端验收](../testing/backend-readiness.md)
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@
|
||||||
|
|
||||||
| 编号 | 需求 | 验收 |
|
| 编号 | 需求 | 验收 |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| R01 | 家庭和角色 | 两户演示家庭的数据互相隔离。查看成员可以找物,写入接口按角色检查。 |
|
| R01 | 家庭和角色 | 两户数据互相隔离。所有者可签发和撤销邀请、调整普通成员角色及移除成员。两人同时兑换同一邀请时只有一人加入。查看者可找物,降权或移除后用原登录凭据也只能执行当前权限允许的请求。 |
|
||||||
| R02 | 多层位置 | 可以建立房间、柜子、收纳盒。同名位置显示完整路径。禁止把上级移动到子节点下,有活动物品或下级的位置归档前须先处理关联。 |
|
| R02 | 多层位置 | 可以建立房间、柜子、收纳盒。同名位置显示完整路径。禁止把上级移动到子节点下,有活动物品或下级的位置归档前须先处理关联。 |
|
||||||
| R03 | 物品和移位 | 可以新增、修改、移位和归档物品。移位后同时查到当前和原来的位置,用旧版本写入时提示冲突。 |
|
| R03 | 物品和移位 | 可以新增、修改、移位和归档物品。移位后同时查到当前和原来的位置,用旧版本写入时提示冲突。 |
|
||||||
| R04 | 搜索 | 可以按名称、别名和位置找物。结果带完整位置路径。 |
|
| R04 | 搜索 | 可以按名称、别名和位置找物。结果带完整位置路径。 |
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@
|
||||||
|
|
||||||
| 需求 | 当前 API 和证据 | 后续边界 |
|
| 需求 | 当前 API 和证据 | 后续边界 |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| R01 家庭和角色 | 已登录的用户创建家庭后成为 OWNER,家庭详情和用户可访问的家庭列表受 JWT subject 约束。冒烟覆盖两个家庭、查看者、投递服务账号和匿名请求。 | 成员邀请、角色维护和管理后台 API 待交付。 |
|
| R01 家庭和角色 | 已登录的用户创建家庭后成为 OWNER。真实数据库冒烟覆盖邀请撤销、到期和并发兑换,以及成员升级、降权和移除。同一访问凭据按数据库中的当前角色判断。 | 平台管理后台 API、所有者交接和客户端邀请界面另行交付。 |
|
||||||
| R02 多层位置 | 测试两处同名收纳盒、完整路径、位置详情、非法循环、存在子节点或物品时拒绝归档。 | 大位置树用真实容量样本分析 SQL。 |
|
| R02 多层位置 | 测试两处同名收纳盒、完整路径、位置详情、非法循环、存在子节点或物品时拒绝归档。 | 大位置树用真实容量样本分析 SQL。 |
|
||||||
| R03 物品和移位 | 新建、编辑、移位、归档和历史走真实 PostgreSQL。旧版本写入返回 409。 | 客户端需用刷新后的版本重新提交。 |
|
| R03 物品和移位 | 新建、编辑、移位、归档和历史走真实 PostgreSQL。旧版本写入返回 409。 | 客户端需用刷新后的版本重新提交。 |
|
||||||
| R04 搜索 | 对同一物品用别名和完整位置路径搜索,响应保持完整路径。 | 按数据量评估搜索索引和分页,先保留原生 SQL 基线。 |
|
| R04 搜索 | 对同一物品用别名和完整位置路径搜索,响应保持完整路径。 | 按数据量评估搜索索引和分页,先保留原生 SQL 基线。 |
|
||||||
|
|
@ -20,7 +20,7 @@
|
||||||
- 构建用 `mvn -B -ntp -f backend/pom.xml verify`。
|
- 构建用 `mvn -B -ntp -f backend/pom.xml verify`。
|
||||||
- CI 使用短生命周期 PostgreSQL 并执行 `deploy/local/ci-smoke.sh`。该脚本包含三个服务、真实数据库、模型缺省降级、重新投递和指标验收。
|
- CI 使用短生命周期 PostgreSQL 并执行 `deploy/local/ci-smoke.sh`。该脚本包含三个服务、真实数据库、模型缺省降级、重新投递和指标验收。
|
||||||
- 预发布用 Keycloak 签发的三个账号跑同一冒烟脚本,确认 OIDC、真实 Ollama、镜像摘要和应用日志。需要改数据库状态的故障注入在独立测试库运行。
|
- 预发布用 Keycloak 签发的三个账号跑同一冒烟脚本,确认 OIDC、真实 Ollama、镜像摘要和应用日志。需要改数据库状态的故障注入在独立测试库运行。
|
||||||
- 两个服务的数据按各自 Flyway 迁移版本维护。`V2__confirm_retry_budget.sql` 给已有记录补默认重试限额,新记录存可选 trace parent。第一轮切入新接口前等待旧录入 Pod 完成更新。老版本可读新增列的数据库,但回退时先确认新增恢复任务不在处理中。
|
- 两个服务的数据按各自 Flyway 迁移版本维护。录入库 V2 给已有记录补默认重试限额,新记录存可选 trace parent。物品库 V3 为已有成员补 UUID 与显示名,并建立邀请表。发布后用原账号检查成员角色、原有物品和迁移记录。
|
||||||
- 监控部署后查 Prometheus Targets 和 Outbox 指标,用操作号在 Loki 查日志,再看 Tempo 的对应 trace。详细步骤见 [监控部署](../deployment/observability.md)。
|
- 监控部署后查 Prometheus Targets 和 Outbox 指标,用操作号在 Loki 查日志,再看 Tempo 的对应 trace。详细步骤见 [监控部署](../deployment/observability.md)。
|
||||||
|
|
||||||
[需求与验收](../product/requirements.md) · [逐项测试用例](cases.md) · [交付和灰度](../deployment/backend-release.md)
|
[需求与验收](../product/requirements.md) · [逐项测试用例](cases.md) · [交付和灰度](../deployment/backend-release.md)
|
||||||
|
|
|
||||||
|
|
@ -17,5 +17,7 @@ R01–R08 对应[需求与验收](../product/requirements.md)。实现和当前
|
||||||
| TC-11 并发额度 | R07 | 剩余额度只够一次请求,两个请求同时预占。再模拟已接受请求的用量暂时未知。 | 只有符合额度的一次可以发起调用。未知用量保留待对账,不能提前释放给下一次调用。 |
|
| TC-11 并发额度 | R07 | 剩余额度只够一次请求,两个请求同时预占。再模拟已接受请求的用量暂时未知。 | 只有符合额度的一次可以发起调用。未知用量保留待对账,不能提前释放给下一次调用。 |
|
||||||
| TC-12 个人收藏和评分 | R08 | 两位成员给同一件物品不同的星级。其中一人取消收藏并清除评价。 | 两人评分相互独立。清除只影响当前成员,另一人的评价保留。 |
|
| TC-12 个人收藏和评分 | R08 | 两位成员给同一件物品不同的星级。其中一人取消收藏并清除评价。 | 两人评分相互独立。清除只影响当前成员,另一人的评价保留。 |
|
||||||
| TC-13 恢复演示数据 | 质量 | 从同一批次的备份恢复数据库和附件,打开一件有历史和关联的物品。 | 原位置、历史、关联和附件均可查看,正常访问仍受家庭权限保护。 |
|
| TC-13 恢复演示数据 | 质量 | 从同一批次的备份恢复数据库和附件,打开一件有历史和关联的物品。 | 原位置、历史、关联和附件均可查看,正常访问仍受家庭权限保护。 |
|
||||||
|
| TC-14 邀请兑换 | R01 | 所有者创建邀请码,两个账号同时兑换。再分别测试撤销和到期的邀请码。 | 只有一个账号加入。同一账号可重试,其他账号和无效邀请码返回 404。 |
|
||||||
|
| TC-15 成员权限变化 | R01 | 所有者将查看者升级为编辑者,创建共享物品后降权并移除。各次请求使用原登录凭据。 | 写权限随角色变化。被移除的成员无法读取共享物品或录入,另一个成员的评价仍保留。 |
|
||||||
|
|
||||||
[测试与演示计划](plan.md)
|
[测试与演示计划](plan.md)
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue