package com.example.rzgb.profile; import com.example.rzgb.auth.CurrentUser; import com.example.rzgb.common.*; import jakarta.validation.Valid; import java.sql.Timestamp; import java.time.Instant; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.security.core.Authentication; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; /** 档案是账号私有资源;悲观锁序列化首次创建,版本条件防止多页面覆盖。 */ @RestController @RequestMapping("/api/company-profile") public class ProfileController { private final JdbcTemplate jdbc; private final Json json; private final CurrentUser currentUser; public ProfileController(JdbcTemplate jdbc, Json json, CurrentUser currentUser) { this.jdbc = jdbc; this.json = json; this.currentUser = currentUser; } @GetMapping public CompanyProfile get(Authentication auth) { return read(currentUser.id(auth)); } private CompanyProfile read(String user) { var rows = jdbc.query("SELECT document FROM company_profile WHERE user_id=?", (rs, n) -> json.convert(rs.getString(1), CompanyProfile.class), user); return rows.isEmpty() ? CompanyProfile.empty() : rows.getFirst(); } @PutMapping @Transactional public CompanyProfile save(Authentication auth, @Valid @RequestBody CompanyProfile input) { if (input.matchWeights().total() <= 0) throw new ApiException(400, "INVALID_WEIGHTS", "四维权重不能全部为零"); String user = currentUser.id(auth); jdbc.queryForObject("SELECT id FROM app_user WHERE id=? FOR UPDATE", String.class, user); CompanyProfile previous = read(user); if (previous.version() != input.version()) throw new ApiException(409, "VERSION_CONFLICT", "档案已在其他页面更新,请刷新后重新编辑"); CompanyProfile saved = input.saved(previous.version() + 1, Instant.now()); if (previous.version() == 0) jdbc.update("INSERT INTO company_profile(user_id,document,version,completed,updated_at) VALUES(?,?,?,?,?)", user, json.write(saved), saved.version(), saved.completed(), Timestamp.from(saved.updatedAt())); else jdbc.update("UPDATE company_profile SET document=?,version=?,completed=?,updated_at=? WHERE user_id=?", json.write(saved), saved.version(), saved.completed(), Timestamp.from(saved.updatedAt()), user); return saved; } }