mirror of
https://github.com/yibaiba/hideck.git
synced 2026-12-05 08:01:10 +00:00
fix: keep contact groups consistent across pages
This commit is contained in:
1 parent
ce25e7e427
commit
79e44bd0e7
9 files changed
+403
-73
No files matched your search
@@ -0,0 +1,121 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/yibaiba/hideck/internal/db"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type phoneContactBatchRequest struct {
|
||||
DeviceID string `json:"device_id"`
|
||||
Contacts []phoneContactRequest `json:"contacts"`
|
||||
Atomic bool `json:"atomic"`
|
||||
}
|
||||
|
||||
type phoneContactGroupRequest struct {
|
||||
ContactID string `json:"contact_id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
func (s *Server) handlePhoneContactsBatch(c *gin.Context) {
|
||||
var req phoneContactBatchRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "code": "invalid_json", "message": "请求格式不正确"})
|
||||
return
|
||||
}
|
||||
if len(req.Contacts) == 0 || len(req.Contacts) > maxContactBatch {
|
||||
writePhoneContactBatchSizeError(c, len(req.Contacts))
|
||||
return
|
||||
}
|
||||
region := s.phoneNumberRegion(req.DeviceID)
|
||||
inputs := phoneContactInputs(req.Contacts, region)
|
||||
if req.Atomic {
|
||||
saveAtomicPhoneContactBatch(c, inputs, region)
|
||||
return
|
||||
}
|
||||
imported, skipped, err := db.UpsertPhoneContactsWithRegion(c.Request.Context(), inputs, region)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"status": "error", "code": "contact_batch_failed", "message": "批量保存失败",
|
||||
})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"imported": imported, "skipped": skipped})
|
||||
}
|
||||
|
||||
func writePhoneContactBatchSizeError(c *gin.Context, size int) {
|
||||
if size == 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "code": "empty_batch", "message": "没有可添加的联系人"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"status": "error", "code": "batch_too_large", "message": "一次最多导入 5000 条",
|
||||
})
|
||||
}
|
||||
|
||||
func phoneContactInputs(contacts []phoneContactRequest, region string) []db.PhoneContactInput {
|
||||
inputs := make([]db.PhoneContactInput, 0, len(contacts))
|
||||
for _, item := range contacts {
|
||||
inputs = append(inputs, db.PhoneContactInput{
|
||||
Number: item.Number, Name: item.Name, Region: region,
|
||||
ContactID: item.ContactID, GroupKey: item.GroupKey,
|
||||
})
|
||||
}
|
||||
return inputs
|
||||
}
|
||||
|
||||
func saveAtomicPhoneContactBatch(c *gin.Context, inputs []db.PhoneContactInput, region string) {
|
||||
rows, err := db.UpsertPhoneContactBatchWithRegion(c.Request.Context(), inputs, region)
|
||||
if err != nil {
|
||||
c.JSON(phoneContactMutationStatus(err), gin.H{
|
||||
"status": "error", "code": "contact_batch_failed", "message": "批量保存失败",
|
||||
})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"imported": len(rows), "skipped": 0, "contacts": phoneContactIdentities(rows),
|
||||
})
|
||||
}
|
||||
|
||||
func phoneContactMutationStatus(err error) int {
|
||||
if errors.Is(err, db.ErrInvalidPhoneContact) {
|
||||
return http.StatusBadRequest
|
||||
}
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return http.StatusNotFound
|
||||
}
|
||||
if errors.Is(err, gorm.ErrInvalidDB) {
|
||||
return http.StatusServiceUnavailable
|
||||
}
|
||||
return http.StatusInternalServerError
|
||||
}
|
||||
|
||||
func (s *Server) handlePhoneContactGroupUpdate(c *gin.Context) {
|
||||
var req phoneContactGroupRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "code": "invalid_json", "message": "请求格式不正确"})
|
||||
return
|
||||
}
|
||||
rows, err := db.UpdatePhoneContactGroupName(c.Request.Context(), req.ContactID, req.Name)
|
||||
if err != nil {
|
||||
c.JSON(phoneContactMutationStatus(err), gin.H{
|
||||
"status": "error", "code": "contact_group_update_failed", "message": "更新联系人失败",
|
||||
})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"contacts": phoneContactIdentities(rows)})
|
||||
}
|
||||
|
||||
func (s *Server) handlePhoneContactGroupDelete(c *gin.Context) {
|
||||
numbers, err := db.DeletePhoneContactGroup(c.Request.Context(), c.Query("contact_id"))
|
||||
if err != nil {
|
||||
c.JSON(phoneContactMutationStatus(err), gin.H{
|
||||
"status": "error", "code": "contact_group_delete_failed", "message": "删除联系人失败",
|
||||
})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"deleted": len(numbers), "numbers": numbers})
|
||||
}
|
||||
@@ -30,6 +30,8 @@ func (s *Server) registerPhoneContactRoutes(api *gin.RouterGroup) {
|
||||
api.GET("/phone/contacts", s.handlePhoneContactsList)
|
||||
api.PUT("/phone/contacts", s.handlePhoneContactsUpsert)
|
||||
api.DELETE("/phone/contacts", s.handlePhoneContactsDelete)
|
||||
api.PUT("/phone/contacts/group", s.handlePhoneContactGroupUpdate)
|
||||
api.DELETE("/phone/contacts/group", s.handlePhoneContactGroupDelete)
|
||||
api.POST("/phone/contacts/batch", s.handlePhoneContactsBatch)
|
||||
api.POST("/phone/contacts/delete", s.handlePhoneContactsBatchDelete)
|
||||
api.GET("/phone/contacts/export", s.handlePhoneContactsExport)
|
||||
@@ -151,60 +153,11 @@ func (s *Server) phoneNumberRegion(deviceID string) string {
|
||||
return s.pool.PhoneNumberRegion(deviceID)
|
||||
}
|
||||
|
||||
type phoneContactBatchRequest struct {
|
||||
DeviceID string `json:"device_id"`
|
||||
Contacts []phoneContactRequest `json:"contacts"`
|
||||
}
|
||||
|
||||
type phoneContactDeleteRequest struct {
|
||||
DeviceID string `json:"device_id"`
|
||||
Numbers []string `json:"numbers"`
|
||||
}
|
||||
|
||||
func (s *Server) handlePhoneContactsBatch(c *gin.Context) {
|
||||
var req phoneContactBatchRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "code": "invalid_json", "message": "请求格式不正确"})
|
||||
return
|
||||
}
|
||||
if len(req.Contacts) == 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "code": "empty_batch", "message": "没有可添加的联系人"})
|
||||
return
|
||||
}
|
||||
if len(req.Contacts) > maxContactBatch {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "code": "batch_too_large", "message": "一次最多导入 5000 条"})
|
||||
return
|
||||
}
|
||||
region := s.phoneNumberRegion(req.DeviceID)
|
||||
inputs := make([]db.PhoneContactInput, 0, len(req.Contacts))
|
||||
for _, item := range req.Contacts {
|
||||
inputs = append(inputs, db.PhoneContactInput{
|
||||
Number: item.Number, Name: item.Name, Region: region,
|
||||
ContactID: item.ContactID, GroupKey: item.GroupKey,
|
||||
})
|
||||
}
|
||||
rows, err := db.UpsertPhoneContactBatchWithRegion(c.Request.Context(), inputs, region)
|
||||
if err != nil {
|
||||
c.JSON(phoneContactBatchStatus(err), gin.H{
|
||||
"status": "error", "code": "contact_batch_failed", "message": "批量保存失败",
|
||||
})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"imported": len(rows), "skipped": 0, "contacts": phoneContactIdentities(rows),
|
||||
})
|
||||
}
|
||||
|
||||
func phoneContactBatchStatus(err error) int {
|
||||
if errors.Is(err, db.ErrInvalidPhoneContact) {
|
||||
return http.StatusBadRequest
|
||||
}
|
||||
if errors.Is(err, gorm.ErrInvalidDB) {
|
||||
return http.StatusServiceUnavailable
|
||||
}
|
||||
return http.StatusInternalServerError
|
||||
}
|
||||
|
||||
func phoneContactIdentities(rows []db.PhoneContact) []any {
|
||||
out := make([]any, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
|
||||
@@ -203,7 +203,7 @@ func TestPhoneContactsBatchReturnsOneAtomicGroup(t *testing.T) {
|
||||
server.registerPhoneContactRoutes(api)
|
||||
token := testSessionToken(t, "secret", time.Now().Add(time.Hour))
|
||||
|
||||
body, _ := json.Marshal(map[string]any{"contacts": []map[string]string{
|
||||
body, _ := json.Marshal(map[string]any{"atomic": true, "contacts": []map[string]string{
|
||||
{"number": "10000", "name": "客服", "group_key": "manual"},
|
||||
{"number": "10001", "name": "客服", "group_key": "manual"},
|
||||
}})
|
||||
@@ -229,6 +229,92 @@ func TestPhoneContactsBatchReturnsOneAtomicGroup(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPhoneContactsBatchKeepsPartialSuccessByDefault(t *testing.T) {
|
||||
router, token := newPhoneContactsTestRouter(t, "phone_contacts_partial_batch.db")
|
||||
body, _ := json.Marshal(map[string]any{"contacts": []map[string]string{
|
||||
{"number": "10000", "name": "有效"},
|
||||
{"number": "invalid", "name": "无效"},
|
||||
}})
|
||||
recorder := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/phone/contacts/batch", bytes.NewReader(body))
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
router.ServeHTTP(recorder, req)
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("batch status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
var result struct {
|
||||
Imported int `json:"imported"`
|
||||
Skipped int `json:"skipped"`
|
||||
}
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &result); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.Imported != 1 || result.Skipped != 1 {
|
||||
t.Fatalf("batch result = %+v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPhoneContactGroupRoutesAffectUnloadedNumbers(t *testing.T) {
|
||||
router, token := newPhoneContactsTestRouter(t, "phone_contacts_group_routes.db")
|
||||
rows, err := db.UpsertPhoneContactBatchWithRegion(t.Context(), []db.PhoneContactInput{
|
||||
{Number: "10000", Name: "旧名字", GroupKey: "person"},
|
||||
{Number: "10001", Name: "旧名字", GroupKey: "person"},
|
||||
}, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
updateBody, _ := json.Marshal(map[string]string{"contact_id": rows[0].ContactID, "name": "新名字"})
|
||||
updated := requestPhoneContactMutation(t, phoneContactMutationRequest{
|
||||
Router: router, Token: token, Method: http.MethodPut,
|
||||
Body: updateBody, Target: "/api/phone/contacts/group",
|
||||
})
|
||||
if updated.Code != http.StatusOK || !bytes.Contains(updated.Body.Bytes(), []byte("新名字")) {
|
||||
t.Fatalf("update status=%d body=%s", updated.Code, updated.Body.String())
|
||||
}
|
||||
deleted := requestPhoneContactMutation(t, phoneContactMutationRequest{
|
||||
Router: router, Token: token, Method: http.MethodDelete,
|
||||
Target: "/api/phone/contacts/group?contact_id=" + rows[0].ContactID,
|
||||
})
|
||||
if deleted.Code != http.StatusOK || !bytes.Contains(deleted.Body.Bytes(), []byte(`"deleted":2`)) {
|
||||
t.Fatalf("delete status=%d body=%s", deleted.Code, deleted.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func newPhoneContactsTestRouter(t *testing.T, databaseName string) (http.Handler, string) {
|
||||
t.Helper()
|
||||
previous := db.DB
|
||||
if err := db.Init(filepath.Join(t.TempDir(), databaseName)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { db.DB = previous })
|
||||
gin.SetMode(gin.TestMode)
|
||||
server := &Server{auth: config.WebConfig{Username: "admin", Password: "secret"}}
|
||||
router := gin.New()
|
||||
api := router.Group("/api")
|
||||
api.Use(server.authMiddleware())
|
||||
server.registerPhoneContactRoutes(api)
|
||||
return router, testSessionToken(t, "secret", time.Now().Add(time.Hour))
|
||||
}
|
||||
|
||||
type phoneContactMutationRequest struct {
|
||||
Router http.Handler
|
||||
Token string
|
||||
Method string
|
||||
Body []byte
|
||||
Target string
|
||||
}
|
||||
|
||||
func requestPhoneContactMutation(t *testing.T, input phoneContactMutationRequest) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
recorder := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(input.Method, input.Target, bytes.NewReader(input.Body))
|
||||
req.Header.Set("Authorization", "Bearer "+input.Token)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
input.Router.ServeHTTP(recorder, req)
|
||||
return recorder
|
||||
}
|
||||
|
||||
type contactsPageResponse struct {
|
||||
Contacts []map[string]any `json:"contacts"`
|
||||
Total int `json:"total"`
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func UpdatePhoneContactGroupName(ctx context.Context, contactID, name string) ([]PhoneContact, error) {
|
||||
contactID = strings.TrimSpace(contactID)
|
||||
name = strings.TrimSpace(name)
|
||||
if !validPhoneContactID(contactID) || name == "" {
|
||||
return nil, ErrInvalidPhoneContact
|
||||
}
|
||||
if DB == nil {
|
||||
return nil, gorm.ErrInvalidDB
|
||||
}
|
||||
var rows []PhoneContact
|
||||
err := DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Where("contact_id = ?", contactID).Find(&rows).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return gorm.ErrRecordNotFound
|
||||
}
|
||||
result := tx.Model(&PhoneContact{}).Where("contact_id = ?", contactID).Updates(map[string]any{
|
||||
"name": name, "updated_at": time.Now(),
|
||||
})
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
rows = rows[:0]
|
||||
return tx.Where("contact_id = ?", contactID).
|
||||
Order("updated_at DESC, number ASC").Find(&rows).Error
|
||||
})
|
||||
return rows, err
|
||||
}
|
||||
|
||||
func DeletePhoneContactGroup(ctx context.Context, contactID string) ([]string, error) {
|
||||
contactID = strings.TrimSpace(contactID)
|
||||
if !validPhoneContactID(contactID) {
|
||||
return nil, ErrInvalidPhoneContact
|
||||
}
|
||||
if DB == nil {
|
||||
return nil, gorm.ErrInvalidDB
|
||||
}
|
||||
var rows []PhoneContact
|
||||
err := DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Where("contact_id = ?", contactID).Find(&rows).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return gorm.ErrRecordNotFound
|
||||
}
|
||||
return tx.Where("contact_id = ?", contactID).Delete(&PhoneContact{}).Error
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
numbers := make([]string, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
numbers = append(numbers, row.Number)
|
||||
}
|
||||
return numbers, nil
|
||||
}
|
||||
@@ -122,3 +122,37 @@ func TestPhoneContactStrictBatchIsAtomicAndSharesGroupID(t *testing.T) {
|
||||
t.Fatalf("rolled-back contact lookup error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPhoneContactGroupUpdateAndDeleteAffectEveryNumber(t *testing.T) {
|
||||
database, err := gorm.Open(sqlite.Open(filepath.Join(t.TempDir(), "contact-group.db")), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := database.AutoMigrate(&PhoneContact{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
previous := DB
|
||||
DB = database
|
||||
t.Cleanup(func() { DB = previous })
|
||||
|
||||
rows, err := UpsertPhoneContactBatchWithRegion(t.Context(), []PhoneContactInput{
|
||||
{Number: "10000", Name: "旧名字", GroupKey: "person"},
|
||||
{Number: "10001", Name: "旧名字", GroupKey: "person"},
|
||||
{Number: "10002", Name: "其他联系人"},
|
||||
}, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
updated, err := UpdatePhoneContactGroupName(t.Context(), rows[0].ContactID, "新名字")
|
||||
if err != nil || len(updated) != 2 || updated[0].Name != "新名字" || updated[1].Name != "新名字" {
|
||||
t.Fatalf("updated contacts=%+v err=%v", updated, err)
|
||||
}
|
||||
deleted, err := DeletePhoneContactGroup(t.Context(), rows[0].ContactID)
|
||||
if err != nil || len(deleted) != 2 {
|
||||
t.Fatalf("deleted numbers=%v err=%v", deleted, err)
|
||||
}
|
||||
remaining, err := ListPhoneContacts(t.Context())
|
||||
if err != nil || len(remaining) != 1 || remaining[0].Number != "10002" {
|
||||
t.Fatalf("remaining contacts=%+v err=%v", remaining, err)
|
||||
}
|
||||
}
|
||||
@@ -167,6 +167,12 @@ function contactGroupKey(item: PhoneIdentity) {
|
||||
return item.contact_id || `number:${item.number}`
|
||||
}
|
||||
|
||||
function contactGroupID(group: ContactGroup) {
|
||||
const contactId = String(group.contactId || '').trim()
|
||||
if (!contactId) throw new Error('联系人缺少稳定 ID,无法修改整个联系人')
|
||||
return contactId
|
||||
}
|
||||
|
||||
function handleOpenChange(open: boolean) {
|
||||
emit('update:modelValue', open)
|
||||
}
|
||||
@@ -295,6 +301,7 @@ async function saveManual() {
|
||||
|
||||
async function addNumberToGroup(group: ContactGroup) {
|
||||
try {
|
||||
const contactId = contactGroupID(group)
|
||||
const { value } = await ElMessageBox.prompt(`给「${group.name}」再加一个号码`, '添加号码', {
|
||||
...overlayDialog,
|
||||
confirmButtonText: '添加',
|
||||
@@ -304,7 +311,7 @@ async function addNumberToGroup(group: ContactGroup) {
|
||||
})
|
||||
const number = normalizePhoneContactNumber(value)
|
||||
const ident = await phoneContactsService.save({
|
||||
number, name: group.name, deviceId: props.deviceId, contactId: group.contactId
|
||||
number, name: group.name, deviceId: props.deviceId, contactId
|
||||
})
|
||||
identities.upsertLocal(ident, number, props.deviceId)
|
||||
expanded.value = group.key
|
||||
@@ -317,6 +324,7 @@ async function addNumberToGroup(group: ContactGroup) {
|
||||
|
||||
async function editGroup(group: ContactGroup) {
|
||||
try {
|
||||
const contactId = contactGroupID(group)
|
||||
const { value } = await ElMessageBox.prompt('保存后,来电和短信通知会显示这个名字', '改联系人', {
|
||||
...overlayDialog,
|
||||
confirmButtonText: '保存',
|
||||
@@ -326,12 +334,8 @@ async function editGroup(group: ContactGroup) {
|
||||
inputValidator: (v) => !!String(v || '').trim() || '请填写名字'
|
||||
})
|
||||
const name = String(value).trim()
|
||||
const saved = await phoneContactsService.saveMany(group.items.map((item) => ({
|
||||
number: item.number, name, contactId: group.contactId
|
||||
})), props.deviceId)
|
||||
saved.forEach((ident, index) => {
|
||||
identities.upsertLocal(ident, group.items[index].number, props.deviceId)
|
||||
})
|
||||
const saved = await phoneContactsService.updateGroup(contactId, name)
|
||||
identities.applyContactGroupUpdate(saved)
|
||||
ElMessage.success({ message: '已更新联系人', zIndex: 5100 })
|
||||
} catch (error) {
|
||||
if (error === 'cancel' || error === 'close') return
|
||||
@@ -340,12 +344,10 @@ async function editGroup(group: ContactGroup) {
|
||||
}
|
||||
|
||||
async function deleteGroup(group: ContactGroup) {
|
||||
const count = group.items.length
|
||||
try {
|
||||
const contactId = contactGroupID(group)
|
||||
await ElMessageBox.confirm(
|
||||
count > 1
|
||||
? `确定删除「${group.name}」的 ${count} 个号码?删除后,来电和短信会重新只显示号码。`
|
||||
: `确定删除「${group.name}」?删除后,来电和短信会重新只显示号码。`,
|
||||
`确定删除「${group.name}」及其所有号码?删除后,来电和短信会重新只显示号码。`,
|
||||
'删除联系人',
|
||||
{
|
||||
...overlayDialog,
|
||||
@@ -355,7 +357,7 @@ async function deleteGroup(group: ContactGroup) {
|
||||
distinguishCancelAndClose: true
|
||||
}
|
||||
)
|
||||
await identities.removeContacts(group.items.map((item) => item.number), props.deviceId)
|
||||
await identities.removeContactGroup(contactId)
|
||||
ElMessage.success({ message: '已删除联系人', zIndex: 5100 })
|
||||
} catch (error) {
|
||||
if (error === 'cancel' || error === 'close') return
|
||||
|
||||
@@ -138,14 +138,9 @@ async function loadCurrentContactPage(offset: number) {
|
||||
|
||||
function replaceContactRows(page: PhoneContactsPage) {
|
||||
cacheRevision++
|
||||
if (!page.hasMore) {
|
||||
const currentNumbers = new Set(page.contacts.map((row) => row.number))
|
||||
for (const [key, value] of cache) {
|
||||
if (value.name && !currentNumbers.has(value.number)) cache.set(key, withoutContactName(value))
|
||||
}
|
||||
}
|
||||
contacts.splice(0, contacts.length, ...page.contacts)
|
||||
for (const row of page.contacts) rememberWithoutList(row)
|
||||
if (!page.hasMore) reconcileContactNameCache(page.contacts)
|
||||
contactsState.total = page.total
|
||||
contactsState.nextOffset = page.nextOffset
|
||||
contactsState.hasMore = page.hasMore
|
||||
@@ -157,11 +152,22 @@ function appendContactRows(page: PhoneContactsPage) {
|
||||
const rows = page.contacts.filter((row) => !loaded.has(row.number))
|
||||
contacts.push(...rows)
|
||||
for (const row of rows) rememberWithoutList(row)
|
||||
if (!page.hasMore) {
|
||||
cacheRevision++
|
||||
reconcileContactNameCache(contacts)
|
||||
}
|
||||
contactsState.total = page.total
|
||||
contactsState.nextOffset = page.nextOffset
|
||||
contactsState.hasMore = page.hasMore
|
||||
}
|
||||
|
||||
function reconcileContactNameCache(rows: readonly PhoneIdentity[]) {
|
||||
const currentNumbers = new Set(rows.map((row) => row.number))
|
||||
for (const [key, value] of cache) {
|
||||
if (value.name && !currentNumbers.has(value.number)) cache.set(key, withoutContactName(value))
|
||||
}
|
||||
}
|
||||
|
||||
function loadMoreContacts() {
|
||||
if (!contactsState.loaded) return ensureContacts()
|
||||
if (contactsState.loading) return contactsLoadPromise || Promise.resolve(contacts)
|
||||
@@ -209,14 +215,43 @@ async function removeContacts(numbers: string[], deviceId = '') {
|
||||
}).filter(Boolean)
|
||||
if (!targets.length) return
|
||||
const deleted = await phoneContactsService.removeMany(targets, deviceId)
|
||||
removeLocalContacts(targets, deleted)
|
||||
}
|
||||
|
||||
function applyContactGroupUpdate(rows: readonly PhoneIdentity[]) {
|
||||
if (!rows.length) return
|
||||
cacheRevision++
|
||||
const drop = new Set(targets)
|
||||
const updated = new Map(rows.map((row) => [row.number, row]))
|
||||
for (const [alias, value] of cache) {
|
||||
const replacement = updated.get(value.number)
|
||||
if (replacement) cache.set(alias, replacement)
|
||||
}
|
||||
for (const row of rows) rememberWithoutList(row)
|
||||
const loadedCount = contacts.length
|
||||
const reordered = [...rows, ...contacts.filter((item) => !updated.has(item.number))]
|
||||
contacts.splice(0, contacts.length, ...reordered.slice(0, loadedCount))
|
||||
contactsState.nextOffset = contacts.length
|
||||
contactsState.hasMore = contactsState.nextOffset < contactsState.total
|
||||
}
|
||||
|
||||
async function removeContactGroup(contactId: string) {
|
||||
const result = await phoneContactsService.removeGroup(contactId)
|
||||
removeLocalContacts(result.numbers, result.deleted)
|
||||
}
|
||||
|
||||
function removeLocalContacts(numbers: readonly string[], deleted: number) {
|
||||
cacheRevision++
|
||||
const drop = new Set(numbers)
|
||||
const loadedDeleted = contacts.filter((item) => drop.has(item.number)).length
|
||||
for (let i = contacts.length - 1; i >= 0; i--) {
|
||||
if (drop.has(contacts[i].number)) contacts.splice(i, 1)
|
||||
}
|
||||
contactsState.total = Math.max(0, contactsState.total - deleted)
|
||||
contactsState.nextOffset = Math.max(0, contactsState.nextOffset - loadedDeleted)
|
||||
contactsState.nextOffset = Math.min(
|
||||
contactsState.total,
|
||||
Math.max(0, contactsState.nextOffset - loadedDeleted)
|
||||
)
|
||||
contactsState.hasMore = contactsState.nextOffset < contactsState.total
|
||||
for (const [alias, value] of cache) {
|
||||
if (drop.has(value.number)) cache.set(alias, withoutContactName(value))
|
||||
}
|
||||
@@ -248,6 +283,8 @@ const phoneIdentity = {
|
||||
ensureContacts,
|
||||
removeContact,
|
||||
removeContacts,
|
||||
applyContactGroupUpdate,
|
||||
removeContactGroup,
|
||||
titleFor,
|
||||
subtitleFor
|
||||
}
|
||||
|
||||
@@ -99,6 +99,7 @@ export const phoneContactsService = {
|
||||
async saveMany(contacts: readonly PhoneContactSave[], deviceId = ''): Promise<PhoneIdentity[]> {
|
||||
const res = await api.post('/phone/contacts/batch', {
|
||||
device_id: deviceId || undefined,
|
||||
atomic: true,
|
||||
contacts: contacts.map((contact) => ({
|
||||
number: contact.number,
|
||||
name: contact.name,
|
||||
@@ -111,6 +112,30 @@ export const phoneContactsService = {
|
||||
}
|
||||
return (res.data.contacts as PhoneIdentity[]).map(normalizeIdentity)
|
||||
},
|
||||
async updateGroup(contactId: string, name: string): Promise<PhoneIdentity[]> {
|
||||
const res = await api.put('/phone/contacts/group', {
|
||||
contact_id: contactId,
|
||||
name
|
||||
})
|
||||
const contacts = res.data?.contacts
|
||||
if (!Array.isArray(contacts) || contacts.length === 0 || contacts.some((contact) =>
|
||||
typeof contact?.number !== 'string' || !contact.number || contact.contact_id !== contactId)) {
|
||||
throw new Error('更新联系人响应不完整')
|
||||
}
|
||||
return (contacts as PhoneIdentity[]).map(normalizeIdentity)
|
||||
},
|
||||
async removeGroup(contactId: string): Promise<{ deleted: number; numbers: string[] }> {
|
||||
const res = await api.delete('/phone/contacts/group', {
|
||||
params: { contact_id: contactId }
|
||||
})
|
||||
const deleted = Number(res.data?.deleted)
|
||||
const numbers = res.data?.numbers
|
||||
if (!Number.isInteger(deleted) || deleted < 1 || !Array.isArray(numbers) ||
|
||||
numbers.length !== deleted || numbers.some((number) => typeof number !== 'string' || !number.trim())) {
|
||||
throw new Error('删除联系人响应不完整')
|
||||
}
|
||||
return { deleted, numbers: [...numbers] }
|
||||
},
|
||||
async remove(number: string, deviceId = ''): Promise<void> {
|
||||
await api.delete('/phone/contacts', {
|
||||
params: { number, device_id: deviceId || undefined }
|
||||
|
||||
@@ -151,7 +151,8 @@ test('contacts load on scroll and keep drag import discoverable', () => {
|
||||
assert.match(contactsDrawer, /继续向下滚动加载更多/)
|
||||
assert.match(contactsDrawer, /支持将 vcf \/ csv 拖到此处导入/)
|
||||
assert.match(contactsPanel, /identities\.contactsTotal/)
|
||||
assert.match(phoneIdentity, /if \(!page\.hasMore\) \{[\s\S]*!currentNumbers\.has\(value\.number\)/)
|
||||
assert.match(phoneIdentity, /if \(!page\.hasMore\) reconcileContactNameCache\(page\.contacts\)/)
|
||||
assert.match(phoneIdentity, /appendContactRows\([\s\S]*reconcileContactNameCache\(contacts\)/)
|
||||
})
|
||||
|
||||
test('contact import behavior is shared and exposes list refresh failures', () => {
|
||||
@@ -168,10 +169,14 @@ test('contact import behavior is shared and exposes list refresh failures', () =
|
||||
test('contacts are grouped by persistent identity instead of display name', () => {
|
||||
assert.match(contactService, /contact_id\?: string/)
|
||||
assert.match(contactsDrawer, /return item\.contact_id \|\| `number:\$\{item\.number\}`/)
|
||||
assert.match(contactsDrawer, /contactId: group\.contactId/)
|
||||
assert.match(contactsDrawer, /contactId = contactGroupID\(group\)/)
|
||||
assert.match(contactService, /async saveMany\([\s\S]*\/phone\/contacts\/batch/)
|
||||
assert.match(contactService, /atomic: true/)
|
||||
assert.match(contactsDrawer, /saveMany\(numbers\.map/)
|
||||
assert.match(contactsDrawer, /saveMany\(group\.items\.map/)
|
||||
assert.match(contactService, /async updateGroup\([\s\S]*\/phone\/contacts\/group/)
|
||||
assert.match(contactService, /async removeGroup\([\s\S]*\/phone\/contacts\/group/)
|
||||
assert.match(contactsDrawer, /updateGroup\(contactId, name\)/)
|
||||
assert.match(contactsDrawer, /removeContactGroup\(contactId\)/)
|
||||
assert.doesNotMatch(contactsDrawer, /index\.get\(name\)/)
|
||||
})
|
||||
|
||||
|
||||
Reference in new issue
Block a user